Scaling a database: read replicas, sharding Postgres, distributed SQL

From one Postgres server to many, on the chat product: what runs out first, the cheap rungs, read replicas and read-your-writes, partitioning, functional splits, sharding (keys, hot shards, cross-shard work, resharding), distributed SQL and multi-region, with when each rung is enough. Partitioning, Citus sharding with a live rebalance and a CockroachDB node failure were run for real. A child page of Topic: databases. Data as of October 2026. Reading: 45 min, plus 8 in closed details.

The idea in one screen

Measure which resource of the one server runs out, then climb only to the first rung that fixes it: copies multiply reads but never writes, splitting the data multiplies writes and size, and every split makes a query that does not name the key ask every piece.

Fig. 1: three ways to grow, and where one request goes in each

  1. Still one machine. Every read and every write goes to one Postgres server. The rungs that stay here (fix the queries, a bigger box, a connection pooler, a cache, partitions) multiply nothing; the one box is used better. The wall is the largest machine.
  2. More copies: reads multiply, writes do not. Read replicas, in one region or many. Every write still goes to the one primary; its log streams to every replica, which replays it a little behind, so each replica does all the write work again. Reads spread over all the copies.
  3. Split the data: a query with the shard key reaches one shard. Tables to other databases, sharding one table's rows, distributed SQL. A router turns the key into a shard, so the query touches one server of four. Multiplies writes and size.
  4. A query without the key asks every shard. Nothing tells the router where the matches are, so it sends the query to all of them and merges the answers (scatter-gather): four servers busy for one question.

Drawings are schematic. The colours (one machine, copies, split) are the same in the ladder below and in every figure on the page.

You need: the root Topic: databases, Reading sections 1 to 4 and 7 (the chat product, its tables, transactions, indexes, the shard key as a one-way door); its Database atlas tab compares Citus, Vitess, CockroachDB, Spanner, TiDB, YugabyteDB and Aurora with licences, isolation and Jepsen results, and is cited here as "root's Database atlas". Replication and consistency in general, consensus (Raft) and consistent hashing are Distributed systems fundamentals; setting up replicas, failover and pooling are Running Postgres in production; isolation levels on one node are Transactions and concurrency.

Vertical scaling
a bigger machine for the same database (scaling up).
Read replica
a copy that replays the primary's log and answers reads, a little behind.
Read-your-writes
a user always sees their own last write.
Partition
a physical piece of one table, on the same server.
Shard, shard key
a slice of a table's rows on its own server; the column that decides which slice.
Scatter-gather
sending a query to every shard and merging the answers (fan-out).
Logical shard
a small fixed bucket of keys; many live on one server and move as a unit.
Range, leaseholder
in distributed SQL, a contiguous piece of a table replicated by consensus; the replica that serves its reads and proposes its writes.

Click a rung to see what it fixes, what it costs, and when it is enough. The colours mark the three kinds of step: still one machine, more copies, split the data.

Everything on this page that says measured was run for real on one Apple M1 Pro laptop on 5 October 2026 on the root page's chat dataset (same script, same seeds: 100,000 users, 1 million chats, 10 million messages). Every server on one machine means no real network between them: latencies here are lower bounds, and section 11 says how to add the network back. Versions and setup are in Depth.

1. What runs out first on one server

"The database is slow" is not a diagnosis. A database server is a machine with a few separate resources, and each one runs out in its own way, with its own fix. Picking a fix before knowing which resource ran out is the most expensive mistake in this whole subject: teams shard a database whose real problem was one query without an index.

Each resource fails with its own symptom, and each has its own first fix
ResourceWhat uses itHow you noticeFirst fix
CPURunning queries: scanning rows, sorting, joining, computing aggregates.CPU near 100%; every query slower at the same time.Find the few queries using most of it (pg_stat_statements) and fix them (section 2).
Memory (the working set: the data that is read often)Postgres keeps recently used 8 KB pages in its own cache (shared_buffers) and the operating system caches more.Reads start going to disk: the cache hit ratio drops and the same query is suddenly much slower. Measured here: the dashboard query scanning all 10 million messages took 2,766 ms the first time (pages on disk) and about 373 ms once they were in memory.More memory (a bigger machine), or make the hot data smaller (indexes, partitions, archiving old rows).
Disk input/output (IOPS: reads and writes per second the disk allows)Reading pages not in memory; writing the log and the tables.High disk wait times; on a cloud volume, hitting the provisioned IOPS limit. Figma's highest-write tables were heading past the largest IOPS Amazon RDS supports (Case files: figma-2024).Faster or provisioned storage, fewer writes (batching), or split the data.
ConnectionsEvery client connection is a separate Postgres process with its own memory."too many clients already" errors; memory pressure from thousands of idle connections.A connection pooler (section 2).
Write rateAll writes go to one server and one ordered log (the write-ahead log, WAL: every change is written there first so it survives a crash).Commits queue up; replicas fall behind because they replay the log in one process.Batch writes, move write-heavy data elsewhere (section 5); in the end, sharding (section 6).
Size and operationsThe table on disk.Backups and restores take hours, a schema change on a billion-row table is risky, vacuum (Postgres's cleanup of dead row versions) cannot keep up. Notion's engineers found that even "simple catalog-only migrations became unsafe and uncertain" on their monolith (Case files: notion-2021).Partitioning (section 4), archiving, then sharding.

The root page measured how much one laptop does: about 2,133 small write transactions per second with each commit truly flushed to the SSD, and about 65,000 indexed reads per second (Database atlas tab of the root, claim "pg_tps"). A large cloud server does several times that. Most products never outgrow one well-run Postgres server plus replicas; the ones that do usually outgrow it on writes or size, not reads.

Measure before you climb
Four numbers tell you where you are: CPU use, cache hit ratio (blks_hit / (blks_hit + blks_read) in pg_stat_database), disk IOPS against the volume's limit, and write-ahead log bytes per second (pg_stat_wal). Watch their trend, not one value: the useful question is "at this growth rate, which one hits its ceiling first, and when?". Running Postgres in production (section 9, Monitoring) sets these up; Capacity planning and performance turns them into a forecast.

2. The cheap rungs: fix the queries, buy a bigger box, pool, cache

The chat product's database CPU sits at 80% at the evening peak and the p99 latency of opening a chat has doubled in a month. The tempting conclusion is "Postgres does not scale". The professional's first move is to ask which queries use the machine, because the four rungs in this section are each about ten times cheaper than the ones after it and they keep working after you shard, so none of them is wasted.

Rung 1: fix the queries and the indexes

A handful of queries usually use most of the database. pg_stat_statements (a standard extension that sums time per query shape) lists them; EXPLAIN (ANALYZE, BUFFERS) shows why each is slow; an index, a rewritten query or a fixed statistic usually makes it ten to a thousand times cheaper. On this page's data, adding one index on created_at took the dashboard query from about 373 ms to about 23 ms (section 4). OpenAI found that "an extremely costly query that joined 12 tables" was behind several of its worst incidents, and moved such joins into the application (OpenAI, 22 Jan 2026).

Enough when the load is dominated by a few fixable queries. Not enough when every query is already cheap and there are simply too many of them. The method is Query planning and performance; the root's Query plans tab runs real plans on this data.

Rung 2: a bigger machine (vertical scaling)

Vertical scaling (scaling up) means moving the same database to a machine with more CPU, memory and faster disks. Nothing in the application changes; on a managed service it is a setting and a failover of seconds to minutes. It is the most underrated rung, because the largest machines are very large:

The largest Amazon RDS for PostgreSQL machine, db.r8g.48xlarge, has 192 vCPU and 1,536 GiB of memory for $22.944 an hour in one zone (about $16,750 a month), twice that with a Multi-AZ standby; storage tops out at 64 TiB and 256,000 IOPS. The rows, the most-memory machine and the sources are in the one dated table in Depth.

What it costs: price roughly doubles with each size step while the ceiling is fixed; a bigger box takes longer to back up, restore and fail over; and one machine is still one failure domain. Figma's first move was exactly this, from an r5.12xlarge to an r5.24xlarge, before it started splitting tables off (Figma, 4 Apr 2023). Enough when growth is steady and you are below about half of the largest box. Not enough when you are already near the top size, or a forecast says you will be within a year: start the next rung while you still have headroom, because the later rungs take months.

Rung 3: connection pooling, because connections are a wall of their own

Each Postgres connection is a separate operating-system process, and max_connections defaults to 100 (3 kept for superusers). Connections grow with the application, not with the work: every pod or worker holds its own pool, so adding app servers to carry more traffic eventually hits this wall even when the database's CPU is idle, and each read replica you add is one more pool per pod. A connection pooler such as PgBouncer sits in between and lends a few real connections to many clients. OpenAI reports average connection time dropping from 50 ms to 5 ms with PgBouncer (OpenAI, 2026).

Predict: the chat product runs 20 pods with SQLAlchemy's default pool (5 connections plus 10 overflow each). How many pods fit under the default limit before a traffic spike is refused? Then drag.

Arithmetic from Running Postgres in production (section 7), which measures what one backend costs, the refused connection (FATAL: remaining connection slots are reserved), pooling modes, the two ways transaction pooling bites, and timeouts: link, not repeated here. The pool of 20 is illustrative; the wiki's starting point for active connections is about (2 x CPU cores) + disks.

Enough when the symptom is connection count. It does nothing for slow queries.

Connections grow with app pods, not with queries; a pooler holds the server side flat

Rung 4: caching

A cache keeps the answer to a frequent read (the chat list, a user's profile) in memory, usually Redis, so the database is not asked again. It removes reads, often most of them, and adds the problem of stale data and of every cache entry expiring at once (a stampede, which OpenAI handles with "cache locking"). Strategy, invalidation and stampedes live on Caching and Capacity planning and performance. Enough when the load is repeated reads of the same keys. Useless for writes and for reads that are all different.

Pro habit: OpenAI ran ChatGPT on "a single primary Azure PostgreSQL flexible server instance" with "nearly 50 read replicas", at load that "has grown by more than 10x" in a year, by staying on these rungs plus read replicas, rate limiting, and moving only new or write-heavy, shardable workloads to other systems (section 13). The lesson is not "never shard"; it is "do not shard what the cheap rungs can still carry".

Fig. 2 · read-your-writes, three routes

3. Read replicas in practice

The queries are fixed, the box is big, but reads (opening chats, listing chats, search) are 90% of the traffic and still growing. Reads do not change data, so any exact copy of the database could answer them.

A read replica (a standby, a follower) is a second Postgres server that receives the primary's write-ahead log as it is written and replays it, so it holds the same data a moment later. Postgres calls a replica that answers queries a hot standby; its data is "eventually consistent with the primary" (PostgreSQL docs, Hot standby). How replication works, synchronous against asynchronous, and the anomalies of reading behind the primary (measured on a real Postgres replica: 1,993 of 2,000 immediate reads missed the write) are on Distributed systems fundamentals (section 3, "Replication: keeping copies"); setting one up, replication slots and failover are on Running Postgres in production (sections 3 and 4). This section is what the application does with replicas.

Routing: who decides which server a query goes to

The database does not route for you. Three places can:

The application (most common)

Two connection pools, "primary" and "replica". Writes, and reads that must be current, use the primary; everything else uses a replica. Frameworks have it built in: Rails multiple databases (with automatic switching back to the primary after a write), Django database routers.

Routing in the driver, a proxy or the cloud (depth)

The driver

libpq (the C client library under most Postgres drivers) accepts several hosts and a role: target_session_attrs is one of any, read-write, read-only, primary, standby or prefer-standby, and since PostgreSQL 16 load_balance_hosts=random spreads connections across them (libpq docs). It picks a server per connection, not per query.

A proxy or the cloud

A managed reader endpoint (Aurora) or a proxy that sends queries to replicas (Pgpool-II, PgDog). Convenient, but a proxy that guesses "SELECT means read" will send a SELECT that must see the user's last write to a replica.

# the pattern every team ends up writing (Python, psycopg pools)
def db_for_read(user):
    # read-your-writes: this user wrote recently, so the replica may not have it yet
    if now() - user.last_write_at < STICKY_SECONDS: return primary_pool
    replica = pick(r for r in replicas if r.lag_seconds < MAX_LAG)   # skip lagging replicas
    return replica or primary_pool

Read-your-writes in the application

Predict: a user sends a message and the chat reloads straight away from a replica. On Distributed systems fundamentals' real Postgres replica, how many of 2,000 such immediate reads saw the write? It plays the naive route first.

Fig. 2: the same reload under three routes; the replica is behind the write, so only a route that knows it shows the message

  1. The user sends a message. The write goes through the router to the primary, which commits it at log position 0/3000060.
  2. The log streams to the replica. The replica has replayed up to 0/3000020: a fraction of a millisecond behind, which is normal.
  3. The chat reloads from any replica. The router sees a read and picks a replica. Nothing tells it that this user just wrote.
  4. The message is missing. The replica answers from 0/3000020, before the write. To the user the message looks lost.
  5. How often, measured. On Distributed systems fundamentals' real Postgres replica, 1,993 of 2,000 immediate reads missed the write. Lag is short, but a reload is shorter.

Log positions are illustrative; the 1,993 of 2,000 misses and the 0.105 ms wait are measured on Distributed systems fundamentals (section 3).

Two fixes are standard, the second and third modes of Fig. 2. Sticky primary: after a user writes, send that user's reads to the primary for a few seconds (simple; costs primary capacity). Wait for position: remember the log position of the user's last commit (pg_current_wal_insert_lsn()) and read from a replica only once pg_last_wal_replay_lsn() there has passed it (docs). PostgreSQL 19 (Release Candidate 1 on 15 October 2026, general availability targeted for 19 November) adds a WAIT FOR LSN command for the second pattern (release notes); version 18 has nothing built in. The measured cost of the wait (median 0.105 ms on loopback) is on Distributed systems fundamentals.

Lag: monitor it, and route around it

On the primary, pg_stat_replication shows write_lag, flush_lag and replay_lag per replica (docs); alert on replay lag, and have the router stop sending reads to a replica past a threshold. Lag is normally milliseconds (AWS says Aurora replica lag is "usually much less than 100 milliseconds"), but a write spike makes it minutes: OpenAI's PGConf.dev 2025 talk lists an incident with replica lag above 10 minutes after a write spike drove the primary past 90% CPU (slides). A replica also replays every write, in one process, so a primary that writes too fast for one replay process leaves every replica behind.

A correctness surprise: reads on replicas can also violate snapshot isolation (Jepsen's Long Fork, 29 April 2025), so a read that combines several rows to make a decision (a balance check, an invariant across rows) belongs on the primary.

Long Fork on replicas: what Jepsen found, and why (depth)

Jepsen tested Amazon RDS for PostgreSQL 17.4 Multi-AZ clusters and found that reads on replicas can violate snapshot isolation with a Long Fork: two transactions update two different rows; one reader sees the first update and not the second, another sees the second and not the first, so the two readers disagree about which happened first. The cause: the primary makes commits visible in one order (the order transactions release a lock on its list of running transactions), replicas in another (the order of the log) (Jepsen). AWS replied that it is not RDS-specific and reproduces on self-managed Postgres with replicas; the proposed fix (commit sequence numbers) is not in the PostgreSQL 19 release notes (checked at Release Candidate 1) (AWS, 2 May 2025).

What replicas cost, and when they are enough

Each replica is a full copy (same storage, same instance price), replays all writes, and gives stale reads the application must reason about. RDS allows 15 replicas per primary (cascading limits in the dated table in Depth). Enough when reads are the bottleneck and writes fit one primary, which is the situation of most products, OpenAI included. Never enough for writes: adding a replica adds write work, it never removes any.

4. Partitioning inside one Postgres

The messages table is the chat product's biggest: 10 million rows here, billions in a real product, growing every second. The product keeps one year of messages, so every night a job deletes the oldest day, and that job now runs for minutes, writes gigabytes of log, and leaves dead rows behind for vacuum to clean. Dashboards that look only at last week still read pages of old data.

Partitioning splits one logical table into several physical tables, the partitions, each holding the rows whose partition key falls in its slice. Queries still name the parent table; Postgres sends each row to its partition and, when a query's WHERE clause names the partition key, skips the partitions that cannot contain matches. That skipping is partition pruning, done when planning and again when executing (PostgreSQL docs, Table partitioning). Everything stays on one server: partitioning is not sharding.

Postgres has had this built in ("declarative partitioning") since version 10 (range and list) and hash partitioning since 11 (release notes). Three ways to slice (the full syntax and its constraints are SQL and data modelling's):

Range

Each partition holds a range of values, usually time: one partition per month. The natural choice for anything that grows with time and is deleted by age.

List

Each partition holds listed values: country IN ('DE','FR','NL'). Useful when the data has a few natural groups, for example to put EU users' rows on separate storage.

Hash

Rows are spread by a hash of the key into N partitions: MODULUS 8, REMAINDER 3. Evens out size when there is no natural range; pruning only helps queries with key equality.

-- the chat messages, one partition per month (what this page measured)
CREATE TABLE messages_month (LIKE messages INCLUDING DEFAULTS, PRIMARY KEY (id, created_at))
  PARTITION BY RANGE (created_at);
CREATE TABLE messages_m2025_09 PARTITION OF messages_month
  FOR VALUES FROM ('2025-09-01 00:00+00') TO ('2025-10-01 00:00+00');
-- ... one per month to 2026-08; an index created on the parent is created on every partition
CREATE INDEX ON messages_month (chat_id, created_at);

Note the primary key: (id, created_at), not (id). Each partition can only check uniqueness inside itself, so a unique key must include the partition key. Asking for PRIMARY KEY (id) fails, measured: ERROR: unique constraint on partitioned table must include all partitioning columns. If you need id unique on its own, generate it so it cannot collide (a sequence or an ID that embeds time).

Measured: which queries partitioning helps

The 10 million messages were copied into two partitioned versions: by month (12 range partitions on created_at) and by hash of chat_id (8 partitions). Predict before you click: which layout is slowest for opening a chat, a query that never names created_at? Then pick a query and a layout.

How to read it. The dashboard query names created_at, so the monthly layout reads only August: about 26 ms against 373 ms for the plain table (7,341 pages against 192,372). But the "One table" layout with an ordinary index on created_at also answers it in about 23 ms (select "One table" and read the note): for reading, an index does most of what partitioning does. Opening a chat does not name created_at, so the monthly layout must probe all 12 partitions' indexes: 0.21 ms against 0.05 ms, and its planning takes 2.0 ms against 0.3 ms. The hash-by-chat layout is the mirror image: one partition for the chat, all 8 for the dashboard. A partition key is chosen by the queries, exactly like a shard key (section 7), on a smaller stage.

A partition key helps only the queries that name it: highlighted boxes are the partitions the plan read


Where partitioning really pays: deleting old data

Deleting September 2025 from the plain table means finding and marking 863,999 rows, writing 160 MB of log (which every replica must replay, and every backup must store), and leaving 864 thousand dead rows for vacuum. Dropping the September partition removes one file. This, more than speed, is why time-series and log-like tables are partitioned. Archiving works the same way: detach a partition (DETACH PARTITION ... CONCURRENTLY, since PostgreSQL 14, takes only a weak lock on the parent), copy it to cheap storage, drop it.

Maintenance: what you now have to run

  • Create future partitions before data arrives. An insert with no matching partition fails. Most teams use the pg_partman extension or a scheduled job that creates the next few months ahead.
  • Not too many partitions. The docs: the planner handles "up to a few thousand partitions fairly well, provided that typical queries allow the query planner to prune all but a small number". Measured beside it on empty tables, planning time only.

Deleting a month: DELETE on the plain table against dropping its partition (measured)

Planning time grows with the partitions that cannot be pruned (measured)

Planning time in ms (median of 7), for a query on the partition key (pruned to one) and a query on another column (all partitions remain). Every query pays planning time, so 3,000 unpruned partitions add about 0.1 s to each one.

What partitioning does not solve

It does not add CPU, memory, disk or connections: all partitions live on the same server, so a server that is out of any of them stays out. It makes queries that do not name the key slightly slower, constrains unique keys, and adds jobs to run. Enough when the pain is a huge, time-ordered table: retention, vacuum, index size, archiving. Not the answer when the server itself is full.

The default partition trap, and partitionwise joins (depth)
  • The default partition trap. A DEFAULT partition catches rows that fit nowhere, but attaching a new partition then scans the default partition to check none of its rows belong to the new one, under a lock, unless a CHECK constraint proves it (docs).

Partitionwise join and aggregate (planning joins partition by partition) exist but are off by default because they raise planning cost (enable_partitionwise_join, docs).

5. Functional splits: different tables on different databases

The single primary takes every write: messages, credits, billing events, audit logs, rate-limit counters. They have nothing to do with each other except that they share a machine, and the busiest one slows all the others.

A functional split (Figma calls it vertical partitioning) moves whole groups of tables to their own database server: messages to one, billing to another. Each group keeps full SQL and transactions inside itself, and each server now carries only its share of writes. For the chat product: users, chats and messages stay together (they are read together), billing moves out, rate-limit counters move to Redis. Splitting along service boundaries ("a database per service") is the same move, and the same test decides it: split a group of tables off when it has its own owner and its own load, and no frequent transaction or join crosses the line.

A functional split divides the writes between servers, and cuts every transaction that crossed the line

GitHub, 2019 to 2021

GitHub grouped its tables into "schema domains", added linters that fail the build when a query or transaction crosses a domain, then moved domains to their own MySQL clusters, 130 tables in one move. The main cluster had served 950,000 queries per second in 2019 (900,000 on replicas); after the splits the same tables served 1.2 million per second with half the load per host (GitHub, 27 Sep 2021).

Figma, 2020 to 2022

After scaling up, Figma moved groups of tables to separate databases, growing from 2 to 50 tables moved by October 2022, each move costing about 30 seconds of partial impact (about 2% of requests) (Figma, 4 Apr 2023). It bought them time; their largest tables still outgrew one machine.

What it costs

Every JOIN and every transaction that crossed the split is gone. In the chat product, "deduct a credit and save the reply" was one transaction (the root's section 3); with billing on another server it becomes two writes that can half-fail, so it needs the outbox pattern or a saga (Queues, streams and async work). That is why GitHub built linters before moving anything: first stop new code from crossing the line, then move. Enough when no single group of tables is too big or too busy for one server. Not enough when one table (here, messages) is.

6. Sharding: split one table's rows across servers

The messages table alone writes more than the largest machine can absorb, or is larger than it can hold. No rung below splits a single table across machines.

Sharding (horizontal partitioning across servers) gives each server a slice of the rows. Each slice is a shard; the column that decides a row's shard is the shard key (Citus calls it the distribution column). Something must know which shard holds which key: the router, which can be application code, a proxy or the database itself. Each shard is a normal Postgres server, usually with its own replicas. The theory (range against hash, consistent hashing, hot keys) is on Distributed systems fundamentals (section 10, "Partitioning: splitting the data"); this page does it for real on the chat data.

The rule that decides everything: a query that names the shard key goes to one shard; a query that does not must ask every shard and combine the answers (scatter-gather, or fan-out). Fig. 3 runs two of the chat product's queries against one big Postgres and against the same data sharded by user with Citus (3 workers, 32 shards), both measured on this laptop.

Predict: after sharding, does the single-user chat list get faster or slower? And the search across everyone?

Fig. 3: before and after sharding by user: the query with the key touches one shard, the one without it touches all 32

  1. One server: a user's chat list. SELECT id, title FROM chats WHERE user_id = 4242 ORDER BY created_at DESC LIMIT 20 goes to the one Postgres that holds everything; the index on chats(user_id) finds the user's chats in a few pages. Median over 250 random users, measured: 0.10 ms.
  2. One server: search everyone's messages. content LIKE '%c0ffee%' can use no index, so Postgres scans all 10,000,000 messages with 2 parallel workers plus the leader process (its default). 16 matches; median of 5 warm runs: 1,502 ms.
  3. The same data, sharded by user. Citus spreads each table over 32 shards on 3 workers (11, 11 and 10 shards, about 300,000 messages each; the box heights are the real counts), and the application now sends its SQL to the coordinator, which routes it.
  4. With the key: one shard, and slower. WHERE user_id = 4242 names the distribution column, so hash(4242) picks one shard on worker 1 (Citus plan: Task Count: 1). Median 0.46 ms against 0.10 ms: the extra hop through the coordinator. With a real network each hop adds a round trip, typically a few hundred microseconds inside one data centre.
  5. Without the key: all 32 shards. The search says nothing about user_id, so any shard might hold a match (Task Count: 32). Every shard scans its slice and returns its top 50; the coordinator merges them into the final 16. 375 ms against 1,502 ms, faster only because 32 scans ran on more of the laptop's 10 cores at once.
  6. The total work did not shrink, it was spread out. Keyed queries each occupy one shard, so many of them spread over the cluster; every scatter query occupies every shard. On a busy cluster, scatter queries are what stop a sharded system from scaling.
The common misunderstanding
Sharding does not make single queries faster. It makes the system able to hold more data and take more writes, by adding servers. Single-shard queries pay an extra hop; scatter queries pay every shard. A shard key is good when almost every frequent query is single-shard.

7. Choosing the shard key for the chat product

The method

List the frequent queries and writes, with their rates. For each candidate key, ask two questions: which of them become single-shard, and does the load spread evenly, both in stored data and in today's writes. Then check the biggest single key: no shard can be smaller than the busiest key it holds. The candidates for the chat product, counted on the real 10 million messages (8 shards):

Five keys on the real data, 8 shards: only hashing the user is even and keeps a user's requests on one shard
Shard keySingle-shardMust scatterBiggest shard, storedBiggest shard, last week's writes

Counted from the data (src/measure/labdata.py): "stored" is the share of all 10M messages on the fullest of 8 shards (even would be 12.5%); "last week" is the share of the 208,001 messages written in the data's final 7 days. Hash shards use the page's hash function; range by user splits user ids 1 to 100,000 into 8 equal ranges; time puts consecutive months on consecutive shards; country hashes each country code to a shard.

By user (hash): the usual answer

Everything a user does (open a chat, list chats, send a message, delete my account) names the user, so it is single-shard, and the user's chats and messages live together, so joins between them stay on one server. Load is even: the busiest user here has 7,586 messages, 0.076% of the total. Scatters: anything across users (admin search, global dashboards) and login by email, which does not know the user id yet (section 8).

By chat (hash)

Even too, and "open a chat" is single-shard, but a user's chat list touches every shard holding one of their chats, and deleting a user scatters. Better only if chats are shared between many users (Discord partitions messages by channel for this reason: Discord, 2017).

By tenant (workspace, team, shop)

For a business product the tenant is the natural key: Notion shards by workspace, Slack sharded by workspace before Vitess, Shopify by shop (section 13). Everything inside a tenant stays together, and one tenant can be moved or isolated. The risk is the giant tenant: one customer bigger than a shard. The chat product's consumers are each their own tenant, which is why "by user" wins here; the closest coarse key in this data is country, and the US alone is 22% of all messages.

By time, or by a range of ids: the trap

Range by user id puts the oldest, most active users on shard 1 (27% of messages on 8 shards). Range by time puts every new write on the newest shard: 100% of last week's writes on one server while seven sit idle. Spanner warns about exactly this: monotonically increasing keys create a write hotspot (Spanner docs).

Hot shards and hot keys

A hot shard gets far more than its share of load. Two causes: a bad key (range or time, above), fixed by a better key; and a hot key, one key so busy that even alone it overloads its shard (a celebrity, a giant tenant, one viral channel). Hashing cannot split a single key. Fixes, from cheapest: cache its reads; coalesce identical concurrent requests (Discord: Case files: discord-2023); give the giant tenant its own shard; or split the key with a suffix (tenant:42#0 to #7) and pay a small scatter for its reads.

Shard-key lab: choose a key and a shard count, and see which shard runs hot and which requests fan out

Load per shard counted on the same 10,000,000 messages for every key and every shard count from 2 to 16; which requests become single-shard follows from the key.

Try: "By user id range" at 8 shards (the oldest users are the busiest), then "By month" with "last week's writes" (one shard takes everything), then "By user (hash)" with the giant-tenant slider at 10%.

Which requests stay on one shard

"One shard": the request carries the key, so the router sends it to one server. "Every shard": it must fan out to all N. "One shard, hot": single-shard but every such request hits the same shard. The giant tenant is not in the data: it adds one key with the chosen share of all load to show that no key choice can spread a single key.

8. Cross-shard work: lookups, joins, transactions, IDs

Some work will cross shards whatever key you pick. Each kind has a standard answer, and each was measured on the Citus cluster.

Lookups by another column: login by email

Login knows the email, not the user id, so it cannot be routed: Citus sends it to all 32 shards (each uses its local index). Measured over 250 logins: median ms sharded against ms on one node, about times slower, and every login now uses every shard. The fix is a lookup table that maps email to user id, itself sharded by email: one single-shard read to find the user, then one to fetch them. Vitess builds this in as a lookup vindex (Vitess docs). The cost: two writes per signup that must stay consistent.

Joins: co-location and reference tables

Two tables sharded on the same key with the same hash ranges are co-located: user 4242's chats and messages sit on the same server, so joining them on user_id runs inside each shard. That is why the chat product shards messages by user_id even though a message "belongs" to a chat: the shard key is copied into every table that should live with it (Figma calls such a group a "colo"). Small tables everyone joins against (the list of models and prices) become reference tables, copied to every server (Citus docs). A join that is neither is refused by default, measured on Citus with a chat_tags table sharded by chat_id:

SELECT t.tag, count(*) FROM chats c JOIN chat_tags t ON t.chat_id = c.id GROUP BY t.tag;
ERROR:  the query contains a join that requires repartitioning

With citus.enable_repartition_joins on, Citus reshuffles one side across the network to make the join possible: ms, against ms for the same join on one Postgres. Designing tables so joins are co-located is most of the work of sharding a schema.

Crossing shards, measured: the same work on one server and across the cluster

Each pair shares one scale; medians on the laptop cluster (measured), so the network is not included and real ratios are larger.

Transactions across shards

A transaction touching two shards needs every shard to commit or none. Citus uses two-phase commit (2PC: every server first promises it can commit, then all commit) for writes that span nodes (Citus README; how 2PC works and why it blocks is Transactions and concurrency, section 11). Fig. 4 replays the measured test: 300 transactions, each UPDATE users SET plan = plan WHERE id = ... for one user, then for users 11 and 13, which live on different workers.

Fig. 4: one shard commits alone; two workers need a vote before anyone commits

  1. One user, one shard: an ordinary commit. User 11's row lives on one worker, so the coordinator forwards the update and the commit there; nothing else is involved. Median ms.
  2. Two users on two workers. The coordinator sends each update to the worker holding that user's shard. Each worker changes its row and holds a row lock, but neither has committed.
  3. Phase 1: PREPARE TRANSACTION. The coordinator asks both workers to prepare: each writes its changes and the prepared state to disk, keeps its locks, and answers yes. A prepared transaction survives a crash and can still go either way.
  4. The decision is recorded. With both yes votes in, a commit record is stored on the coordinator. From here the transaction counts as committed even if a server crashes: Citus's maintenance daemon compares the coordinator's commit records with the workers' pending prepared transactions, and a present record means commit, an absent one abort (Citus README, checked 6 Nov 2026).
  5. Phase 2: COMMIT PREPARED. Both workers commit and release their locks. Median ms and ms at p99, against ms for one shard and ms for the same two users on one Postgres: the extra round trips are the price of atomicity.
  6. Atomic, but not one snapshot. The two COMMIT PREPAREDs do not happen at the same instant: between them, a reader on worker 1 already sees user 11's change while worker 2 still shows user 13's old row. Citus's multi-node transactions are atomic but have "no distributed snapshot isolation".

Vitess's default mode across shards is "best effort", not atomic, with an opt-in TWOPC mode (Vitess docs). Keep transactions inside one shard by design; that is the shard key's other job.

Unique ids

Each shard's own sequence would hand out the same ids. Options: UUIDs (version 7 sorts by time), a central id service, or ids that embed the shard. Instagram's 64-bit ids are 41 bits of milliseconds, 13 bits of logical shard id and 10 bits of a per-shard sequence, so the shard is readable from the id (Case files: insta-2012).

One 64-bit id, drawn to scale: ids sort by time, and the router reads the shard straight from the highlighted bits.

9. Resharding, and why the shard key is a one-way door

Adding a shard: how much data moves

Three shards are full; a fourth arrives. How many rows must move depends on how keys map to shards. Counted on the real users and their messages, from 3 shards to 4:

Predict: going from 3 to 4 shards, what share of the messages must move under hash(key) mod N? A quarter would be the minimum.

  • hash(key) mod N: changing N from 3 to 4 changes the remainder of about three keys in four, so % of messages move. Never route with a bare modulus over servers.
  • Consistent hashing (each shard owns arcs of a hash ring, 64 points each; explained and animated on Distributed systems fundamentals): only the keys the new shard takes over move, %. But with 64 points per shard the four shards end up holding between % and % of the data, not 25% each.
  • Logical shards: hash keys into a fixed, large number of buckets (here 48) once, forever, and map buckets to servers in a small table. Adding a server moves whole buckets: 12 of 48, % of messages, and the result is even. This is what Instagram (thousands of logical shards), Notion (480) and Citus (32 shards per table by default) do; moving a bucket is copying one table or schema, which tools do well.

Adding a fourth shard: a bare modulus moves three quarters of the data, logical shards move the minimum

Measured: Citus adds a fourth worker with writes running

The real thing, on the Citus cluster: 32 shards per table on 3 workers, a fourth worker added, and citus_rebalance_start() run while a client inserted messages for random users throughout. It uses logical replication, so reads and writes continue during the copy.

Fig. 5: a fourth worker joins and a quarter of the shard groups move to it, with writes running

  1. Three workers, 32 shard groups. Before the move the workers hold 10, 11 and 11 shard groups. A shard group is the matching shard of every co-located table, so a user's chats and messages move together. Inserts keep arriving (purple).
  2. A fourth worker joins, empty. citus_add_node registers it; nothing moves by itself, and no query goes there yet.
  3. The rebalancer copies 8 groups. It takes 2 groups from the first worker and 3 from each of the others. Each is copied with logical replication: a snapshot of the shard, then a stream of the changes made meanwhile. Writes still go to the old placement.
  4. Catch up, then switch. Once the copy has caught up, Citus blocks writes to the group with metadata locks, waits for the last changes to replicate, and updates pg_dist_placement to point at worker 4; the old copy is dropped once ongoing reads finish (Citus README, checked 6 Nov 2026). Insert latency over the whole move: median 0.22 ms, p99 1.38 ms, worst 124 ms.
  5. Even again. 8 groups on every worker: 841 MB of the 3,311 MB of messages (25.4%) moved in 36.1 s, with 140,600 inserts during the move and 0 errors. Which groups moved is drawn for illustration; the counts and sizes are measured.

Two real errors the rebalance hit (depth)

Two real errors along the way are worth knowing. The first attempt refused to start: cannot use logical replication to transfer shards of the relation chat_tags since it doesn't have a REPLICA IDENTITY or PRIMARY KEY (every table you shard needs a primary key). The second stalled because the rebalancer keeps a disk safety margin on the target: not enough empty space on node if the shard is moved (the laptop's disk was 96% full), fixed by lowering citus.desired_percent_disk_available_after_move for this test.

Changing the shard key: the one-way door

Adding shards moves a quarter of the data. Changing the key moves almost all of it: re-sharding the chat data from user to chat on 3 shards puts % of messages on a different shard. Worse, every query was written for the old key: each single-shard query becomes a scatter and the other way round, unique keys and co-location change, and the ids may embed the old shard. That is a rewrite of the data layer under live traffic, done with double-writes, a backfill, verification and a cutover (Notion's 2021 migration took a backfill of about three days before a five-minute cutover: Notion). Hence the root's warning: choose the shard key from the queries, and treat it as permanent. Notion's own second move, from 32 to 96 machines in 2023, kept the key and the 480 logical shards and only moved them, which took them from 15 to 5 schemas per machine (Notion, 17 Jul 2023).

10. Sharding Postgres in practice: by hand, Citus, or a proxy

Postgres has no built-in sharding. Teams get it in one of four ways, and the choice decides how much of sections 6 to 9 you write yourself.

In the application

The application computes the shard from the key and holds one connection pool per shard. Notion (480 logical shards, workspace id), Instagram (user id) and, with a SQL-parsing proxy of its own called DBProxy, Figma. Full control, and nothing new to operate; but you write the router, the scatter-gather, the resharding tooling and the cross-shard rules, and every engineer must know them.

def shard_for(user_id):
    bucket = h32(f"user:{user_id}") % 480   # logical shard, fixed forever
    return BUCKET_TO_HOST[bucket]          # small table, changes when moving

Citus (an extension inside Postgres)

Measured on this page. A coordinator plans queries over workers. create_distributed_table('messages', 'user_id', colocate_with => 'users') shards a table (32 shards by default), create_reference_table('models') copies one everywhere, and the rebalancer moves shards online. Real Postgres underneath, so extensions and SQL mostly work. Licence and hosting are in the dated table. Since Citus 12 it can also shard by schema, one schema per tenant.

Vitess (for MySQL)

Created at YouTube in 2010; Slack runs 99% of its MySQL traffic through it (root's Database atlas). Resharding is a built-in workflow; cross-shard commits are not atomic unless you choose TWOPC.

Vitess vocabulary (depth)

A keyspace is a logical database split into shards named by hash ranges (-80, 80-); the VSchema says how each table is sharded; a vindex maps a column to a shard (a hash vindex, or a lookup vindex backed by a table); vtgate is the stateless proxy that routes queries; resharding is a workflow that copies, streams changes, verifies (VDiff) and switches traffic (Vitess docs v24).

The new Postgres proxies and services (2024 to 2026)

Several projects now bring Vitess's ideas to Postgres: a proxy that parses SQL, routes by the shard key, merges cross-shard results and reshards with logical replication (PgDog, Neki, Multigres), or a managed service with routers and hash-sharded, collocated and reference tables (Aurora PostgreSQL Limitless). They move fast; their status on 5 October 2026 is in the dated table in Depth. Check it before betting on one.

How a pro chooses among them
If you are on Postgres and need sharding now, Citus (self-run or managed on Azure) is the most proven; if you are on AWS and want it managed, Limitless; if you need full control or your access pattern is simple and tenant-shaped, application-level logical shards, as Notion and Figma did. On MySQL, Vitess (or PlanetScale). Whatever you choose, the shard key, co-location and the ban on cross-shard transactions are your design work; no tool does them for you.

11. Distributed SQL: a database that shards itself

Sections 6 to 10 left a lot of machinery to the team: the router, resharding, cross-shard transactions, failover of every shard. A family of databases does all of it inside the database and still speaks SQL with real transactions: Google Spanner (2012 paper), CockroachDB, YugabyteDB, TiDB, and Amazon Aurora DSQL.

The idea, in three parts

  1. Ranges. All rows, sorted by primary key, are cut into contiguous pieces: CockroachDB calls them ranges (split when they pass 512 MiB by default), TiDB regions (256 MiB since v8.4), YugabyteDB tablets, Spanner splits. The database splits and moves them by size and load, so resharding is automatic.
  2. Consensus per range. Each range is kept on three (or five) servers, which agree on every write with a consensus protocol, Raft in CockroachDB, TiDB and YugabyteDB, Paxos in Spanner (how Raft works, step by step: Distributed systems fundamentals, section 7, "Consensus: Raft step by step"). A write commits once a majority has it, so losing one of three copies loses nothing and the range keeps working.
  3. Distributed transactions. A transaction touching several ranges is committed atomically by the database, with serializable isolation by default in CockroachDB and Spanner (the root's Database atlas lists each system's isolation and Jepsen history).

Measured: CockroachDB, three nodes, then two, then one

CockroachDB v26.3.0, three nodes on this laptop, a table of 200,000 messages split into four ranges, each range replicated to all three nodes; one replica per range, the leaseholder, serves its reads and proposes its writes. A client kept inserting through node 1 while nodes were killed with kill -9 (no warning, like a power cut).

Fig. 6: four ranges on three nodes through the measured kill sequence; a range takes writes while a majority of its copies is alive

  1. Four ranges, three copies each. The 200,000 messages sit in four ranges (88 to 91, from SHOW RANGES at the end of the run), each with a copy on every node. Every lease sat on node 1, the node the client was connected to.
  2. A write commits at a majority. The insert goes to its range's leaseholder, which sends it to the two other copies through Raft; once one of them has it, two of three, the write commits. With all three nodes up the client managed about 47 inserts a second.
  3. kill -9 node 3 at 10 s: writes continue. Every range still has two of its three copies, a majority, so writes simply continue (about 56 a second). No lease was on node 3, so there was not even a pause; had node 3 held leases, the ranges it led would have paused until their leases moved to a survivor.
  4. kill -9 node 2 at 35 s: no majority, writes stop. One copy of three cannot commit anything: each insert timed out after 3 s, rather than risk two divergent histories. That is the "consistency over availability" choice that Distributed systems fundamentals explains (section 6, "CAP read correctly, and PACELC").
  5. Restart node 2 at 50 s: writes resume by themselves. Two of three copies again: inserts came back about 3 s later, and nobody ran a failover.
  6. Restart node 3 at 65 s: back to three copies. Node 3 catches up from the others, and every range can lose a node again.

The same run, second by second

The strip beside counts the successful inserts in every second of the run that Fig. 6 walks through: steady with three nodes and with two, nothing while only one was alive, and back without anyone acting once a majority returned. The numbers under it are averages over each stretch; the latency tiles compare one insert with plain Postgres (the price of consensus is below).

The measured run: inserts per second while nodes were killed (measured)

successful inserts per secondseconds with no successful insert (each attempt timed out after 3 s)

The four ranges at the end of the run (SHOW RANGES ... WITH DETAILS)

The latency floor, and where it comes from

Every write waits for a majority of a range's replicas. Inside one data centre that is one fast round trip; across regions it is physics. Median round trips between AWS regions, measured by CloudPing (5 Oct 2026): us-east-1 (Virginia) to us-east-2 (Ohio) about 13 ms, to us-west-2 (Oregon) about 70 ms, to eu-west-1 (Ireland) about 68 ms, to ap-southeast-1 (Singapore) about 218 ms (cloudping.co).

Where the three replicas areSurvivesEach commit waits at least
Three zones of one regiona zoneone round trip between zones, about 1 to 2 ms
Virginia, Ohio, Oregon (leaseholder in Virginia)a regionVirginia to Ohio, about 13 ms
Virginia, Ireland, Singapore (leaseholder in Virginia)a region, on another continentVirginia to Ireland, about 68 ms
Same, client in Singapore writing a row led from Virginiaabout 218 + 68 = 286 ms
Spanner's extra wait: TrueTime and commit wait (depth)

Spanner adds one more wait. Its clocks (TrueTime) report an interval of uncertainty, epsilon, "typically a sawtooth function of time, varying from about 1 to 7 ms"; to make commit order match real time, a commit waits out that uncertainty ("commit wait", about twice epsilon) before becoming visible, which overlaps with the Paxos round (Spanner paper, OSDI 2012).

Each commit waits for the nearest other replica: one region, three regions, a far client

three zones, one region1 to 2 ms
Virginia, Ohio, Oregon13 ms
Virginia, Ireland, Singapore68 ms
same, client in Singapore286 ms

Commit at least = round trip from the leaseholder to the nearest other replica (a majority of three is the leader plus one), plus the client's round trip to the leaseholder if it is far away. The intra-region figure is the one cited on Distributed systems fundamentals; the rest are CloudPing medians.

Cheaper reads: follower reads

Reading from the leaseholder means crossing the ocean too. A follower read reads a nearby replica at a timestamp slightly in the past, so it never waits: SELECT ... AS OF SYSTEM TIME follower_read_timestamp(). Measured on this cluster, the timestamp was s in the past, matching the follower-reads page's "at least 4.2 seconds" (docs; the function reference says 4.8 s without a licence key, which this unlicensed cluster did not show). It is a read replica's trade, made explicit per query.

The systems, briefly (5 Oct 2026)

SystemPieces and consensusCompatible withWorth knowing
Google Spannersplits, Paxos, TrueTimeGoogleSQL and a PostgreSQL dialectManaged only; monotonically increasing keys make a hotspot.
CockroachDBranges (512 MiB), Raft, leaseholdersPostgreSQL wire protocol and much of its SQLSerializable by default. Licence terms (dated table) throttle an unlicensed multi-node cluster after 7 days, which is why this page's demo was short.
YugabyteDBtablets, Raft per tablet; hash sharding of the first key column by defaultReuses PostgreSQL's query layer (YSQL)Apache 2.0 core.
TiDBregions (256 MiB), Raft, a placement driver (PD) that balances themMySQLSnapshot isolation, no serializable (root's Database atlas).
Aurora DSQLAWS-internal; optimistic concurrency (no locks, conflicts fail at commit with SQLSTATE 40001 and must be retried)PostgreSQL 16, partlyFixed at repeatable read; a transaction may change at most 3,000 rows; no triggers, temporary tables or PL/pgSQL (full limits in the dated table).
What you give up

Latency: every write pays a consensus round trip: a median insert took ms on this three-node loopback cluster against ms on plain Postgres with macOS's default flush and ms with a real SSD flush per commit, as CockroachDB does, and tens of milliseconds across regions. Compatibility: "Postgres-compatible" means the wire protocol and much of the SQL, not every extension, isolation level or planner behaviour. Hotspots still exist: a sequential key sends all inserts to the last range. Retries: serializable and optimistic systems abort conflicting transactions, so the application must retry. Cost and skills: more nodes per byte, a new system to learn, and for some, licence terms. Worth it when you need writes beyond one machine, or must survive a zone or region without a failover runbook, and you would otherwise build sections 6 to 10 yourself.

12. Multi-region: putting data near users, and where the law says

Users in Singapore pay about 218 ms per round trip to a database in Virginia. Three patterns, from simplest:

One primary, replicas everywhere

Reads are local, writes cross the world. OpenAI's "nearly 50 read replicas across multiple geographic regions" with one primary is this pattern. Simple; writes from far away are slow, and failover to another region risks the split brain GitHub hit in 2018 (Case files: gh-2018-10).

Geo-partitioning (each row lives near its owner)

Rows carry a region, and each region's rows are stored and led there: a European user's messages commit in Europe. CockroachDB calls this a REGIONAL BY ROW table; with sharding you get it by making region part of the shard key (one cell or pod per region, as Shopify does per pod). It is also how data residency is done, keeping some users' data inside a jurisdiction, which some laws and many enterprise contracts require.

Global tables (read everywhere, write rarely)

Small, read-mostly data (the list of models, feature flags, prices) is copied to every region for local reads, and each write pays the cost of reaching all of them. CockroachDB: GLOBAL tables, "fast reads everywhere, slower writes" (table localities); sharded systems: reference tables.

Surviving a whole region failing needs replicas in at least three regions, and then every write waits for a second region: CockroachDB's REGION survival goal "adds at least one inter-region round trip to writes", while the default ZONE goal keeps writes inside a region (survival goals). Decide which failure you must survive, then pay for exactly that.

Where a Singapore user's read and write go under each pattern

13. How real companies climbed, with their numbers

Dates are publication dates; numbers are the companies' own. The pattern across all of them: everyone climbed the cheap rungs first; those who sharded chose a tenant-like key (workspace, user, shop, channel) and many logical shards; and the hardest part was never the router but migrating live data and rewriting the queries that crossed shards.

Nine companies on the ladder: how high each climbed, and the number that shows it
Company (date)Highest rungThe number
OpenAI (22 Jan 2026)replicas and a functional split; no sharding of Postgresone primary, nearly 50 read replicas, millions of queries per second
Notion (2021, 2023)application sharding by workspace480 logical shards; 32 machines, then 96
Figma (2023, 2024)bigger box, 50 tables split off, then sharding behind its own proxy"almost 100x" growth since 2020
Instagram (2012)application sharding by userseveral thousand logical shards on a few servers
GitHub (2021, 2023)functional splits, Vitess for the largest areas5.5 million queries per second, more than 50 clusters
Slack (1 Dec 2020)workspace shards, then Vitess2.3 million queries per second at peak, p99 11 ms
Shopify (2018, 2021)sharding by tenant (pods), moving shops onlineload spread between shards from about 4x to about 2x
Discord (2017, 2023)a different store, keyed by (channel, 10-day bucket)177 Cassandra nodes became 72 ScyllaDB nodes
Uber (23 Feb 2021)distributed SQL built in-house (Docstore)partitions of 3 to 5 MySQL nodes kept consistent with Raft
The nine stories in full, with quotes and sources (depth)

Where the SWE topic has the story as a case file, it is linked rather than retold.

OpenAI: one primary, nearly 50 replicas

22 Jan 2026 queriesbigger boxpoolingcachereplicasfunctional split

ChatGPT and the API run on "a single primary Azure PostgreSQL flexible server instance" with "nearly 50 read replicas across multiple geographic regions", at millions of queries per second after load grew more than 10x in a year. Write-heavy, shardable workloads moved to Azure Cosmos DB, and "we also no longer allow adding new tables". Schema changes have "a strict 5-second timeout"; PgBouncer cut connection time from 50 to 5 ms; cascading replication was being tested to go past 100 replicas. Result: "low double-digit millisecond p99" and five-nines availability, with one top-severity Postgres incident in a year (OpenAI; earlier detail in the PGConf.dev 2025 talk).

Notion: 480 logical shards, then a re-shard

6 Oct 2021 and 17 Jul 2023 sharding (application)

Sharded by workspace id into 480 logical shards (Postgres schemas) on 32 machines, 15 each; limits they set: 500 GB per table, 10 TB per database. Migration: double-write, a backfill of about three days, verification, a five-minute cutover. In 2023, 32 machines became 96 (5 schemas each) by moving schemas with logical replication; syncing took 12 hours instead of 3 days, and users saw at most about a second's pause. The 480 shards never changed (Case files: notion-2021; re-shard post).

Figma: up, apart, then sharded, still Postgres

4 Apr 2023 and 14 Mar 2024 bigger boxfunctional splitsharding (proxy)

Bigger instance first, then 50 tables moved to separate databases, then horizontal sharding of the biggest tables after "almost 100x" growth since 2020. They considered CockroachDB, TiDB, Spanner and Vitess and built their own: a DBProxy that parses SQL and routes it, "colos" of tables sharing a shard key, and logical sharding (views) before physical. First sharded table in September 2023, with about 10 seconds of partial availability (Case files: figma-2024).

Instagram: thousands of logical shards

2012 sharding (application)

Users split into several thousand logical shards (Postgres schemas) on a few servers; growing means moving schemas, never re-bucketing. Ids carry time, shard and sequence (section 8) (Case files: insta-2012).

GitHub: functional splits, Vitess for the biggest

27 Sep 2021 and 7 Dec 2023 replicasfunctional splitsharding (Vitess)

Schema domains and linters, then clusters per domain (section 5). By 2023: more than 1,200 MySQL hosts, more than 300 TB, 5.5 million queries per second across more than 50 clusters, with Vitess used only for the largest areas (GitHub).

Slack: workspace shards, then Vitess

1 Dec 2020 sharding (application, then Vitess)

Thousands of MySQL hosts sharded by workspace by 2016, which broke down for big workspaces and cross-workspace features. Moved to Vitess: 99% of queries, 2.3 million per second at peak (2 million reads, 300,000 writes), median 2 ms, p99 11 ms (Slack).

Shopify: pods, and moving shops between them

2 Mar 2018 and 24 Sep 2021 sharding by tenantmulti-region

Shops grouped into pods with isolated datastores (Case files: shopify-2018). Hot shards appear anyway, because shops grow unevenly; moving shops online (batch copy plus following the binary log, the Ghostferry tool) cut the load spread between shards from about 4x to about 2x (Shopify).

Discord: partition key (channel, time bucket)

13 Jan 2017 and 6 Mar 2023 a different store

Messages in Cassandra keyed by channel and a 10-day bucket so partitions stay under 100 MB; later 177 Cassandra nodes became 72 ScyllaDB nodes, with hot channels handled by request coalescing (Case files: discord-2023; wide-column design is on NoSQL in practice).

Uber: Docstore, MySQL plus Raft

23 Feb 2021 distributed SQL (built in-house)

Uber turned its Schemaless store into Docstore: partitions of 3 to 5 MySQL nodes kept consistent with Raft, tens of petabytes, tens of millions of requests per second (Uber). Most companies buy this layer instead of building it.

Depth

Reference material, closed by default: measurement setup, the dated product table and every term.

How the measurements were made (versions, machine, caveats)

All on one Apple M1 Pro laptop, 5 October 2026: PostgreSQL 16.2 (the pgserver wheel), Citus 14.2.0 built from source against it (a coordinator and three, then four, workers), and CockroachDB v26.3.0 (three nodes). The data is the root page's chat dataset, generated by the same script with the same seeds: 100,000 users, 1 million chats, 10 million messages. Scripts and raw outputs are in src/measure/ and src/inputs/; the build notes (one local Citus patch, the disk-space setting) are in src/README.md.

Dated: machines, prices and product status (volatile; read 5 to 15 Oct 2026)
ItemFactSource, date read
db.r8g.48xlarge, one availability zone192 vCPU, 1,536 GiB; $22.944 per hour, about $16,750 per month (730 h)AWS price list dated 1 October 2026, us-east-1, on demand, matching instances.vantage.sh/rds; storage is extra
db.r8g.48xlarge, Multi-AZ (a standby in a second zone)$45.888 per hour, about $33,500 per month
db.x2iedn.32xlarge (most memory), one zone128 vCPU, 4,096 GiB; $60.864 per hour, about $44,430 per month
RDS storage ceilings64 TiB; up to 256,000 IOPS on io2 Block Express, 64,000 on gp3RDS storage docs, 5 Oct 2026
RDS read replicas15 per primary; cascading replicas (replicas of replicas) up to three levels deep with 5 per source below the first levelAWS docs, 5 Oct 2026
CitusAGPL v3 since 2022 (root's Database atlas); owned by Microsoft since 2019, offered on Azure as elastic clusters in Azure Database for PostgreSQL, while Azure Cosmos DB for PostgreSQL "is on a retirement path"Microsoft Learn, 5 Oct 2026
PgDoga pooler that parses queries, routes by shard key, merges cross-shard results and reshards with logical replication; says it is "used in production", some features experimentalGitHub, 5 Oct 2026
Neki (PlanetScale)"not a fork of Vitess"; available, cross-shard transactions "coming soon"neki.dev, 5 Oct 2026
Multigres (Supabase)led by a Vitess co-creator; early developmentSupabase blog, 5 Oct 2026
Aurora PostgreSQL Limitlessgenerally available since 31 Oct 2024: routers plus hash-sharded, collocated and reference tables, managed by AWSAWS docs, 5 Oct 2026
CockroachDB licencesince 24.3: free self-hosting only for companies under 10M USD revenue with telemetry; an unlicensed multi-node cluster is throttled to 5 concurrent transactions after 7 dayslicensing FAQ, 5 Oct 2026
Aurora DSQLgenerally available since 27 May 2025; a transaction may change at most 3,000 rows and 10 MiB and run 5 minutes; multi-region only within one continentquotas, overview, 5 Oct 2026
PostgreSQL 19Release Candidate 1 on 15 October 2026, general availability targeted for 19 November; adds WAIT FOR LSNrelease notes, 15 Oct 2026

Monthly = hourly x 730.

Glossary: every term on this page
Vertical scaling: a bigger machine for the same database.
Horizontal scaling: more machines, each with part of the work.
Read replica: a copy that replays the primary's log and answers reads, a little behind.
Replication lag: how far a replica is behind the primary, in time or log bytes.
Read-your-writes: a user always sees their own last write.
Long Fork: two readers see two independent writes in opposite orders.
Partition: a physical piece of one table on the same server.
Partition pruning: skipping partitions a query cannot need.
Functional split (vertical partitioning): whole tables moved to another database.
Shard: a slice of a table's rows on its own server.
Shard key (distribution column): the column that decides a row's shard.
Router: the code or proxy that maps a key to its shard.
Scatter-gather (fan-out): sending a query to every shard and merging the answers.
Logical shard: a small fixed bucket of keys; many live on one server and move as a unit.
Co-location: related tables sharded on the same key so their rows share a server.
Reference table: a small table copied to every server.
Lookup table (lookup vindex): maps a non-key column (email) to the shard key.
Two-phase commit (2PC): prepare on every server, then commit on all.
Hot shard / hot key: a shard or single key receiving far more than its share of load.
Resharding: changing the number of shards or the key; moves data.
Range (region, tablet, split): a contiguous piece of a distributed SQL table, replicated by consensus.
Leaseholder: the replica of a range that serves its reads and proposes its writes.
Follower read: a read from a nearby replica at a slightly past timestamp.
Geo-partitioning: storing and leading each row in its owner's region.
Data residency: keeping data inside a given jurisdiction.