Summary#
Writes are harder to scale than reads. A read can be served from any copy, but a write must change the one authoritative copy of a piece of data, durably and in order, and then every replica, index and cache must catch up. Scaling writes is the pattern for growing past what one database server can absorb. Like scaling reads, it is a ladder. First, make each write cheaper on one machine: fewer indexes, group commit, bigger and faster hardware, and a write-optimised database such as an LSM-based store. Next, shard: split data by a well-chosen partition key so that writes spread over many machines, and split unrelated data into separate databases. Then smooth bursts with queues, and reduce the number of writes by batching, coalescing in a write-behind buffer, and aggregating hierarchically before data reaches storage. Special techniques handle the hardest cases. Sharded counters and hot-key splitting deal with a single key too popular for one shard. Load shedding protects the system by dropping low-value writes when it is overwhelmed.
Why It Exists#
Picture a ride-hailing app. Every active driver's phone reports its location every 4 seconds. With 1 million drivers online at peak, that is 250,000 location writes per second, before counting trips, payments and ratings. Or an ad network, where every click must be recorded for billing, at a million clicks per second during a big sporting event. Or a social app on New Year's Eve, when message rates jump tenfold in one minute. Interviewers love to take a design that works at modest scale and ask: "Now it is a runaway success. Where does it break?" On the write side, it usually breaks quickly.
Writes resist the techniques that scale reads:
- You cannot cache a write. A write must reach durable storage, or it is not a write. A cache in front of writes either delays durability, which is write-behind with its risks, or does nothing.
- Replicas do not help. Every replica must apply every write, so adding replicas adds work rather than spreading it. See Replication.
- Each write has fixed costs. A durable commit appends to a log and forces it to disk with fsync, updates every index on the table, may take locks, and is shipped to replicas. Some of these costs are per transaction, whatever the transaction's size.
- Writes contend. Two writes to the same row must be ordered. A popular row, a global counter or the newest page of a time-ordered index becomes a single point that every writer queues behind.
- Writes come in bursts. A sale, a match, a push notification or a viral post can raise write rates by ten times within seconds, and the database cannot be scaled that fast.
The physical limits are concrete. A single NVMe SSD sustains perhaps a few hundred thousand random writes per second and a few gigabytes per second of sequential writes. A forced flush with fsync costs tens of microseconds on enterprise SSDs with power-loss protection, and milliseconds on cloud network storage. A single relational database server on good hardware commonly sustains somewhere from 5,000 to 50,000 write transactions per second, depending on transaction size, indexes and durability settings. Beyond that you need either cheaper writes, fewer writes, or more machines each owning a part of the data.
How It Works#
The strategies form a ladder, from staying on one machine to spreading writes across many and reducing how many writes happen at all. Climb only as far as the numbers require. Each rung adds complexity, and sharding in particular is hard to undo.
Write-bottleneck signals#
Before scaling writes, confirm that writes are what is failing. The signs are:
- Write latency rises with load. Commit time, from the application's point of view, grows from 2 ms to 50 ms at peak, while reads stay fast.
- The disk is busy with writes. Write IOPS or bytes per second approach the volume's limit, the write-ahead log (WAL) device shows high utilisation, or cloud volumes hit their provisioned IOPS ceiling and start throttling.
- Lock and latch waits grow. Many transactions wait on the same rows, the same index page or the same sequence, which points to contention on a few keys rather than to raw throughput.
- Replicas fall behind. Replication lag growing at peak is often the first visible sign that the write rate exceeds what replicas can apply.
- Background work cannot keep up. Checkpoints take longer and cause latency spikes, vacuum falls behind in PostgreSQL, or compaction backlogs grow in LSM stores.
- Queues grow without draining. Consumers writing to the database fall further behind every peak and never fully catch up overnight.
Write-bottleneck signals, in depth#
Estimate the write load first. Write the numbers down per data type, because they vary enormously. For a ride-hailing app with 1 million drivers sending a location every 4 seconds, that is 250,000 writes per second of roughly 100 bytes each, 25 MB/s. Trips: perhaps 20 million a day, with a dozen state changes each, about 3,000 writes per second on average and three times that at peak. Payments: one per trip, a few hundred per second, but each one must be durable, consistent and never duplicated. These three need different solutions. Location updates are high volume, small, and overwrite-friendly: only the latest position matters, and losing one is harmless. Payments are low volume and must be exact. Designing one write path for all of them either wastes money or loses money.
Distinguish throughput from contention. Throughput problems show up as saturated disks or CPUs with writes spread across many keys. Contention problems show up as lock waits and serialisation failures on a few keys while the hardware is underused. The fixes differ. Throughput needs cheaper writes, fewer writes or more machines. Contention needs the hot key to be split, the update made commutative, or the writes serialised through a queue; see Dealing with Contention.
Measure bursts, not only averages. A system that averages 10,000 writes per second may receive 100,000 per second for 30 seconds after a push notification. Look at per-second peaks in the metrics, not per-minute averages, which hide spikes. The burst ratio, peak over average, decides whether you need a buffer (rung 4) or permanent capacity (rung 3).
Know your durability requirement. "Every write must survive a power failure" means each commit waits for fsync, or for a quorum of replicas to acknowledge it. "Losing the last second of writes on a crash is acceptable" allows much cheaper commits. Many systems have both kinds of data. Ask, for each write type, what happens if it is lost, duplicated or delayed by a minute. The answers decide which rungs are allowed.
Rung 1: Optimise writes on one node#
Before adding machines, make each write cost less and fit more of them on the machine you have.
- Scale up the right resource. Writes are bound by storage latency and bandwidth more than by CPU. Local NVMe SSDs, or provisioned-IOPS cloud volumes, and a separate fast device for the WAL often double write capacity. More memory lets the database delay and combine page writes.
- Drop unneeded indexes. Each secondary index is another structure to update on every insert. A table with eight indexes does roughly nine writes per row. Remove indexes that queries do not use, and move analytical queries to another store so their indexes do not burden the primary.
- Group commit. Many transactions committing at the same moment can share one fsync. Most databases do this automatically, and it is why throughput rises with concurrency up to a point.
- Batch statements. Insert 500 rows in one statement or one transaction instead of 500 transactions. Use bulk-load paths such as PostgreSQL's
COPYfor large imports. - Shape the schema for writes. Prefer appending new rows to updating hot rows in place. Avoid wide rows that are rewritten in full for small changes. In PostgreSQL, leave free space in pages (
fillfactor) so updates that do not touch indexed columns can stay on the same page as heap-only tuple (HOT) updates, avoiding index writes. - Relax durability where it is safe. PostgreSQL's
synchronous_commit = off, per transaction or per session, acknowledges a commit before its WAL is flushed. A crash can lose the last fraction of a second of those commits but never corrupts the database. It is ideal for low-value writes such as page views or telemetry, and wrong for payments.
Rung 1, in depth#
Anatomy of a durable write. Following one INSERT through a typical relational database shows where time goes:
- Parse, plan and lock: microseconds, plus any wait for row locks.
- Modify pages in memory: the heap page and one page per index, a few microseconds each if they are cached. If a page is not in memory, it must first be read from disk.
- Append WAL records for each change to the in-memory WAL buffer.
- Commit: flush the WAL to stable storage with fsync. This is the dominant cost: tens of microseconds on local enterprise NVMe, roughly 0.5 to 2 ms on network-attached cloud volumes, and more with synchronous replication, which adds a network round trip to a standby.
- Later, in the background, write the dirty data pages to their places on disk at checkpoints. Those are random writes, but they are batched and deferred.
Only step 4 is on the critical path for durability. This is why databases log changes sequentially and write pages lazily: the log turns random updates into sequential appends. See Storage Engines.
Group commit, worked. If one fsync takes 1 ms and each transaction does its own, a single connection commits at most 1,000 transactions per second. With group commit, the transactions that arrive while one flush is in progress share the next flush. With 50 concurrent connections, one flush might cover 20 to 50 commits, raising throughput to 20,000 to 50,000 commits per second at the same 1 ms flush cost, at the price of each commit waiting up to one flush interval. PostgreSQL's commit_delay and MySQL's binary log group commit tune this behaviour. The effect explains a common benchmarking surprise: a database that manages only 1,000 inserts per second from one client may manage 30,000 from 64.
Checkpoints and write stalls. At each checkpoint, the database must write every dirty page to disk. If checkpoints are too frequent, the same hot pages are written again and again. If they are too large and sudden, they flood the disk and stall foreground writes. Tune checkpoint intervals and spreading, such as PostgreSQL's checkpoint_completion_target, and give the WAL its own capacity. Note also that PostgreSQL writes a full page image to the WAL the first time each page changes after a checkpoint, which protects against torn pages but multiplies WAL volume right after checkpoints.
Hardware ceilings to know. A large cloud database instance can sustain tens of thousands of write transactions per second on fast storage. Provisioned-IOPS volumes cap out at limits set by the provider, so check them before assuming a machine's disk is the limit. Beyond one machine's IOPS or WAL bandwidth, no tuning helps, and you move to rung 2 or 3.
Rung 2: Choose a write-optimised store#
A classic relational database uses B-trees, which update pages in place. Each random insert lands on some leaf page, and when the working set does not fit in memory, inserts cost random disk I/O. Several families of databases are built specifically to absorb heavy writes:
- LSM-tree stores, such as Cassandra, ScyllaDB, HBase, and RocksDB as an embedded engine. They write each change to a commit log and an in-memory table, flush sorted immutable files to disk sequentially, and merge files in the background. Writes are sequential and fast. Reads may check several files, helped by Bloom filters.
- Append-only logs, such as Kafka. They are the ultimate write-optimised store: every write appends to the end of a partition, and consumers read in order. They are ideal as an ingestion buffer and as the source of truth for event streams; see Pub/Sub and Event Streaming.
- Time-series databases, such as InfluxDB, TimescaleDB and Prometheus's storage. They are tuned for timestamped appends with compression by series and by time; see Time-Series Databases.
- Columnar analytical stores, such as ClickHouse, Apache Druid and Apache Pinot. They ingest high volumes of events in batches and serve aggregations, provided writes arrive in large blocks rather than row by row.
- Managed key-value stores, such as DynamoDB and Bigtable. They partition automatically and scale writes horizontally per key, with limits per partition that matter for hot keys.
Rung 2, in depth#
Why LSM trees write faster. A B-tree insert into a table much larger than memory may require reading a leaf page from disk, modifying it and eventually writing the whole page back: one random read and one random page write for a 100-byte row. An LSM tree appends the row to its commit log, which is sequential, and inserts it into a sorted in-memory structure. When the memtable fills, typically at tens to hundreds of megabytes, it is written out as one sorted file in a single sequential write. Sequential bandwidth on SSDs is far higher than random small-write throughput, and on spinning disks the difference is a hundredfold or more. The idea comes from "The Log-Structured Merge-Tree (LSM-Tree)" by Patrick O'Neil, Edward Cheng, Dieter Gawlick and Elizabeth O'Neil (Acta Informatica, 1996), and was popularised by Google's Bigtable (OSDI 2006).
The cost is paid later, in compaction. Background compaction merges files to discard overwritten and deleted values and to keep reads fast. Every byte may be rewritten several times as it moves down the levels. That is write amplification, commonly in the range of 10 to 30 times for leveled compaction, and lower for size-tiered compaction at the cost of more space and slower reads. If ingestion outpaces compaction, files pile up, reads slow, and engines eventually throttle writes, which RocksDB calls write stalls. Sizing an LSM cluster means sizing for compaction throughput, not only for ingestion. See Storage Engines for the full comparison.
Matching the store to the write shape.
| Write shape | Good fit | Why |
|---|---|---|
| High-volume appends of events or messages, read by key and time | Cassandra, ScyllaDB, Bigtable, DynamoDB | Partitioned LSM storage, writes spread by partition key |
| Metrics and telemetry | Time-series databases, ClickHouse | Compression by series, batched columnar ingestion |
| Event streams consumed by many systems | Kafka, Redpanda, Kinesis | Sequential append, retention, replay |
| Latest value per key, overwritten often | Redis, DynamoDB, Cassandra | Cheap overwrites; old versions compacted away |
| Transactions with invariants across rows | Sharded PostgreSQL or MySQL, distributed SQL | Constraints and transactions, at higher cost per write |
Discord's message store. Discord has described storing trillions of messages, first in Cassandra and then, after a migration completed in 2022, in ScyllaDB, a Cassandra-compatible LSM database written in C++. The migration came with a data-services layer in Rust that coalesced concurrent requests for the same data. Messages are partitioned by channel and a time bucket, so that one huge channel does not grow a single unbounded partition. The design shows rung 2 and rung 3 together: a write-optimised engine plus a partition key chosen to spread writes and bound partition size.
Rung 3: Shard and partition#
Horizontal sharding splits rows of the same table across many databases by a partition key, so each shard handles only its share of writes. Ten shards give roughly ten times the write capacity, if the key spreads load evenly. See Partitioning and Sharding for hashing, ranges and routing.
Vertical partitioning splits different data into different databases: user profiles in one, likes in another, analytics events in a third. Each workload gets hardware and a store suited to it, and a flood of low-value writes, such as view events, cannot slow down high-value ones, such as orders. Splitting by service boundary in a microservices architecture is vertical partitioning by another name.
The partition key decides whether sharding works:
- High cardinality. There must be many more distinct key values than shards, so the load can spread. Sharding by country with 200 values, half the traffic in a few countries, does not work.
- Even load. Values must receive similar write rates, or the busy ones must be spread further. User ID usually works for user-generated writes; celebrity accounts are the exception to handle.
- Locality for the dominant operations. Data written and read together should share a key, so a transaction or query touches one shard. Shard orders by customer ID if most transactions involve one customer.
- Not monotonic. A key that increases over time, such as a timestamp or an auto-increment ID, sends every new write to the shard holding the latest range. Hash it, or prefix it with something that spreads.
Sharding, in depth#
Good and bad keys, by example. For a metrics system, sharding by metric_name alone puts the most popular metric, such as request counts across the whole fleet, on one shard. Sharding by (metric_name, host) spreads it across hosts. For a chat system, sharding messages by message_id spreads writes perfectly but scatters a conversation across all shards, so reading a channel's recent messages hits every shard. Sharding by channel_id keeps a conversation together but makes a huge channel a hot shard, which is why Discord added a time bucket to the key. For an ad click system, sharding by ad_id keeps an ad's clicks together for aggregation, but a Super Bowl ad becomes a hot key. The right key is usually the one that serves the dominant access pattern, plus a plan for the few keys it treats badly.
Logical shards decouple data from machines. Map keys to a large, fixed number of logical shards, such as 4,096, and map logical shards to physical databases with a small, changeable table. Adding capacity then means moving some logical shards to a new machine, not rehashing every key. Instagram's engineering team described this design in 2012: several thousand logical shards held as PostgreSQL schemas, spread over far fewer physical servers, with IDs that embed the logical shard number; see Unique ID Generation. Consistent hashing achieves a similar effect with a ring of virtual nodes; see Consistent Hashing.
Cross-shard writes are expensive. A write that must atomically update two shards needs a distributed transaction such as two-phase commit, or a saga with compensations; see Distributed Transactions. Choose the key so the common transactions stay within one shard, and accept asynchronous, eventually consistent updates for the rest, such as updating a follower count on another shard through an event.
Range versus hash partitioning for writes. Hash partitioning spreads writes evenly but loses ordering, so range scans touch all shards. Range partitioning keeps keys ordered, which is good for scans, but concentrates sequential inserts on the last range. Systems such as Bigtable, HBase and CockroachDB split ranges automatically as they grow and move them between nodes, but a strictly increasing key still writes to one range at a time. The usual fix is a hash or bucket prefix in front of the time component, at the cost of more complex range queries.
Resharding when you need more shards#
Sooner or later the shards fill up or run hot, and you must add more. "How do you reshard without downtime?" is a standard deep-dive question. With logical shards or consistent hashing, resharding means moving a subset of data to new machines while writes continue. The standard procedure is:
- Provision the new shards and decide which logical shards or key ranges move.
- Copy a snapshot of the moving data to the new shards in the background.
- Stream changes made since the snapshot, from the source's change log, so the copy catches up and stays current. Alternatively, have the application double-write to the old and new locations.
- Verify that the copies match, with row counts and checksums by key range.
- Cut over: briefly pause writes to the moving range, typically for seconds, let the stream drain, update the shard map, and resume, so that writes now go to the new shard.
- Clean up: keep the old copy for a while for rollback, then delete it.
Resharding, in depth#
Tools that do it for you. Vitess, the MySQL sharding system created at YouTube, performs this procedure with its VReplication workflows: copy, catch up from the binary log, verify with VDiff and switch traffic. Managed stores such as DynamoDB split partitions automatically. Distributed SQL databases split and rebalance ranges continuously. If you shard a relational database yourself, budget real engineering time for a resharding tool, because you will need it more than once.
Double writes and their traps. Application double-writing is simple to explain but has subtle failure modes. If the write to the new shard fails after the old one succeeded, the copies diverge. If two writes to the same key are applied in different orders on the two copies, they diverge. Treat the old location as the source of truth until cutover, make the new-location write idempotent and retryable, and run a verifier that compares and repairs. Change-data-capture-based copying avoids most of these problems because it replays the source's own commit order. See Data Migration.
Avoid resharding by over-partitioning. Start with many more logical shards than you need, such as 1,000 times the initial number of machines, so growth means moving logical shards, not splitting them. Splitting a logical shard later means rehashing its keys, which is the hard version of the problem.
Rung 4: Absorb bursts with queues#
If the average write rate fits your storage but the peaks do not, put a queue between the producers and the database. Producers append writes to a durable queue or log, such as Kafka, Amazon SQS, Kinesis or Redis Streams, at whatever rate they arrive. Consumers read from it and write to the database at the rate it can sustain. The queue absorbs the burst, and the database never sees more than its capacity. See Message Queues.
- The client gets an acknowledgement, not a result. The write is accepted, meaning durably queued, but it is not yet in the database. The API returns 202 Accepted, or the UI shows "processing". Reads right after the write may not see it.
- Consumers control the rate. Size the consumer pool and its batch size so the database stays at a safe utilisation. More consumers drain faster, until the database becomes the limit again.
- Ordering and idempotency. Partition the queue by entity key so writes for one entity are applied in order, and make consumer writes idempotent, because consumers redeliver messages after failures; see Delivery Semantics.
Queues are a cure for bursts, not for sustained overload. If the arrival rate stays above the drain rate, the backlog grows without bound, the delay between write and visibility grows with it, and eventually the queue's retention or storage limit is reached.
Queues for bursts, in depth#
Backlog arithmetic. Suppose the database can absorb 20,000 writes per second and normally receives 5,000. A flash sale brings 50,000 writes per second for 10 minutes. During the burst, the backlog grows at 30,000 per second, reaching 18 million messages after 600 seconds. After the burst, the consumers drain at 20,000 per second while 5,000 per second keep arriving, a net 15,000 per second, so clearing the backlog takes 1,200 seconds, 20 minutes. The worst-case delay is reached at the end of the burst: an item queued then waits roughly 18 million / 20,000 = 900 seconds, 15 minutes. Is a 15-minute delay acceptable? For analytics events, yes. For order confirmations, no, which means either more database capacity, or a separate fast path for orders and a queue for everything else.
Little's law and queue delay. The average time an item spends in the queue equals the average backlog divided by the throughput. Monitor both the backlog (consumer lag in Kafka) and the age of the oldest message, and alert on age, because age is what users experience.
Back-pressure versus buffering. A queue hides overload from producers, which is its purpose, but it also removes the natural signal that tells clients to slow down. Bound the queue, or monitor its age, and when it is too old, start rejecting or shedding at the entry point. That turns the queue into a shock absorber with a limit rather than a place where requests go to wait forever.
Slack's job queue. Slack has described putting Kafka in front of its Redis-based job queue after an incident in which a backlog overwhelmed Redis memory. Kafka, with its disk-backed, durable log, absorbs bursts of enqueued jobs, and a relay moves jobs into Redis at a rate the workers can handle. It is rung 4 applied to a job system rather than a database.
Rung 5: Batch, write behind and aggregate#
The most effective way to scale writes is to perform fewer of them. Three techniques reduce the number of storage writes without losing information that matters.
Batching. Combine many small writes into one larger write. A single multi-row INSERT of 1,000 rows costs far less than 1,000 single-row transactions, because the per-transaction overheads of parsing, round trips, locking and fsync are paid once. Kafka producers batch messages per partition, controlled by linger.ms and batch.size. Columnar stores such as ClickHouse expect inserts in blocks of thousands to millions of rows. Batching trades a little latency, the time spent waiting to fill a batch, for a large gain in throughput.
Write-behind, or write-back. The application writes to a fast in-memory store, such as Redis or an in-process buffer, and acknowledges immediately. A background process flushes the accumulated changes to the database later, in batches. When the same key changes many times between flushes, only the final value, or the sum of the changes, is written: that is coalescing. A like counter incremented 10,000 times in a second becomes one database write of +10,000.
Hierarchical aggregation. Aggregate at each level before passing data upwards. Edge servers count events for a few seconds and send totals, not raw events, to regional aggregators, which send per-region totals to a global store. Live reactions on a video stream, view counts, ad impressions and metrics all work this way. Raw events can still be archived cheaply to object storage for audit and reprocessing.
Batching, write-behind and aggregation, in depth#
Batch size and latency. If the per-batch overhead is o and the per-item cost is c, a batch of n items costs o + n × c, so the cost per item is o / n + c. With o = 2 ms and c = 0.02 ms, a batch of 1 costs 2.02 ms per item, a batch of 100 costs 0.04 ms per item, and a batch of 1,000 costs 0.022 ms. Beyond a few hundred items, the gain flattens while latency and the size of a failed batch keep growing. Flush on whichever comes first, size or time: for example, 500 items or 50 ms.
Write-behind risks. Until the flush, the only copy of the change is in memory. If the buffer's process crashes, those changes are lost. Mitigations, in increasing strength: flush frequently, every 100 ms to 1 second, to bound the loss. Use Redis with append-only persistence and replicas, so a node failure does not lose the buffer. Put the change in a durable log first, such as Kafka, and aggregate from the log, which is really rung 4 plus rung 5. Use write-behind only for data where a small, bounded loss or an approximate value is acceptable: counts, presence, last-seen times and analytics. Never use it for money.
Coalescing changes the semantics. Coalescing keeps the final value, or the sum, and drops the intermediate history. That is fine for "latest location" or "total likes". It is wrong where every event matters individually, such as bids, payments or audit logs. Then batch, but do not coalesce.
Aggregation windows. Aggregators sum over windows, such as 1 second or 1 minute. Events arrive late and out of order, so decide whether a window waits for stragglers, using watermarks in stream processors such as Flink, or is updated by later corrections. See Batch and Stream Processing. For billing-grade counts, such as ad clicks, a common design pairs a fast streaming aggregate with a periodic batch recount from the raw archive, and the batch result wins if they differ.
The arithmetic of aggregation. A live event with 10 million viewers sending one reaction every 10 seconds produces 1 million reactions per second. Stored raw, that is a million writes per second. Aggregated per stream, per reaction type and per second at 100 edge aggregators, the regional tier receives about 100 aggregators × 5 reaction types = 500 small messages per second for the stream, and the store receives 5 rows per second. Disney+ Hotstar has written about delivering billions of emoji reactions during cricket matches by aggregating reactions in a streaming pipeline over short windows before sending results to viewers, an example of this shape.
Rung 6: Sharded counters and hot keys#
Sharding spreads keys across machines, but one key always lives on one shard. A single row updated thousands of times per second, such as a viral post's like count, a global "tickets sold" counter or a celebrity's follower count, is limited by how fast one shard can update one row, often a few hundred to a few thousand updates per second under row locking. Adding shards does nothing for it.
Sharded counters split one logical counter into N physical sub-counters, say 20 rows likes:post9:0 to likes:post9:19. Each increment goes to a random sub-counter, so writes spread over N rows, and potentially N shards. Reading the total sums the N sub-counters, which is cheap if reads are cached. Google App Engine's documentation popularised this technique for its datastore, which had a limit on writes per second to a single entity group.
For other kinds of hot keys, the reference strategies are:
- Split all keys. Always append a suffix from 0 to k−1 to the key, chosen at random or by hashing a secondary attribute, so every key is spread over k partitions from the start. It is simple and handles any key that becomes hot, but every read must query k partitions and merge.
- Split hot keys dynamically. Write normally, detect keys that become hot, and only then start spreading their writes across k sub-keys. Record which keys are split, and how many ways, in a small metadata table or cache that readers check, so cold keys keep single-partition reads. It is more complex, but most reads stay cheap.
Sharded counters and hot keys, in depth#
Choosing N. If one row sustains about 500 updates per second, and the hottest counter may receive 20,000 increments per second, N must be at least 40, and 64 gives headroom. A read then sums 64 rows. If reads are rare or cached, that is fine. If every page view reads the count, cache the sum for a second, or maintain it asynchronously in a separate row that a background job updates.
Detecting hot keys in write paths. Count writes per key in each partition with a heavy-hitters sketch such as Count-Min or Space-Saving, report the top keys every few seconds, and mark keys above a threshold as hot; see Probabilistic Data Structures. Splitting decisions must propagate to every writer before they take effect, and readers must know to merge, so the metadata change should be versioned and applied in two steps: readers first, writers second.
How managed stores handle heat. The 2022 paper "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service" by Mostafa Elhemali and colleagues (USENIX ATC 2022) describes how DynamoDB moved from static per-partition throughput to global admission control and adaptive capacity, and how it splits partitions for heat, by key range, when one part of a partition is hot. Splitting only helps when the heat is spread over many keys in the partition. A single item still has a per-item throughput limit, so applications must still split truly hot single keys themselves, with sharded counters or write sharding by suffix.
Hotspot accounts in payments. A merchant account receiving thousands of payments per second is a hot row in a ledger, because every payment updates its balance. Techniques include splitting the merchant's account into many sub-accounts that payments are spread across and periodically consolidating them, and recording payments as append-only ledger entries with the balance computed and cached asynchronously, so no single row is updated per payment. Both trade an immediately exact running balance for throughput, which is acceptable for incoming funds to a merchant but not for an outgoing balance check that must prevent overdrafts.
Commutative updates avoid contention. Increments commute: the order in which +1s are applied does not change the result. That is what makes sharded counters correct without coordination. Operations that do not commute, such as "set the price" or "reserve the last seat", cannot be split this way and need contention control instead. The CRDT literature formalises which data types can be merged without coordination, such as grow-only and positive-negative counters; see Collaborative Editing and CRDTs.
Rung 7: Load shedding and prioritisation#
When load exceeds capacity even after all of the above, the system must choose what not to do. Load shedding deliberately rejects or drops some work so that the rest succeeds. Without it, every request slows down, timeouts and retries multiply the load, and the whole system fails together.
- Classify writes by value. Orders, payments and messages are critical. Likes and profile edits are important but can be retried. View counts, analytics events, presence and location pings are deferrable or droppable.
- Shed the lowest class first. Under pressure, sample analytics events instead of recording all of them, drop every other location ping, defer non-critical writes to a queue, and reject low-priority requests with HTTP 429 or 503 and a
Retry-Afterheader. - Shed early and cheaply. Reject at the edge or the load balancer, before work is done, rather than after a request has consumed database capacity.
- Protect the critical path with separate capacity. Give critical writes their own queues, connection pools or even databases, so that a flood of low-value writes cannot consume their capacity. This is the bulkhead pattern; see Resilience Patterns.
Load shedding, in depth#
What to measure for shedding decisions. CPU and queue depth are useful signals, but latency and in-flight concurrency respond fastest. A common technique is an adaptive concurrency limit: the server tracks request latency, estimates the concurrency at which latency starts to rise, and rejects requests beyond that limit, in the spirit of TCP congestion control. Netflix open-sourced a library for this, called concurrency-limits. Another is to reject requests that have already waited in a queue longer than their client's timeout, because the client has given up and the work is wasted.
Clients must cooperate. Shedding only helps if clients do not immediately retry. Clients should use exponential backoff with jitter, honour Retry-After, and use retry budgets that cap retries as a share of normal traffic. Otherwise rejected requests return at once, multiplied. See Resilience Patterns and Rate Limiting.
Degrade gracefully, and say so. A product can usually lose features rather than fail: show approximate counts, delay notification emails, pause recommendation updates. Decide the degradation order in advance and practise it, so on-call engineers can flip switches rather than invent policy mid-incident.
Sample instead of dropping blindly. For analytics and telemetry, record a fixed fraction of events, say 1 in 10, and scale the counts up by 10. The totals stay statistically sound, and the write load falls tenfold. Keep the sampling rate in each record, so later queries can correct for it, and never sample events that are billed.
Worked example: ingesting ad clicks at 600,000 per second#
An ad network records every click for billing and reporting. Requirements: 10 billion clicks a day, about 120,000 per second on average and 600,000 per second at peak during major live events. Each click record is about 300 bytes. No billed click may be lost or double-counted. Advertisers see per-minute click counts per ad within about a minute. The most popular ad during a final can draw 50,000 clicks per second on its own.
Why the naive design fails. Writing each click as a row into a relational database and updating a clicks counter on the ad row would mean 600,000 inserts and 600,000 updates per second at peak. That is far beyond any single database, and the hottest ad's counter row would receive 50,000 updates per second, two orders of magnitude more than one row can take.
Rung 2 and 4: a log as the write buffer. Click servers validate each click, assign a unique click ID, redirect the user, and append the click to a Kafka topic. Peak throughput is 600,000 × 300 bytes = 180 MB/s, or 540 MB/s of disk writes with replication factor 3, which fits on a cluster of roughly 6 to 10 brokers with headroom. With 256 partitions, each carries under 1 MB/s at peak, and consumers can scale to 256 parallel instances. Producers batch with a linger.ms of a few milliseconds and compress, cutting network and disk use further. Kafka's retention of several days means a downstream outage delays results but loses nothing.
Rung 3 and 6: the partition key and the hot ad. Partitioning by ad_id keeps each ad's clicks together for aggregation, but the 50,000-per-second ad would saturate one partition's consumer. Ads detected as hot, or flagged in advance for major events, are salted: their key becomes ad_id#n with n from 0 to 15 derived from the click ID, spreading them over 16 partitions. This is split-hot-keys-dynamically, with a small table of salted ads consulted by the click servers.
Rung 5: aggregate before storing. A stream processor such as Flink reads the topic. It first deduplicates by click ID, keeping IDs seen in the last hour in keyed state, so retried client requests are not double-counted. It then counts clicks per ad in one-minute tumbling windows. For salted ads, a second stage merges the 16 partial counts into one. The output is at most one row per active ad per minute: with 1 million active ads, about 17,000 rows per second, written in large batches to an analytical store such as ClickHouse, Druid or Pinot. That is a reduction from 600,000 writes per second to a few dozen bulk inserts per second.
Raw data for billing truth. A connector writes the raw click stream to object storage as compressed columnar files every few minutes. An hourly batch job recounts clicks per ad from the raw files, with the same deduplication. If its result differs from the streaming result, the batch result is authoritative for billing. This is the usual pairing of a fast, approximate-in-failure path with a slow, exact one.
Rung 7: shedding what is safe to shed. The same click servers also emit impression and hover events for analytics. Under pressure, those are sampled at 1 in 10 with the rate recorded, while clicks are never sampled. If Kafka itself is unreachable, click servers spill clicks to local disk and replay them later, rather than dropping them.
Result. The database-facing write rate falls from 1.2 million row operations per second to a few dozen batched inserts per second, plus the raw archive. Bursts are absorbed by Kafka's retained log. The hot ad is spread across 16 partitions. Counts appear within about a minute of the window closing. Correctness for billing rests on unique click IDs, deduplication in both the streaming and batch paths, and the batch recount. See Design an Ad Click Aggregator for the full case study.
When to Use It#
- Sustained write rates exceed what one well-tuned database can take, typically beyond somewhere around 10,000 to 50,000 write transactions per second, or the write volume in bytes saturates one machine's storage.
- Writes are bursty: sales, live events, push notifications, end-of-day batches.
- A single key receives far more writes than the rest: counters, popular posts, celebrity accounts, flash-sale items, merchant accounts.
- The data is append-heavy: events, logs, metrics, messages, locations, clicks, IoT telemetry.
- Some writes are worth more than others, so a flood of low-value writes threatens the important ones.
- In interviews: high-volume ingestion problems such as metrics monitoring, ad click aggregation, location tracking, rate limiters, top-K, notifications, chat message storage, job schedulers and flash sales.
When NOT to Use It#
- Do not shard before you must. A single PostgreSQL or MySQL server with good hardware and tuning handles thousands to tens of thousands of writes per second. Sharding costs cross-shard queries, transactions and resharding work forever.
- Do not put a queue in front of writes the user must see confirmed, such as a payment or a booking, unless the product is designed around "pending" states. Otherwise you swap a slow response for a confusing one.
- Do not use write-behind or coalescing for data where every event or every unit matters: money, bids, inventory, audit records.
- Do not split hot keys preemptively everywhere if reads must then merge many sub-keys on every request. Split the few that need it.
- Do not reach for an LSM store for a read-heavy, update-in-place workload with complex transactions; you will trade a write problem you do not have for read and compaction problems you do.
- Do not shed load you have not classified. Dropping writes at random during overload loses important data along with unimportant data.
How to Implement It#
- List each write type with its rate, peak rate, size, durability need, ordering need and the cost of losing, delaying or duplicating it.
- Tune the single node first: storage, group commit, batched statements, unused indexes, schema shaped for appends, relaxed durability only for low-value data.
- Choose the store per write type: relational for transactional data, LSM key-value or wide-column for high-volume keyed writes, a log for event streams, a time-series or columnar store for telemetry.
- Pick the partition key for each high-volume store: high cardinality, even load, locality for the main transactions and reads, never monotonic. Use logical shards from the start.
- Buffer bursts with a durable queue or log in front of the storage, sized for the largest expected burst, with consumer lag and oldest-message age monitored.
- Reduce writes: batch everywhere, coalesce counters and last-value data in a write-behind buffer, aggregate hierarchically, archive raw events cheaply.
- Handle hot keys: sharded counters for commutative updates, salting for hot partition keys, heavy-hitter detection for dynamic splitting.
- Define load-shedding classes and switches before you need them, with separate capacity for critical writes.
- Rehearse: load-test peak bursts, a hot key at 100 times normal, a consumer outage that builds a backlog, and a resharding operation.
The buffer below coalesces like counts in memory and flushes them every 500 ms, or every 5,000 distinct keys, as one multi-row upsert into a sharded counter table.
const pending = new Map<string, number>(); // post_id -> likes since last flush
let flushing = false;
export function recordLike(postId: string, delta = 1): void {
pending.set(postId, (pending.get(postId) ?? 0) + delta);
if (pending.size >= 5000) void flush(); // size trigger
}
setInterval(() => void flush(), 500); // time trigger bounds the loss window
async function flush(): Promise<void> {
if (flushing || pending.size === 0) return;
flushing = true;
const batch = [...pending.entries()];
pending.clear();
const sub = Math.floor(Math.random() * 64); // spread hot posts over 64 sub-rows
try {
await db.query(
`INSERT INTO like_counts (post_id, sub, n)
SELECT unnest($1::text[]), $2, unnest($3::bigint[])
ON CONFLICT (post_id, sub) DO UPDATE SET n = like_counts.n + EXCLUDED.n`,
[batch.map(([id]) => id), sub, batch.map(([, n]) => n)],
);
} catch (err) {
for (const [id, n] of batch) pending.set(id, (pending.get(id) ?? 0) + n); // retry later
} finally {
flushing = false;
}
}The total for a post is SELECT sum(n) FROM like_counts WHERE post_id = $1, which reads at most 64 rows and is cached. A crash loses at most about half a second of likes from that server, which is acceptable for likes and not for payments. For exactly-once counting, each like would also be recorded as a row keyed by user and post, which is the source of truth, and the counter becomes a derived, rebuildable value.
| Technology | Fits when |
|---|---|
| PostgreSQL, MySQL with tuning | Transactional writes up to tens of thousands per second on one primary |
| Vitess, Citus | Sharding MySQL or PostgreSQL with routing and online resharding |
| CockroachDB, YugabyteDB, Spanner, TiDB | Distributed SQL with automatic range splitting and transactions across shards |
| Cassandra, ScyllaDB | Very high keyed write rates, multi-region, append-heavy data |
| DynamoDB, Bigtable | Managed horizontal write scaling with per-partition limits to design around |
| Kafka, Redpanda, Kinesis | Durable write buffer, event ingestion and replay |
| Amazon SQS | Simple durable queue to smooth bursts for job-style writes |
| Redis | Write-behind buffers, counters, last-value data with bounded loss |
| Flink, Kafka Streams, Spark Structured Streaming | Windowed aggregation and deduplication before storage |
| ClickHouse, Druid, Pinot | Batched ingestion of events with fast aggregate queries |
| TimescaleDB, InfluxDB, Prometheus | Time-series metrics and telemetry |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Tune and scale up one node | No distribution, full transactions | Hard ceiling, single failure domain | Up to tens of thousands of writes per second |
| Write-optimised LSM store | Fast sequential writes, horizontal scale | Compaction cost, weaker transactions, read amplification | Append-heavy, keyed, high-volume data |
| Horizontal sharding | Near-linear write scaling | Cross-shard transactions and queries, resharding | Sustained load beyond one node |
| Vertical partitioning | Isolates workloads, right store per data type | Cross-database joins and consistency | Mixed workloads of very different value |
| Queue buffering | Absorbs bursts, decouples producers | Asynchronous visibility, backlog delay | Peaks far above the average |
| Batching | Large throughput gains, simple | Added latency, bigger failure units | Many small writes |
| Write-behind with coalescing | Collapses repeated updates into one | Possible loss of buffered changes, loses history | Counters, last-value data, analytics |
| Hierarchical aggregation | Orders of magnitude fewer writes | Approximate under failures, late events | Counts, metrics, reactions |
| Sharded counters, salted keys | Spreads a single hot key | Reads must merge sub-keys | Hot commutative updates |
| Load shedding | Keeps critical writes alive in overload | Deliberately loses or rejects some work | Overload with writes of different value |
Common Pitfalls#
- Sharding by a monotonic key such as a timestamp or auto-increment ID, which sends every new write to one shard.
- Choosing a low-cardinality key, such as country or status, so a few shards take most of the load.
- Assuming more shards fix a hot key. One key is always on one shard; it needs splitting.
- Treating a queue as extra capacity. It only moves load in time. Under sustained overload, the backlog grows until something breaks.
- Using write-behind for money or inventory, and losing acknowledged writes in a crash.
- Forgetting idempotency in consumers, so redelivered messages double-count.
- Ignoring compaction when sizing an LSM cluster, then hitting write stalls at peak.
- Unbounded per-row update rates, such as updating a
last_seencolumn on every request, which turn reads into writes. Update at most once per minute, or keep the value in a cache. - Retry storms after load shedding because clients retry immediately without backoff.
- No resharding plan. Discovering at 90% disk that moving data takes weeks.
Real-World Examples#
- Discord stores trillions of messages in ScyllaDB, after migrating from Cassandra. Messages are partitioned by channel and time bucket to bound partition size and spread writes. A Rust data-services layer coalesces concurrent requests for hot channels.
- Instagram described sharding PostgreSQL into thousands of logical shards, mapped to fewer physical servers, with 64-bit IDs that encode the time, the logical shard and a sequence. Writes spread across servers, and capacity grows by moving logical shards.
- Amazon DynamoDB, in its USENIX ATC 2022 paper, explains how it moved from fixed per-partition throughput to global admission control, adaptive capacity and splitting partitions for heat, and why a single item still has a throughput limit.
- Slack put Kafka in front of its Redis job queue so that bursts of enqueued jobs are absorbed by a durable, disk-backed log rather than exhausting Redis memory.
- YouTube created Vitess to shard MySQL horizontally, and it is now a CNCF project used by other large MySQL users for sharding and online resharding.
- LinkedIn created Kafka to ingest activity events and logs at very high volume. The company has reported processing trillions of messages a day across its clusters.
- Google App Engine's documentation on sharding counters popularised splitting a hot counter into many entities to work around per-entity write limits.
- Disney+ Hotstar has described aggregating billions of live emoji reactions in a streaming pipeline before fanning results out to viewers, an example of hierarchical aggregation under a huge write burst.
Case studies that use this pattern#
- Design an Ad Click Aggregator: log buffering, salted hot ads, windowed aggregation and batch reconciliation.
- Design Metrics Monitoring: high-volume telemetry into a time-series store, with downsampling.
- Design Top-K: streaming counts with heavy-hitter structures instead of a write per event.
- Design a Rate Limiter: a counter update on every request, kept in memory and sharded.
- Design a Distributed Job Scheduler: bursts of job creation buffered through queues and partitioned by time.
- Design Post Search: indexing a high-volume write stream asynchronously.
- Design a Notification System: bursts of millions of notifications queued and rate-controlled per channel.
- Design a Flash Sale: queue-based admission, load shedding and hot-SKU contention.
- Design a Dating App: very high swipe write volume, partitioned by user.
- Design a Ride-Hailing App: hundreds of thousands of location updates per second, overwrite-friendly and in memory.
- Design a Chat System: message storage partitioned by conversation and time.
In the Interview#
Deep Dive: Write amplification from the API to the diskShow
One logical write, many physical ones. A single 1 KB row inserted into a relational table with four secondary indexes and two replicas generates surprisingly many bytes of I/O:
- The WAL record for the row and for each index entry, perhaps 1.5 KB. After a checkpoint, the first change to each page logs a full 8 KB page image, which can multiply WAL volume several times over for random inserts.
- The heap page and four index pages, each eventually written in full, 8 KB each, at the next checkpoint. If many rows land on the same pages before the checkpoint, the cost is shared. If inserts are random across a large table, each page write may carry only one or two new rows.
- Two replicas receive the WAL and repeat all of the page writes.
- Backups and change-data-capture read the WAL again, and archives store it.
For random inserts into a large table, the bytes written to disks across the cluster can easily be 50 to 100 times the size of the row. For sequential inserts into a time-ordered table with few indexes, the amplification is much smaller, because each page fills with many rows before it is written. That is why append-friendly schemas and fewer indexes matter so much.
LSM amplification. In an LSM tree with leveled compaction and a size ratio of about 10 between levels, each byte is rewritten roughly once per level it passes through, times a factor related to the size ratio, giving total write amplification often quoted in the range of 10 to 30. Size-tiered compaction rewrites less, often under 10 times, but leaves several overlapping files per key range, so reads check more files and space use temporarily doubles during compaction. Engines such as RocksDB expose the choice, and newer research designs such as key-value separation, in WiscKey (Lanyue Lu and colleagues, FAST 2016), store large values in a separate log so compaction moves only keys and pointers.
The RUM conjecture. Manos Athanassoulis and colleagues argued in "Designing Access Methods: The RUM Conjecture" (EDBT 2016) that an access method can optimise at most two of three overheads: Read, Update and Memory or space. B-trees favour reads. LSM trees favour updates and accept read and space overhead. Hash indexes favour point reads and updates but not range scans. Every write-scaling decision about storage engines moves along this triangle, so choose the engine by which two your workload needs.
Replication factor and the write budget. With replication factor 3 and leveled compaction at 10 times amplification, 100 MB/s of logical writes becomes about 3 GB/s of device writes across the cluster. SSD endurance, measured in drive writes per day, then becomes a design constraint. Write-heavy clusters sometimes choose higher-endurance drives, larger memtables or tiered compaction to stay within it.
Deep Dive: The mathematics of skew and partition keysShow
Random hashing is not perfectly even. Hash n equally busy keys onto m shards. The average load per shard is n / m, but the busiest shard receives more. When n / m is large, the maximum is roughly n / m + √(2 (n / m) ln m). For 1 million keys on 100 shards, the average is 10,000 keys and the maximum about 10,000 + √(2 × 10,000 × 4.6), roughly 10,300, only 3% above the average. With many keys per shard, hashing balances well. With few keys per shard, the imbalance grows: 1,000 keys on 100 shards gives an average of 10 and a maximum often around 18. This is one reason to use many logical shards per machine: it averages out the variation.
Skew in key popularity is the real problem. Real write rates per key are not equal. If key popularity follows a Zipf distribution with exponent 1 over N keys, the hottest key receives a fraction 1 / H(N) of all traffic, where H(N) ≈ ln N + 0.577. For N = 10 million keys, that is about 1 / 16.7, or 6% of all writes to one key. No number of shards can spread that key, because it sits on one shard. If the system takes 500,000 writes per second, that key alone needs 30,000 per second, beyond what one row or partition typically handles. That is why sharded counters and salting exist. It also explains why skew grows with success: as total traffic grows, the hottest key's absolute rate grows with it, while its share stays the same.
How many ways to split a hot key. If one partition can absorb c writes per second and a key receives w, split it at least ⌈w / c⌉ ways, plus headroom: at 30,000 writes per second and 2,000 per partition, at least 15 ways, so 16 or 32. Readers then merge that many parts. If a key's heat changes over time, as with a trending post, dynamic splitting lets you split widely while it is hot and fold the parts back when it cools.
Why the power of two choices does not apply. For stateless requests, picking the less loaded of two random servers dramatically reduces maximum load, a classic result from the balls-into-bins literature. For keyed writes, the key decides the shard, so there is no choice to make. Salting reintroduces a choice: writes to a salted key may go to any of k sub-keys, so the writer can pick randomly, or even pick the least loaded of two. That is exactly what makes salted hot keys spread well.
Temporal skew. Monotonic keys are skew in time: all current writes target the newest range. Hash or bucket prefixes convert temporal skew into spatial spread. For time-series data, partitioning by (series, time bucket) keeps each series's recent data together while spreading series across shards, and bounds each partition's size, which matters for compaction and repair in Cassandra-style stores.
Deep Dive: Counting correctly through buffers, queues and aggregatorsShow
Each write-reduction technique introduces a point where data can be lost or counted twice. Billing-grade systems need a deliberate design for correctness through the pipeline.
Give every event an identity. Assign a unique ID at the source, such as a click ID or message ID, so that any stage can tell a duplicate from a new event. Without an ID, retries from clients or redeliveries from queues are indistinguishable from real repeats.
Deduplicate where duplicates arise. Client retries create duplicates before the queue. Consumer restarts create duplicates after it. A stream processor can deduplicate with keyed state holding IDs seen within a window, such as one hour, sized by the event rate. At 600,000 events per second and 16-byte IDs, one hour of IDs is about 35 GB, spread across the job's state backend. Probabilistic filters cut that further at a small false-positive rate, which drops a tiny fraction of genuine events and therefore must be acceptable for the use case.
Make outputs idempotent. When an aggregator writes "ad 42, minute 12:03, 1,250 clicks", it should overwrite that row, not add to it. A restarted job that recomputes the same window writes the same value, and nothing is double-counted. Additive upserts, like the counter snippet above, are simpler but are only safe if each delta is applied exactly once, which needs transactional coordination between the input offsets and the output.
Transactional processing. Kafka's transactions let a stream processor commit its output records and its input offsets atomically, so after a failure it resumes exactly where its committed output ends. Flink achieves end-to-end exactly-once results with distributed snapshots of its state, based on the Chandy-Lamport algorithm, combined with transactional or idempotent sinks. See Delivery Semantics.
Reconcile against the raw record. Even with all of this, bugs and edge cases happen. Keeping the raw events in cheap storage and recomputing totals in batch provides an independent check and a way to repair. When the batch and streaming results disagree, investigate, and let the batch result win for money. This architecture, a fast path plus a reprocessing path, is the practical form of the lambda and kappa debates in stream processing.
Bound what write-behind can lose. For counts where approximate is acceptable, write down the loss bound: "at most 500 ms of likes per server on a crash", and confirm with the product owner that it is acceptable. Monitor flush failures and buffer sizes, and alert when buffers grow, because a growing buffer means the loss window is growing too.
Key Takeaways#
- Writes are harder to scale than reads because each must change one authoritative copy durably, and replicas and caches add work rather than spreading it.
- Size each write type separately, by rate, peak, size and the cost of loss or duplication. Most systems need different paths for transactional writes and high-volume telemetry.
- Optimise one node first: fast storage, group commit, batching, fewer indexes and append-friendly schemas. Relax durability only for low-value data.
- Write-optimised stores, such as LSM engines, logs and time-series databases, turn random writes into sequential ones, paying later in compaction.
- Shard by a key with high cardinality, even load and good locality, never a monotonic one. Use logical shards so that resharding moves data rather than rehashing it, and reshard with a snapshot, change stream, verification and short cutover.
- Queues absorb bursts but not sustained overload. Calculate the backlog and the delay it causes.
- The best write is one you avoid: batch, coalesce in write-behind buffers where loss is bounded and acceptable, and aggregate hierarchically.
- One key always lives on one shard. Split hot keys with sharded counters or salting, either for all keys or dynamically for detected hot keys, and merge the parts on read.
- Under overload, shed load by value, protect critical writes with separate capacity, and make clients back off.