System designPatterns8 min read

Scaling Writes

Reads can be copied: add a replica or a cache and every copy serves traffic. Writes cannot. Every write has to land somewhere authoritative, be made durable and usually be replicated, so write-heavy systems hit limits that read tricks do not fix. This lesson is for software engineers preparing for system design interviews. It covers the moves that raise write capacity, in order of complexity, and the follow-ups interviewers ask about each.

It builds on Scaling Data for partitioning and replication, and on Choosing and Scaling a Database for B-tree and LSM storage engines.

Why writes are the hard direction

A single durable write involves more work than it looks:

  • The database appends to its write-ahead log and flushes it to disk before acknowledging the commit. Group commit lets concurrent transactions share one flush, but a client committing one row at a time waits for a flush on every row.

  • Every index on the table is updated too. A table with four indexes does five writes per insert.

  • Replication sends the write to every replica; with three copies, the network and disks see it three times.

  • Row locks serialize concurrent updates to the same row, so one popular row caps throughput no matter how big the machine is.

This multiplication is called write amplification, and the techniques below mostly work by reducing it, spreading it across machines, or deferring it.

The worked scenario

Keep one example in mind for the rest of the lesson: a delivery app where every active driver's phone reports its location.

1,000,000 active drivers x 1 ping every 4 seconds = 250,000 writes/s
each ping ~100 bytes                              = 25 MB/s of ingest
250,000 x 86,400 seconds                          = 21.6 billion pings/day
21.6 billion x 100 bytes                          ~ 2.2 TB/day of raw history

Two different needs hide inside that stream. The dispatch system needs every driver's latest location, right now. Analytics and dispute resolution need the history, but minutes of delay are fine. Splitting those two is the first and most valuable move, because they want completely different storage.

The moves, cheapest first

1. Write less

Before scaling the write path, shrink it. A driver waiting at a restaurant reports the same coordinates dozens of times. If the phone, or the ingest service, drops pings that moved less than 10 meters since the last stored point and sends a heartbeat at most every 30 seconds instead, history writes fall sharply for stationary drivers without losing anything the business uses. The general move is to decide what precision the product actually needs and stop storing the rest.

2. Overwrite the latest state in a fast store

The latest location is one small value per driver that gets replaced, never accumulated. An in-memory key-value store keyed by driverId fits it:

1,000,000 drivers x ~100 bytes ~ 100 MB of data

The data fits on one machine; the write rate does not, comfortably, so partition the keys by hash(driverId) across several nodes, for example five nodes at about 50,000 writes per second each (a per-node figure you would confirm with a load test). An overwrite in memory has no index maintenance, no growing table and no lock contention between drivers, because each driver only touches their own key. Durability barely matters here: if a node dies and loses its keys, every affected driver's next ping, at most 4 seconds later, rebuilds them. Say that out loud, because it is the reason an in-memory store is acceptable for this path and not for the history.

3. Batch the history

Inserting 250,000 rows per second one transaction at a time pays the commit cost 250,000 times. Batching 1,000 rows per insert pays it 250 times per second. The cost is latency (a ping waits up to the batch window, say one second, before it is durable) and a decision about failure: if the ingest process crashes with a half-filled batch, those pings are lost unless they were first written to a durable log. Which leads to the next move.

4. Put an append-only log in front

A durable, partitioned log (Kafka-style) is the standard shock absorber for write-heavy pipelines. Producers append pings to it; consumers read in order and write batches to the history store at their own pace. Appending to a log is sequential I/O, the cheapest kind of durable write, and the log decouples the rate pings arrive from the rate the database can accept them.

The partition key matters. Partitioning by driverId keeps each driver's pings in order and spreads load evenly. Partitioning by city would put a whole metro area on one partition. Partitioning by timestamp would send every current write to the newest partition.

5. Choose write-optimized storage for the history

Append-heavy, rarely updated, time-ordered data suits storage built on log-structured merge trees (wide-column stores such as Cassandra) or columnar files in object storage partitioned by day. LSM engines turn random writes into sequential ones, at the price of background compaction that rewrites data several times: a different kind of write amplification, paid later and off the request path. Choosing and Scaling a Database explains the trade-off.

6. Shard by the write key

When one primary cannot take the write rate, split it by a key that spreads writes evenly and keeps each write on one shard. For history, a key of (driverId, day) spreads writes across shards and still lets "show this driver's route on Tuesday" read from one place. If the store partitions by key range, avoid monotonically increasing keys such as timestamps or auto-increment ids: every new write falls in the same "latest" range, which becomes a hotspot while the others sit idle. Hash partitioning spreads such keys evenly, at the price of turning a time-range query into a query to every shard.

Bursts and backpressure

Traffic is not flat. Say the evening rush triples pings to 750,000 per second for an hour, while the history consumers are sized for 400,000 per second.

excess during the rush: 750,000 - 400,000 = 350,000 pings/s
backlog after one hour: 350,000 x 3,600   = 1.26 billion pings (~126 GB)
drain rate afterwards:  400,000 - 250,000 = 150,000 pings/s
time to drain:          1.26 billion / 150,000 ~ 8,400 s ~ 2.3 hours

That is acceptable for history, because the log holds the backlog durably and nobody needs it within the hour. It would be unacceptable for the latest-location path, which is exactly why that path writes directly to the in-memory store and never sits behind the queue.

When a backlog grows past what you can tolerate, push back on the source rather than falling over. Here the ingest service can tell the app, in each response, to report every 8 seconds instead of 4, halving load during the peak. Elsewhere backpressure means returning 429 with a Retry-After header, or shedding low-priority writes first. The point is that the system degrades on purpose.

Counters at scale

A counter that everyone increments is the classic single-row bottleneck. "Deliveries completed today in this city" might take 2,000 increments per second at peak, all locking the same row.

A sharded counter splits it into, say, 16 rows. Each increment picks one at random, so each row takes about 125 increments per second and lock waits mostly disappear. Reads sum the 16 rows, which is cheap because reads of this counter are rare compared with writes. If an approximate value is acceptable, buffer increments in each application server and flush the sum every second instead: one write per server per second, at the cost of losing up to a second of counts if a server dies. How to Run a Deep Dive covers the exact versus approximate choice.

Weak and strong answers

Prompt: "Drivers report their location every 4 seconds. Design the storage."

Weak answer: "Each ping is inserted into a locations table, with a Kafka queue in front and the table sharded by timestamp." It never states the rate, sends the dispatch system's "where is this driver now" query through an ever-growing table, and picks the one shard key that puts every current write on one shard.

Strong answer: 250,000 writes per second (requirements); latest location overwritten in a partitioned in-memory store, history appended to a log and batched into LSM or columnar storage (high-level design); a history shard key of (driverId, day) and the burst and drain arithmetic (deep dive and scalability); and an explicit choice to accept minutes of lag on history and one ping of staleness on the latest location (trade-offs). The same components, but each one justified by a number.

Follow-ups to expect

  • "What if the ingest service crashes mid-batch?" Pings were appended to the durable log first; consumers commit their offset only after the batch is written, so a crash replays the batch. Writes must therefore be idempotent, for example keyed by (driverId, timestamp).

  • "How do you keep a driver's pings in order?" Partition the log by driverId and keep one consumer per partition.

  • "One city has 40 percent of drivers. Does your shard key survive?" Yes, because the key is the driver, not the city. A city-keyed design would not.

  • "How stale is the latest location?" One ping interval, about 4 seconds, plus a few milliseconds of write time.

What changes with seniority

A mid-level candidate is expected to batch writes, add a queue, and shard by a sensible key. A senior candidate separates the latest-state and history paths, does the burst and backlog arithmetic, and explains failure and replay. A staff-level candidate also designs the degradation: which writes are shed first, how backpressure reaches the clients, and how the team notices a growing backlog before users do.

Mistakes that cost points

  • Treating all writes alike. Latest state and history have different freshness, durability and storage needs; one table for both serves neither.

  • Sharding by time or by a skewed attribute. The newest shard, or the biggest city, takes all the load.

  • Adding a queue without sizing it. Say how fast it fills, how much it holds and how long it takes to drain.

  • Forgetting idempotency. Every retry or replay path writes twice unless the write is keyed to be safe to repeat.

Practice it

Take 15 minutes to redo the arithmetic above for a different stream, such as likes on a social app at 50,000 per second with a 5x spike, and decide which path needs to be real time. Then practice on Design a Real-Time Chat System, where message writes, ordering and fan-out all come up.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Real-Time Updates

    Choose between polling, long polling, server-sent events and WebSockets, route each update to the server holding the recipient's connection, and handle ordering, reconnection, missed messages and presence.

    7 min read

  • Dealing with Contention: When Everyone Wants the Last Seat

    Work out how many updates per second a hot row can take, then pick and defend the right fix: pessimistic or optimistic locking, atomic conditional updates, expiring holds, fenced distributed locks, queues or split stock.

    8 min read

  • Multi-Step Processes and Long-Running Jobs

    Design flows that span services so they finish or cleanly undo themselves, with sagas, compensations, idempotent retries, the outbox pattern and durable workflows, and run long jobs with status, heartbeats and dead-letter queues.

    8 min read

  • Handling Large Files: Uploads, Processing and Delivery

    Keep large files off your API servers with presigned and resumable multipart uploads, keep metadata and stored bytes consistent, process files after upload, and deliver them through a CDN with range requests.

    7 min read