Your events table started small. Two years later it holds hundreds of millions of rows, the nightly cleanup job runs for hours, the indexes no longer fit in memory, and every query that touches "last week" still has to deal with an index that covers everything since launch.

Two words come up when people talk about fixing this: partitioning and sharding. They are often used as if they meant the same thing. They do not. Both split data into pieces, but they split it in different places, and they solve different problems.

  • Partitioning splits one logical table into smaller physical pieces inside one database server.
  • Sharding splits the data across several database servers, each holding part of the rows.

Get this distinction right and you will usually find that you need the first long before you need the second.

Partitioning: one server, many pieces

With partitioning, the application still sees a single table. Under the hood, the database stores the rows in several child tables called partitions, and it routes each row to the right partition based on a partition key.

PostgreSQL has built-in declarative partitioning. Here is the events table split by month:

CREATE TABLE events ( id bigint NOT NULL, created_at timestamptz NOT NULL, user_id bigint NOT NULL, payload jsonb ) PARTITION BY RANGE (created_at); CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01'); CREATE TABLE events_2026_12 PARTITION OF events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01'); 

An INSERT INTO events lands in the right monthly table. A query like this one:

SELECT count(*) FROM events WHERE created_at >= '2026-12-01' AND created_at < '2026-12-08'; 

only reads events_2026_12. The planner skips the other partitions entirely. This is called partition pruning, and it is the main reason partitioning speeds up queries.

There are three common ways to choose which partition a row goes to:

  • Range: by a range of values, usually time. Good for logs, events, orders, metrics.
  • List: by an explicit list of values, for example country IN ('DZ', 'MA', 'TN').
  • Hash: by a hash of the key, to spread rows evenly when there is no natural range.

MySQL, SQL Server and Oracle support the same ideas with their own syntax.

What partitioning buys you

  • Faster queries on the hot slice, when queries filter on the partition key and pruning kicks in.
  • Smaller indexes per partition, which are more likely to stay in memory.
  • Cheap data removal. Deleting a month of old data with DELETE touches millions of rows, creates a lot of dead tuples and bloats the table. With partitions you run DROP TABLE events_2024_01 (or detach it first) and the data is gone in a moment.
  • Easier maintenance: vacuum, reindex or archive one partition at a time.

What it does not buy you

All partitions live on the same machine. They share the same CPU, RAM, disk and connection limit. If your problem is that one server cannot handle the write rate or store the total data, partitioning does not fix it.

Sharding: many servers, each with part of the data

Sharding takes the same idea and moves it across machines. Each shard is a full database server (often with its own replicas) that holds a subset of the rows. Together they hold everything.

Say you have four shards and pick user_id as the shard key. A simple rule could be shard = hash(user_id) % 4. All rows for user 42 live on one shard, all rows for user 43 maybe on another. The application, a proxy or the database layer has to know this rule and send each query to the right server.

Step by step, a read looks like this:

  1. A request comes in for user 42.
  2. The routing layer computes the shard for 42, say shard 2.
  3. The query goes to shard 2 only.
  4. Shard 2 answers like a normal database.

That is fast and scales well, as long as queries include the shard key. Now consider "top 10 users by spending this month". No single shard has the answer. The query has to go to all four shards, and someone has to merge the results. This is a scatter-gather query, and it gets slower and more fragile as you add shards.

What sharding buys you

  • Write and storage capacity beyond one machine. Each shard handles only part of the load.
  • Smaller failure blast radius. If one shard is down, only part of the users are affected.
  • Data placement, for example keeping a region's users on servers in that region.

What it costs you

  • Cross-shard queries and joins are slow or not supported, depending on the setup.
  • Transactions across shards need distributed coordination, or you design them away.
  • Unique constraints and foreign keys only hold inside a shard, unless the system does extra work.
  • Rebalancing. With hash % N, changing N moves most of the rows. Real systems use consistent hashing, a lookup directory or many small virtual shards to move less data.
  • Hot shards. A bad key (for example one huge customer) puts most of the traffic on one server.
  • Operations: more servers to back up, upgrade, monitor and keep in sync on schema.

Some databases shard for you: MongoDB has sharded clusters, Vitess shards MySQL, Citus distributes PostgreSQL tables, and distributed SQL databases such as CockroachDB split data into ranges automatically. They hide the routing, but the trade-offs above still exist underneath.

Side by side

Partitioning Sharding
Where the pieces live One server Several servers
Visible to the app Usually not Often yes (routing, keys)
Main goal Manageability, pruning, cheap deletes Capacity beyond one machine
Joins and transactions Work normally Hard across shards
Operational cost Low High

The two can be combined. Each shard can itself partition its big tables by time. Many large systems do exactly that.

Common mistakes

Partitioning without a matching filter. If most queries do not filter on the partition key, the planner has to scan every partition, and the extra planning overhead can make things slower than one table.

Too many partitions. Thousands of tiny partitions increase planning time and catalog overhead. Pick a granularity that matches how you query and delete, often monthly or daily for large event tables.

Sharding too early. A single well-tuned server with good indexes, read replicas, caching and partitioning can go a long way. Sharding is a one-way door for your schema and your code. Reach for it when one primary truly cannot keep up with writes or data size.

Choosing the shard key on a whim. The key decides which queries are cheap forever. Pick the one that appears in almost every query and spreads load evenly, often a tenant or user ID. Avoid monotonic keys like timestamps as the shard key with range sharding, because all new writes then hit the last shard.

Forgetting about unique IDs. With several shards, auto-increment sequences collide. Use UUIDs, a central ID service, or per-shard ranges.

In short

  • Partitioning splits a table into pieces on one server. It helps queries that filter on the partition key, keeps indexes small, and makes deleting old data cheap.
  • Sharding splits data across many servers. It adds write and storage capacity, at the cost of cross-shard queries, distributed transactions and harder operations.
  • Try indexes, replicas and partitioning first. Shard when one machine is the real limit, and choose the shard key with care.

Watch the animated version: https://youtu.be/YDjeR1jMoa8

Originally published at abdeldjalilchougui.biz.