Nguyen Le Phong

Foundations of Software ArchitecturePart 10 of 15

Scaling a Database: Climb the Ladder Before You Shard

Before you shard, read the query plan.

Your app servers are the easy part. They keep no state, so when traffic doubles you run more of them behind a load balancer and get on with your day. The database is different. It holds the state, and state is the one thing you can't copy and forget about. That's why, in most growing products, the database is where the pain shows up first.

It's also where teams tend to grab the biggest tool first. "Let's shard." "Let's move to NoSQL." "Let's split it into services." Those moves exist for good reasons, but they sit at the top of a ladder. Below them are cheaper steps that are easy to undo, and most slow databases get fixed on the bottom rungs. This post walks the ladder in order: what each step buys you, what it costs, and how to tell when you've outgrown it.

Nguyen Le Phong at his desk with two monitors, one showing a code editor, while he works through why a query is slow.
Most scaling work starts at a desk like this one: one slow query, a query plan and a bit of patience before anyone orders bigger hardware.
Five steps for scaling a database, from cheap and easy to undo on the left to expensive and hard to undo on the right: index, scale up, read replicas, cache, shard. CLIMB IN ORDER: CHEAP AND REVERSIBLE FIRST, COSTLY AND STICKY LAST 1 · Index fix the query 2 · Scale up a bigger box 3 · Read replicas spread the reads 4 · Cache skip the query 5 · Shard split the data cheaper · easy to undo costly · hard to undo
The ladder. Each step is cheaper and easier to roll back than the one to its right. Move right only when the step you're on has really run out.

Step 0: Measure first, it's often one query

Before you scale anything, find out why it's slow. Early on, the cause is rarely "the database is too small." It's a missing index, an N+1 loop that fires a hundred small queries to render one page, or an innocent-looking query that reads the whole table to return a handful of rows.

The tool for this is the query plan. In PostgreSQL, EXPLAIN shows the plan the database intends to use, and EXPLAIN ANALYZE runs the query and reports real row counts and timings for each step. One thing to know before you paste it into production: because it really runs the statement, an EXPLAIN ANALYZE on an UPDATE or DELETE changes your data. The PostgreSQL docs suggest wrapping it in BEGIN and ROLLBACK (Using EXPLAIN).

-- Ask the planner what it actually does (this runs the query)
EXPLAIN ANALYZE
SELECT id, total FROM orders WHERE customer_id = 42;
-- Seq Scan on orders: it read every row to find a few

-- Build the index without blocking writes on a live table
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
-- Run EXPLAIN ANALYZE again: look for an Index Scan instead

A plain CREATE INDEX locks out writes on the table until it finishes. CONCURRENTLY avoids that, at the price of two table scans and a longer build. It can't run inside a transaction block, and if it fails it leaves an "invalid" index behind that you drop and retry (CREATE INDEX). Indexes also aren't free: every one of them has to be updated on each write. Add the ones your slow queries need, not one per column.

The most expensive mistake on this page

Paying for hardware to cover a missing index. The bigger instance bill arrives every month. The migration that adds the index is one line, written once. Open the query plan before you open the pricing page.

Step 1: Scale up before you scale out

Sometimes the machine really is the limit: CPU pinned, the working set no longer fits in RAM, disk I/O maxed out. The next move is the boring one, a bigger instance. More memory means more of your data stays cached, faster disks shorten every miss, more cores handle more connections.

Boring is the point. There's no code change, no new failure mode and nothing new for the team to learn. You buy headroom and time to work on the next problem.

It has limits you should know about. There's a largest size you can rent. The top sizes cost a lot more per unit of capacity. And it's still one machine: resizing usually means a restart or a failover window, and if that box dies, writes stop until something takes over. None of that is a reason to skip this step. A single well-tuned database carries a lot of traffic, so spread out only once you've actually hit the wall.

Step 2: Most traffic is reads, so add read replicas

The next two steps rest on one observation: most apps read far more than they write. Facebook's memcache paper puts it bluntly for their product: users consume an order of magnitude more content than they create (Nishtala et al., Scaling Memcache at Facebook, NSDI 2013). Your ratio will differ, so check your own query stats, but product pages, feeds and dashboards usually lean the same way.

So stop asking one machine to do both jobs. Keep a single primary that takes every write and add read replicas: read-only copies that follow the primary and serve queries. On Amazon RDS, for example, the primary copies changes to each replica asynchronously, and AWS lists the main uses as read-heavy traffic, reporting queries you'd rather keep off production, and disaster recovery, since you can promote a replica if the primary fails (Working with DB instance read replicas).

The application sends every write to one primary. Reads go to several read replicas, which copy the primary's changes asynchronously and so run slightly behind it. READS SPREAD OUT · WRITES STAY ON ONE PRIMARY Application Primary writes Replica A Replica B all writes reads spread out async copy · some lag a replica runs a little behind the primary: that gap is replication lag
One primary takes every write and the replicas share the reads. The price is replication lag: a replica is always a little behind the primary, and how far behind depends on load.

That price has a name: replication lag. Because the copy is asynchronous, a replica is always somewhat behind. Most of the time the gap is small. Under heavy writes, a busy replica or a network problem, it grows. Here's the classic bug it causes: a user posts a comment (write, primary), the page reloads and reads from a replica that hasn't caught up, and the comment seems to vanish. So they post it again. Now there are two.

Martin Kleppmann's Designing Data-Intensive Applications calls the fix read-after-write consistency, or reading your own writes: after you change something, you should see your change. You don't need it everywhere. You need it on the few screens where people look at what they just did.

A backend engineer sketches one primary database feeding two replicas on a whiteboard while two teammates follow along from their laptops.
Replicas work out when the team agrees, flow by flow, which reads can be a little stale and which must go to the primary.
Living with the lag

Send reads that must see the latest write to the primary: the profile a user just edited, the order they just placed. A simple version is to read from the primary for a short window after that user writes. Let search, feeds, dashboards and reports read from replicas. Then watch the lag itself. On RDS that's the ReplicaLag metric in CloudWatch (Monitoring read replication), and an alert on it beats finding out from a support ticket.

Step 3: Skip the database entirely with a cache

The fastest query is the one you never send. For data that's read often, costly to build and changes rarely, put a cache such as Redis or Memcached in front of the database and answer from memory.

The everyday pattern is cache-aside, which Microsoft's Azure Architecture Center describes step by step: read from the cache, on a miss read from the database and store the result, and on a write update the database and then remove the cached item (Cache-Aside pattern). Here it is with the node-redis client:

async function getProduct(id) {
  const key = `product:${id}`
  const cached = await redis.get(key)
  if (cached) return JSON.parse(cached)   // hit: served from memory

  const product = await db.products.findById(id)   // miss: pay for the query once
  if (product) await redis.set(key, JSON.stringify(product), { EX: 300 })
  return product
}

async function updateProduct(id, changes) {
  await db.products.update(id, changes)   // write the source of truth first
  await redis.del(`product:${id}`)        // then drop the stale copy
}

The order in updateProduct matters. The Azure guide explains why: if you delete the cache entry first, another request can miss, read the old row and put it back before your update lands. Facebook's paper makes a related choice: they delete cached data instead of updating it, because deletes are idempotent.

Phil Karlton's line, as Martin Fowler retells it, still holds: there are only two hard things in computer science, cache invalidation and naming things. The cache is wrong from the moment the data changes, and deciding when to refresh it is the real work. The second trap is the stampede: a hot key expires, many requests miss at once and all of them hit the database together. Facebook solved this with leases, where memcached hands out a token for a key at most once every 10 seconds and other requests wait briefly instead of querying. On a set of keys prone to this problem, their peak database query rate dropped from 17K/s to 1.3K/s (Scaling Memcache at Facebook).

The cache is a copy, never the source

The database is the record. The cache is a fast copy you can throw away. Design so that if the whole cache disappeared right now, you'd be slower for a few minutes and lose nothing. Azure's guide adds two cases where cache-aside isn't worth it: when most requests miss anyway, and when the data is sensitive enough that it shouldn't sit in a shared cache.

Step 4: When one machine can't hold the writes, partition and shard

Everything so far scales reads and keeps one primary for writes. At some point (for most teams, later than they fear) the write volume or the sheer size of the data outgrows one machine. Then you have to split the data itself. There are a few ways to do that, from mild to drastic.

Partitioning inside one database comes first. PostgreSQL can split a big table into range, list or hash partitions on the same server. It helps when most queries hit a few partitions, and dropping an old partition is far faster than a bulk DELETE and skips the VACUUM cost. The docs' rule of thumb: it's usually worth it only once the table is larger than the server's physical memory (Table Partitioning).

Vertical partitioning moves columns or whole tables to another database, like a huge, rarely read blob column or an audit log. Taken across a whole company, that's database-per-service, where each service owns its own slice.

Sharding splits the rows of one logical table across several databases by a shard key: user_id by hash, customers by region, orders by date range. Each shard is a normal database holding its share of the rows.

A shard router uses a shard key, here user_id modulo three, to decide which of three independent database shards holds each row. THE SHARD KEY IS THE DECISION THAT'S HARDEST TO TAKE BACK Shard router key → which shard? Shard 0 user_id % 3 == 0 Shard 1 user_id % 3 == 1 Shard 2 user_id % 3 == 2 good key → most queries hit one shard · bad key → hot shard + scatter-gather
Sharding spreads the rows of one table over independent databases by a shard key. With a good key most queries touch one shard. With a bad one you get a hot shard and slow queries that have to ask every shard.

Choosing the shard key deserves more time than any other decision on this page. A good key spreads load evenly, so one shard doesn't melt while the rest sit idle, and it matches your most common query, so that query lands on one shard. Notion's write-up is a nice real example: in 2021 they split their Postgres into 480 logical shards over 32 physical databases, keyed by workspace ID, because every block belongs to exactly one workspace and people usually work inside one workspace at a time. One of their lessons is "Shard earlier": by the time they moved, the old database was so loaded that even backfilling the new key column would have made things worse (Herding elephants: Lessons learned from sharding Postgres at Notion). So "later than you fear" doesn't mean "never": watch the signals and plan before you're in trouble.

Nguyen Le Phong points at a large map covered in colored markers and database icons while two colleagues think through how to split the data.
The hard part of sharding happens before the migration: picking a key that spreads the load and still answers the questions the product asks every day.

The bill is real, which is why sharding sits at the top:

  • Cross-shard queries get slow. "Top 10 orders across all customers" now means asking every shard and merging the answers.
  • Cross-shard transactions go away. You're back to sagas and eventual consistency, only now inside your storage layer.
  • Resharding is a project. Splitting a hot shard or changing the key means moving live data without downtime. Notion picked 480 logical shards partly because 480 divides evenly by many numbers, so they could grow from 32 hosts to 40 or 48 and keep the shards balanced.

For the detailed version (key strategies, hotspots and rebalancing), see Database Sharding: When It's Worth It and What It Costs.

SQL or NoSQL? Pick by access pattern

At some point someone will say you need to "move to NoSQL to scale." Usually that's the wrong reason. A relational database that has climbed this ladder goes a long way, and the Notion example above is plain sharded Postgres.

Reach for a different store when the access pattern is different. A key-value store for huge volumes of simple lookups. A document store for nested data that changes shape often. A search engine for full-text search. A time-series database for metrics. A wide-column store for heavy writes with a known query shape. Each one is good at something relational databases do awkwardly.

A sensible default

Stay on your relational database longer than the internet suggests. Using the right store for each job is a good idea at scale, but every new datastore is one more thing to run, back up, monitor and keep consistent with the others. Add the second one when a specific access pattern needs it.

Climb the ladder in order

What you're seeingThe cheapest fix that works
One endpoint is slowRead its query plan with EXPLAIN ANALYZE, add the missing index, kill the N+1
The whole database is close to its CPU or RAM limitMove to a bigger instance first
Reads are the bottleneck, writes are fineRead replicas, with must-be-fresh reads routed to the primary
The same expensive reads, again and againA cache in front (cache-aside plus a TTL)
One table is huge but the server copesPartition it inside the same database
Writes or data size exceed one machineShard by a carefully chosen key
One access pattern fights the relational modelAdd a purpose-built store, and accept that you now run it

What this looks like at different sizes

  • Solo or early startup: one database, good indexes, regular backups and a restore you've actually tested. That's the whole strategy, and it's the right one. The common mistake here is sharding for traffic you don't have yet.
  • Growing company: add a read replica once reads dominate (it doubles as a failover option). Cache the few hot paths that are obvious from your metrics. Scale the primary up when you have to. Watch write volume and table size so sharding is a planned project, and when the time comes, spend real time on the key.
  • Large organization: replicas, cache tiers and sharding (or a managed distributed SQL database that shards for you) are normal parts of the setup. The work moves to operations: who owns shard keys, cache invalidation as a platform service, automatic failover, capacity planning. Multiple datastores here should be a deliberate choice, with an owner for each.

Try this week

  • Pull your five slowest queries and run EXPLAIN ANALYZE on each. Look for sequential scans on big tables.
  • If you use replicas, list the screens where users look at something they just changed, and check where those reads go.
  • Add an alert on replication lag if you don't have one.
  • Check your cache writes: does the code update the database first and then delete the key?
  • Write down which table you'd shard first and by what key. You don't have to do it, but you'll know what to watch.

Scaling the data layer is mostly about not doing the exciting thing first. It sits next to two other questions worth reading about: who owns the data once you split services, and how the system keeps working when one of those pieces fails.

What did you think?

Frequently asked questions

Should I add an index or buy a bigger database server first?
Read the query plan first. In PostgreSQL, EXPLAIN ANALYZE runs the query and shows where time goes. A sequential scan over a big table usually means a missing index, which is a one-line migration. Move to a bigger instance only when the whole machine is the limit: CPU pinned, the working set no longer fits in RAM, or disk I/O maxed out.
What is replication lag and how do I handle it?
Read replicas copy the primary's changes asynchronously, so they always run a little behind, and the gap grows under heavy load. Send reads that must show a user's latest change to the primary (for example, for a short window after they write), let feeds, search and reports read from replicas, and alert on the lag metric.
When should I shard a database?
When write volume or data size outgrows one machine after you've used indexes, a bigger instance, replicas, caching and in-database partitioning. Don't leave it until the database is struggling, though: Notion's write-up lists "Shard earlier" as a lesson, because their overloaded database made the migration harder. Spend most of the design time on the shard key.