"Design a distributed counter" sounds like a warm-up: keep a number, add one. On a single machine it is count++. The question gets hard at the scale where a single viral post receives more increments per second than any one database row can absorb.
That is the whole problem, and it is a nice one because the fixes are old, cheap ideas that people forget under pressure. What do you do when every writer wants the same row? How accurate must the number be, and what does accuracy cost? And when a client retries a "like" because the network blinked, how do you avoid counting it twice?
The data partitioning lesson explains hot spots in general. This page applies them to the sharpest case: one key, enormous write volume.
Clarify the requirements
We design counters for a content platform: view counts and like counts on posts.
Functional requirements:
- Increment a post's view count when someone views it.
- A user can like and unlike a post. A user's like counts once.
- Read the current counts for a post, and for a page of posts at once.
- Show an approximate number of unique viewers for popular posts.
Out of scope, said aloud: ranking posts by counts (see top-K trending), counts over arbitrary time windows, fraud scoring of fake views.
Non-functional requirements:
- Very high write throughput, including one post receiving a large share of all traffic.
- Fast reads: a count appears on every post in a feed, so reads must be cache-fast.
- Eventually accurate: a view count may lag by a few seconds. A like count must never double count a user.
- No lost increments: a crash must not erase views already acknowledged.
- Available: counting must not block the page from loading.
Estimate the scale
Assume 100 million daily active users, each triggering 100 counted events a day (views and likes), and 1 billion posts with counters.
Increment rate: 100M × 100 = 10 billion a day ÷ 86,400 s ≈ 116,000 per second on average, about 350,000 per second at peak.
Read rate: every view also reads a count, so reads are about the same, 116,000 per second on average, mostly served from cache.
Counter storage: 1 billion counters × 16 bytes (an 8-byte id and an 8-byte count) = 16 GB. The totals are tiny.
The hot key: suppose one viral post receives 6% of peak traffic: 0.06 × 350,000 = 21,000 increments per second on one key. A relational row updated by a transaction (read, lock, write, commit) handles on the order of 1,000 updates per second, because each update waits for the previous one's lock. That is a 20× gap.
Unique viewers: a HyperLogLog sketch is up to 12 KB per item. For all 1 billion posts that is 12 TB, but only the top 1% (10 million posts) need one: 10M × 12 KB = 120 GB.
"The totals are tiny and the average rate is modest. The entire difficulty is the hot key: 21,000 writes per second to one number is twenty times what one row can take. And the number of distinct posts being updated in any second is far smaller than the number of increments, which means batching increments by key makes the durable store's load a fraction of the incoming events."
The capacity estimator reproduces the 116,000 per second. Ignore its storage line: counters are overwritten in place, not appended.
API and data model
POST /v1/posts/{postId}/views (fire and forget) -> 202
PUT /v1/posts/{postId}/likes/{userId} -> { liked: true } (idempotent)
DELETE /v1/posts/{postId}/likes/{userId} -> { liked: false }
GET /v1/posts/counts?ids=1,2,3 -> { 1: {views, likes}, ... }likes (post_id, user_id) PK together -- the source of truth for who liked
totals (post_id) -> { views, likes } -- the derived counts
hot Redis: count:{post_id} (fast display counter)
stream increment events keyed by post_idLikes are stored as pairs, not as a count. The count is derived from the pairs, so an unlike is the removal of a pair and a retried like is a no-op on a primary key that already exists. Views are different: nobody needs to know who the viewer was, only how many, so they are pure counts.
High-level design
The slice to simulate is the increment path: the API writes to a fast hot counter and a stream, and an aggregator folds the stream into durable totals.
- The counter API increments an in-memory counter in Redis for fast display and publishes an event to a stream.
- The stream is partitioned by post, so one aggregator handles each post's events.
- Rollup workers batch events and write durable totals to DynamoDB.
Describe this diagram
Components
- clients (Client)
- counter api (Service)
- hot counters (Redis)
- increment stream (Kafka)
- rollup workers (Service)
- durable totals (DynamoDB)
Connections
- clients sends to counter api
- counter api sends to hot counters
- counter api sends to increment stream
- increment stream sends to rollup workers
- rollup workers sends to durable totals
Run it, then try raising the load or reducing the stream's partitions, and watch which stage saturates first. The durable store sees far fewer writes than the front end.
The write path: the API increments the Redis counter (so the displayed count is nearly instant) and appends an event to the stream, then answers 202. It does not wait for the durable write.
The read path: reads come from Redis. If a counter is missing (evicted or after a restart), the API loads the durable total from DynamoDB, adds any events not yet rolled up, and refills Redis.
The interesting problem: a million writers, one key
Approach A: increment one row
UPDATE counters SET views = views + 1 WHERE post_id = ?, or an atomic ADD in a key-value store.
Good: correct and trivial, and fine for the vast majority of posts, which get a handful of increments a minute.
Bad: the viral post wants 21,000 updates a second on one row, and every update waits its turn. Latency climbs, requests time out and retries add load. The row (and in a partitioned store, the whole partition holding it) becomes the bottleneck.
Approach B: sharded counters
Split one logical counter into N sub-counters, views#0 to views#19. Each increment goes to a random sub-counter. A read sums all N.
Good: writes spread across N rows, partitions or nodes. With N = 20, the hot post's 21,000 per second becomes about 1,050 per row, within a row's limit. It is exact, simple and well-understood.
Bad: every read costs N lookups (cache the sum), and N must be chosen: too few and the hot key still burns, too many and every cold post pays for 20 rows it does not need.
Approach C: buffer and aggregate
Do not write each event to the database. Append increments to a stream partitioned by post id. A rollup worker keeps an in-memory map of post_id -> pending count, and every second flushes the totals: one write adding 21,000 instead of 21,000 writes adding 1.
Good: the durable store's write rate becomes the number of distinct posts touched per second, not the number of events. A viral post costs the same one write per second as a quiet one. Because one worker owns each post through the stream partition, nothing contends. It also absorbs bursts: the stream buffers them.
Bad: counts lag by the flush interval, a crashed worker must replay from the stream (so the increment must be idempotent against replays), and the system has more moving parts.
The recommended answer is C for views, with Redis for instant display, and B as the cheaper fallback when a stream feels like too much. For a mid-sized system, sharded counters on the hot keys only (see the practice below) get you most of the benefit. Say that you would start with A, measure, and move to C when one key's rate approaches what a row can take.
The second decision: how exact must the count be
"Count" hides three different accuracy needs, and a good answer separates them.
Views: approximate is fine. Nobody can tell 1,203,457 from 1,203,490. A few seconds of lag and a rare lost increment on a crash are acceptable. Use the fast path: Redis plus batching. If the stream replays after a crash, an event may be applied twice. Make the rollup idempotent by recording the last stream offset applied together with the total (in the same write), so a replay skips events already counted.
Likes: exact, with identity. The count must reflect who liked. Write a row (post_id, user_id) with a conditional insert (attribute_not_exists in DynamoDB, ON CONFLICT DO NOTHING in SQL). A retry hits the primary key and changes nothing. Increment the derived total only when the insert actually created a row. Periodically reconcile the total against a count of the rows to repair drift.
Unique viewers: probabilistic. Exact unique counts need to remember every viewer, which is a set as large as the audience. A HyperLogLog sketch estimates the number of distinct items in at most 12 KB with a standard error around 0.8%, regardless of the audience size, and two sketches can be merged. Use it only for popular posts (the 120 GB number), and display "1.2M viewers" without pretending to precision.
Money is different. If a counter drives billing (API calls, ad impressions), do not use the lossy fast path alone. Write each event to a durable log first, count from the log and reconcile, as in the ad click aggregator problem.
Bottlenecks and failures
A hot key appears suddenly. A post can go from 100 to 20,000 increments a second in a minute. With approach C, the stream partition for that post is busy but only one writer is involved. To spread the Redis counter too, shard it dynamically: detect keys above a threshold rate and switch them to N sub-keys, then sum them on read.
Redis loses a counter. An eviction or a failover can lose the display value. The durable total plus unrolled events rebuild it. Display counts that dip briefly are less bad than counts that block pages.
A rollup worker crashes. Its stream partition is picked up by another worker, which replays from the last committed offset. Idempotent application (the offset stored with the total) makes replay safe.
Stream lag. If aggregators fall behind, displayed counts lag. Alert on consumer lag in seconds, and scale workers up to the partition count.
Abuse. Bots inflate views, and a script can like a post a million times. Rate limit per user and per IP, require authentication for likes, and process views through a fraud filter before they reach the durable total.
What if the stream is down? Fall back to incrementing Redis only and queueing events locally for a short time, accepting undercounting, rather than failing the page. A counter is never worth breaking the thing it counts.
Trade-offs to name aloud
- Batching over per-event writes: counts lag by a second or two, in exchange for a durable store whose load follows distinct keys, not events.
- Sharded counters: exact and simple, in exchange for N reads per lookup.
- Approximate unique counts: 12 KB per item and under 1% error, in exchange for not knowing who the viewers were.
- Separating views from likes: two code paths, in exchange for using the cheap method where precision does not matter.
- Eventually consistent display: a count that is a few seconds behind, in exchange for pages that never wait on a write.
What interviewers listen for
- A working answer: an increment API, a counter per post in a database and a cache for reads.
- A strong answer: identifies the hot key with a number, proposes sharded or batched counters, and separates exact like counts from approximate view counts.
- A standout answer: also makes the rollup idempotent with offsets, uses conditional inserts for likes, reaches for HyperLogLog for unique viewers and explains the billing exception.
Check your understanding
Common mistakes
One row, no number. "Just use an atomic increment" is correct for most posts. It is incomplete until you say what happens at 21,000 per second.
Reading a count by summing events. A count that grows with data size gets slower every day. Maintain totals and update them incrementally.
Treating all counts alike. Views, likes and billing events need different guarantees. Using exact, durable machinery for views is waste, and using the lossy fast path for money is a bug.
Counting a retry twice. Without an identity per event, at-least-once delivery inflates counts. Name the idempotency key or the offset.
Ignoring the read side. Writes get all the attention, but a feed page reads 20 counts at once. Batch reads and cache them.
Forgetting that counters can be wrong. Caches evict, streams replay, workers crash. Say how drift is detected and repaired.
Practice
You do not want a stream yet. A post suddenly goes viral and one counter row is timing out. What is the smallest change that stops the incident, and what do you build after?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Handle only the keys that are hot, and avoid making every read slower.
Show a strong answer
Stop the incident with sharded counters on that key. Rewrite the hot post's counter as 20 sub-counters (post:77:views#0 to #19). Each increment picks one at random. The 21,000 writes per second become about 1,050 per row.
Mark it, do not shard everything. Store a flag on the post's record, for example shards = 20. Writers read the flag (cached) and only flagged posts pay the N-read cost on every read. The other 999,999,999 counters stay single-row.
Keep reads cheap. Cache the summed total for one to five seconds in Redis, so the sum of 20 is computed rarely.
Then automate it. Build hot-key detection from the stream of increments or from the database's throttling metrics, so a key crossing a rate threshold is sharded automatically, and shrunk again when traffic falls.
The pattern worth keeping: apply the expensive fix to the few keys that need it, and keep the common path simple.
API usage counters drive customer invoices, so they must be exact. How is that design different from the views counter?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Where is the source of truth, and what can you replay?
Show a strong answer
Make the durable log the source of truth. Every usage event is appended to a durable, replicated log with a unique event id before anything else happens. The counter is a derived view, and the log is the record.
Aggregate from the log, idempotently. Aggregators read the log in order and apply each event once, keyed by event id or by offset stored with the total. A crash and replay produces the same totals.
Deduplicate at the edge. Clients retry, so the event id (supplied by the caller or assigned at the gateway) lets the pipeline drop a duplicate event even across a crash.
Reconcile. Each night recompute the totals from the raw log and compare them with the live counters. A difference is a bug to investigate, not noise to tolerate.
Accept higher cost and latency. This path writes every event durably and is slower. Do not use it for page views.
The pattern worth keeping: when a number must be exact, make the log the truth and every counter a recomputable view.
Key takeaways
- The problem is the hot key: one key at 21,000 writes per second is twenty times a row's limit.
- Shard the counter or batch the increments, and shard only the keys that are hot.
- Batching makes the store's load follow distinct keys, not events.
- Likes need identity (a post and user pair); views and unique counts can be approximate.
- Make rollups idempotent with offsets, so replays do not double count.
- A counter must never break the page it counts: degrade to approximate rather than fail.
Further reading
- G. DeCandia et al., "Dynamo: Amazon's Highly Available Key-Value Store", SOSP (2007): background on partitioned stores where hot keys matter.
- P. Flajolet, E. Fusy, O. Gandouet and F. Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm", AofA (2007).
- Amazon Web Services, Amazon DynamoDB Developer Guide, "Best practices for designing and using partition keys effectively": hot partitions and write sharding.