Data · L2Scaling writes and hot keys

Scaling writes and hot keys

Reads can be copied, but every write must land on the one place that owns its key. Learn to spread writes, split hot keys and smooth bursts, and know what each fix costs.

L2 SeniorData19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 13 Nov 2026 · How we check content
Section 1 of 8

What broke

Amazon DynamoDB lets you buy write throughput for a table. In its early years, DynamoDB split that throughput evenly over the table's partitions. 1

The paper's example: one partition can take at most 1,000 write units. A table bought with 3,200 got four partitions of 800 each. 1 This works only if your app writes to all keys evenly.

Real apps do not. Amazon found that workloads "frequently have non-uniform access patterns", over time and over keys. 1 A few busy items sat on one partition. That partition hit its 800, and DynamoDB rejected the extra writes. This is called throttling. It happened even when the whole table had enough capacity. 1

To customers, it looked like downtime, "even though the service was behaving as expected". Customers worked around it by buying more capacity than they used, just to give the hot partition enough. 1

Amazon added fixes over time. Partitions could borrow unused capacity for short bursts. Adaptive capacity raised the limit on hot partitions and removed over 99.99% of the throttling caused by skew. Later, busy partitions were split automatically. 1

But one case was left. A partition "receiving high traffic to a single item" does not gain from a split. 1 Today each partition still takes at most 1,000 write units a second. 2 The database can spread many keys. Only you can spread one key.

Section 2 of 8

The idea in simple words

Reads are easy to copy. You can add replicas and caches, and each copy serves its own share of reads.

Writes cannot be copied away. Each write must reach the one place that owns its key. Every replica must then apply that write too. So adding replicas does not add write capacity.

When writes are the bottleneck, you have five moves:

  1. A bigger machine. Simple, and it buys time.
  2. Spread keys over shards, so each machine owns part of the writes.
  3. Split a hot key into many sub-keys.
  4. Write less often, by combining many small writes into one.
  5. Smooth bursts with a queue, so the database sees a steady rate.

The key idea. One key lives in one place, so its write rate is capped by that place. To go faster, you must change the key, or send fewer writes to it. Every fix moves cost somewhere else: to reads, to freshness, or to correctness.

Section 3 of 8

How it works

First, check that writes are the problem

Look at the primary database, not the replicas. Signs of a write bottleneck are a busy disk, a long write queue, and transactions waiting on row locks. Replicas that lag behind are another sign, because each replica must apply every write.

Then try the cheap fix: a bigger machine with faster disks. It needs no code change. Do this before you shard, as in Sharding and From zero to millions.

Shard by a key that spreads writes

If one machine is not enough, shard. For writes, the shard key must have many values, and new writes must spread over all of them. A user ID or tenant ID usually works.

A date is a bad write key. All of today's writes go to the shard that owns today. The DynamoDB docs use exactly this example of a hot key. 3

Split a hot key: write sharding

Some keys are hot by nature: a celebrity's post, a flash-sale product, a global counter. No shard key fixes them. So you split the key itself. Step through it. Use Next and Back, or the ← and → keys.

Split one hot counter key into sub-keys, then add them up on readLikes on one post: 3,000 writes/s P1 P2 P3 P4 each partition: at most 1,000 writes/s post423,000/s2,000 writes/s throttledP1, P3 and P4 sit idle Split into 4 sub-keyspost42#0post42#1post42#2post42#3each like picks one at random: ≈750/s each✓ writes spread over 4 partitions Read: get all 4, then add762 + 741 + 749 + 748 = 3,0004 reads instead of 1 job adds them every 5 s → one total rowpages read 1 row, but it can be 5 s old SeniorPath
  1. A viral post gets 3,000 likes a second. Its counter is one key, so it lives on one partition. That partition takes at most 1,000 writes a second. The rest are throttled, while the other partitions do nothing.
  2. Split the key into 4 sub-keys: post42#0 to post42#3. Each like adds 1 to a random sub-key. The hash spreads the sub-keys over the partitions. Each sub-key takes about 750 writes a second, under the limit. Use more sub-keys for more headroom.
  3. The cost moves to reads. To show the count, you read every sub-key and add them up. Four sub-keys mean four reads, and 50 would mean 50.
  4. If reads are frequent, a small job adds the sub-keys every few seconds and stores one total. Pages read that one row. The price is a count that can be a few seconds old.
Step 1 of 4

The DynamoDB docs call this write sharding. Their example adds a random number from 1 to 200 to a date key, such as 2014-07-09.1 to 2014-07-09.200. Writes spread across partitions. To read the whole day, you query all 200 keys and merge the results. 3

If you need to find one item again, use a calculated suffix instead. Compute the suffix from something you know, such as a hash of the order ID. 3

For a counter, this is called a sharded counter. Firestore's docs describe a pattern you build yourself: each counter gets a set of shard documents. A write adds 1 to a random shard. A read sums all the shards. 4 Here it is in Python with Postgres:

import random

N = 40  # sub-keys per hot counter

def add_like(conn, post_id):
    # conn: a psycopg 3 connection with autocommit=True
    conn.execute(
        """INSERT INTO like_shards (post_id, shard, n)
           VALUES (%s, %s, 1)
           ON CONFLICT (post_id, shard)
           DO UPDATE SET n = like_shards.n + 1""",
        (post_id, random.randrange(N)))

def like_count(conn, post_id):
    return conn.execute(
        "SELECT COALESCE(SUM(n), 0) FROM like_shards WHERE post_id = %s",
        (post_id,)).fetchone()[0]

The table has the primary key (post_id, shard). In one Postgres, the 40 rows let 40 writers hold row locks at once, not one. In a sharded store, if the shard key includes the sub-key, the rows also land on different machines. The read sums whatever rows exist, so you can raise N later without moving data.

Choose N from numbers. Firestore says write throughput grows linearly with the number of shards. So does the cost of each read. 4 For 20,000 writes a second and a limit of 1,000 per key, you need at least 20. Add headroom, and stop there. Only split the keys you have measured as hot.

For busy pages, add a roll-up. A job sums the shards every few seconds and stores one total. Firestore suggests this too, at the price of a total that lags. 4 The deep dives lesson walks through this choice for a like counter.

Write less often: combine, then flush

You can also stop sending every write to the hot row. This part is our advice. Each app server keeps a running total per key in memory. Once a second, it writes the total as one UPDATE ... SET n = n + 37. With 50 servers, the row gets at most 50 writes a second, whatever the traffic. The risk: a crash loses the totals not yet written. And a retried flush can add the same total twice. So use it only for counts where a small loss is fine, such as views.

A safer form keeps every event in a queue and applies them in batches. Modern Treasury had a "hot account" in its ledger: a ledger account that was "present on most Transactions". Contention on its single balance cache row made write latency spike. 5 Its fix lets a client mark an entry as safe to process later. Those entries go to an AWS SQS queue. A scheduled job takes them from the queue in batches. The target is 60 seconds; in practice, the p90 is 1 second. 5

Modern Treasury still keeps every entry, because all money movement must be recorded immutably. The balance still lives in one cached row. The batch job simply writes to that row far less often than once per entry. Wait too little between batches, and contention comes back. 5 Money and ledgers shows why ledgers work this way.

Smooth bursts with a queue

A database has a steady rate it can handle. Traffic arrives in spikes. Put a log or queue in front, and let consumers write at the rate the database can take. During a spike, you get lag, not errors. Queues vs logs covers delivery, and backpressure covers what to do when the queue fills.

A consumer can also write in batches, such as 500 rows per statement. That shares the fixed cost of each round trip and each disk flush. See batching and group commit.

Each write costs more than one write

Every index on a table is extra work for every write. In DynamoDB, a write that changes an attribute the index stores also uses the index's write units. Changing an indexed key costs two index writes: a delete and a put. If an index lacks capacity, writes to the table itself are throttled. 6

Postgres had its own form of this in 2016. Uber wrote that every index pointed to the row's location on disk. When that location changed, all indexes had to be updated. The write-ahead log grew too, so replication carried more data. 7 Storage engines add more: an LSM-tree rewrites data during compaction. See B-trees vs LSM-trees. Before you scale writes, remove the indexes nobody uses.

Section 4 of 8

Trade-offs

OptionWrite gainCost on readsOther costs
Bigger machineSome. One step, then a ceiling.None.Price. Still one machine.
Shard by a spread-out keyYes Grows with shards.Queries without the key hit every shard.Cross-shard transactions get hard.
Split a hot key into N sub-keysYes About N times for that key.N reads, or a roll-up that lags.A rule like "stock ≥ 0" no longer lives in one row.
Combine in memory, then flushYes One write per server per interval.Count lags by the interval.A crash loses the pending totals.
Queue events, apply in batchesYes The shared total row is written once per batch.Total lags by the batch interval.A queue and a batch job to run and watch.
Queue in front of the databaseSmooths peaks only.Reads lag behind the queue.The queue needs a limit and an alert.

Simple rule: go bigger first, then shard by a key that spreads writes. Split or combine only the few keys you have measured as hot.

Section 5 of 8

At work: how a senior uses this

  • Ask: "What is our peak write rate per key, not per table?" Averages hide the one hot key.
  • Find the limit of one key in your store, and divide. The answer tells you if a key needs splitting.
  • Log the top keys by write count on each partition. Alert when one key takes a big share.
  • Decide how stale each count may be, and get product to agree. It picks between sub-keys, a roll-up and in-memory totals.
  • Before splitting stock or balances, check the rules that need one row, such as "never below zero". See inventory and flash sales.
  • Count the indexes on write-heavy tables. Each one needs a reason.
  • Load test with real skew: one key with a large share of the writes, not keys spread evenly.
Section 6 of 8

With AI

What to ask the agent

"Here is our schema and a sample of write logs. Find the 10 keys with the most writes per second at peak, and say which ones exceed the per-key limit of our database."

"Convert this single-row counter to 40 sub-keys with a random suffix. Keep the read API the same, and add a job that stores the total every 5 seconds."

"List every index on these tables, how often each is used by queries, and how many extra writes each adds per insert."

What to check yourself

  • The sub-key is picked at random, or from a hash, never from a value that is the same for every write.
  • The read sums every sub-key that exists, not just 0 to N − 1 of today's N.
  • In-memory totals are only used where losing a few seconds of writes is acceptable.
  • The queue in front of the database has a limit and an alert on lag.
  • The load test sends a large share of writes to one key.
Section 7 of 8

Check yourself

1. A DynamoDB table has plenty of total write capacity, but writes to one item are throttled. Amazon's split for consumption is on. Why does the split not help?

Show answer

All writes go to one item, and one item cannot be split across partitions. The paper says a partition with high traffic to a single item will not benefit from a split. One key always lives on one partition.

2. A like counter gets 20,000 writes a second at peak. Each key takes at most 1,000 writes a second. How many sub-keys should you start with?

Show answer

At least 20, plus headroom, so about 40. 20,000 ÷ 1,000 = 20 is the bare minimum. Random choice is not perfectly even, so add headroom. Many more sub-keys only make reads cost more.

3. Each app server adds likes up in memory and writes the total once a second. What is the main new risk?

Show answer

A server crash loses the likes it counted but has not written yet. The pending total lives only in memory until the flush. A crash in between loses it.

4. You add three global secondary indexes to a write-heavy DynamoDB table. What can happen to writes on the table?

Show answer

Each write that changes an attribute the index stores also uses index write capacity, and an index without enough write capacity can throttle the table's writes. The DynamoDB docs say index updates consume the index's write units, and a table write is throttled if any affected index lacks capacity.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 7 sources and related lessons
  1. Mostafa Elhemali et al., “Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service”, USENIX ATC 2022 (opens in a new tab)
    Section 4 tells how hot partitions and throughput dilution caused throttling, and how bursting, adaptive capacity, global admission control and split for consumption fixed most of it.
  2. Amazon DynamoDB Developer Guide, “Best practices for designing and using partition keys effectively in DynamoDB” (opens in a new tab)
    The read and write limits of one partition, and what one write unit is.
  3. Amazon DynamoDB Developer Guide, “Using write sharding to distribute workloads evenly in your DynamoDB table” (opens in a new tab)
    Random and calculated suffixes on a partition key, and the extra queries that reads need.
  4. Firebase documentation, “Distributed counters” (Cloud Firestore) (opens in a new tab)
    A counter split into shards, how write throughput and read cost both grow with the number of shards, and the roll-up option.
  5. Matt McNierney, “Behind the Scenes: How We Built Ledgers for High Throughput”, Modern Treasury (2024) (opens in a new tab)
    A real hot account in a ledger, and how a queue plus batch processing took the pressure off one balance row.
  6. Amazon DynamoDB Developer Guide: Using Global Secondary Indexes in DynamoDB (opens in a new tab)
    Every table write that changes data an index stores also writes to the index, and an index without enough write capacity can throttle writes to the table.
  7. Evan Klitzke, “Why Uber Engineering Switched from Postgres to MySQL”, Uber Engineering (2016) (opens in a new tab)
    How, in the Postgres of 2016, a change to one row could mean an update to every index on the table, and more data to replicate.

Related: Sharding and consistent hashing · Queues vs logs and delivery guarantees · Batching and pipelining · Backpressure and flow control · B-tree vs LSM-tree · Distributed caches · Scaling reads · Deep dives and explaining trade-offs · Inventory, overselling and flash sales · Money and double-entry ledgers

Before this: Sharding and consistent hashing and Queues vs logs. For the read side of hot keys, see Distributed caches. Each store in depth: DynamoDB and Cassandra.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper