Build a Fault-Tolerant Distributed Counter at Scale
System DesignModel answerLast updated
Design a horizontally scalable counter service that guarantees atomic updates, read-after-write consistency, and correct behavior under retries and failures.
The Problem
You are building a general-purpose counter service that many clients write to simultaneously. Think of it as the engine behind inventory tracking, rate limiting, viral like counts, or global quota enforcement — anywhere an exact integer must stay correct under high concurrency.
What to design
Describe a complete system. Cover each of the following:
APIs Define the write and read endpoints. What parameters does a caller send? What does the response include? How does the API surface support safe retries?
Data model How are counters stored, partitioned, and identified? What metadata does each entry carry?
Concurrency control Walk through at least two strategies (for example, optimistic compare-and-swap, distributed locking, and single-writer-per-key via consensus). Explain why you choose one over the others.
Idempotency and delivery semantics Retries are inevitable. How do you ensure a timed-out request never double-counts? Where exactly does the deduplication check happen, and why does that location matter?
Leader election and failover Who decides which node handles writes to a given counter? What happens during a leader change, and how quickly do clients recover?
Partition tolerance If part of the cluster becomes unreachable, what can and cannot proceed? Name the CAP trade-off you are making and justify it.
Clock skew Where do clocks appear in the design? How do you prevent drift from causing ordering bugs or incorrect expiry?
Hotspot mitigation A single counter receives 200k writes per second — far beyond one node. How do you scale it without losing correctness?
Monitoring and rollback What signals tell you a counter node is struggling? How do you roll back a bad deployment without losing acknowledged writes?
Constraints and assumptions to state out loud
Before answering, agree on scale. A reasonable baseline:
| Dimension | Starting assumption |
|---|---|
| Total counters | 100 million |
| Aggregate writes | 1 million/s |
| Aggregate reads | 5 million/s |
| Hottest single key | up to 200k writes/s |
| Write latency SLO | p99 < 20 ms within a region |
| Read latency SLO | p99 < 10 ms within a region |
| Availability target | 99.99% |
| Durability | No acknowledged increment is ever lost |
Challenge these numbers if they seem wrong for the use case you are solving. Interviewers expect you to drive the scoping conversation.
What a strong answer looks like
- Commits to a concrete architecture early, then defends it against failure scenarios.
- Clearly names trade-offs rather than presenting every option as equally good.
- Gives rough numbers (batch size, replication factor, dedup TTL, failover window) to show the design is grounded in reality.
- Handles the "hottest key" scenario without hand-waving.
Hints
Hint 1
Start by nailing down consistency requirements before touching architecture. Read-after-write for a single key is a very different contract from cross-key transactions — scope this explicitly so you don't over-engineer.
Hint 2
Compare optimistic CAS, distributed locks, and single-writer-per-shard for concurrency control. Think about what happens to each approach when 200k writes/s hit the same key — retry storm behavior is the deciding factor.
Hint 3
Idempotency is only airtight if the dedup check and the counter update happen atomically in the same replicated operation. If they are separate steps, a failover between them silently breaks your exactly-once guarantee.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem looks simple — it's just x += 1 — but that simplicity is the trap. The real challenge is keeping the increment correct across machines, retries, and partial failures, while one key might absorb 200k writes per second. The right move is to commit to a specific architecture and defend it under failure scenarios rather than describing every option without landing anywhere.
1. Clarify Scale First
Before drawing anything, state your assumptions out loud:
- 100M counters, ~10 GB at 100 bytes each — storage is trivial.
- 1M writes/s and 5M reads/s in aggregate — routing and replication throughput matters.
- Hottest key: up to 200k writes/s. This is the hard constraint that shapes everything.
- p99 write < 20 ms, p99 read < 10 ms within a region.
- Durability: once a write is acknowledged, it cannot be lost.
- Consistency: read-after-write and linearizable writes per key. Multi-key transactions are out of scope.
The idempotency table deserves a storage estimate too. At 1M writes/s with a 10-minute dedup window, that's ~600M entries at ~50 bytes each — about 30 GB clustered. Storage is fine; the hard problems are contention and correctness.
2. API Design
POST /counters/{key}/update
body: { delta: int64, request_id: uuid, client_id: string,
condition?: { min_value?: int64, expected_version?: int64 } }
→ { value: int64, version: int64 }
GET /counters/{key}?min_version=V
→ { value: int64, version: int64 }
request_id is mandatory. Without it, a timed-out write is ambiguous — did it apply or not? Clients must supply a stable ID and retry with the same ID until they get a response.
version is the Raft log index for that key's shard. The client passes it back on reads as min_version, letting any replica that has applied at least that index answer — this is how you deliver read-after-write without forcing every read to the leader.
The optional condition field supports quota counters ("decrement only if value stays ≥ 0") without building a separate compare-and-swap endpoint.
3. Data Model
Counter: { key, value: int64, version: int64 }
DedupEntry: { (client_id, request_id) → { result_value, result_version, expires_at } }
ShardMap: { key_range → raft_group_id, leader_node, epoch } // in etcd or ZooKeeper
Counters are hash-partitioned into ~1,000 ranges. Each range is owned by one Raft group of 3 replicas, spread across availability zones.
4. Architecture Overview
Stateless API gateway — authenticates callers, caches the shard map (versioned by epoch), and routes each request to the Raft leader for the owning range. On NOT_LEADER replies, it refreshes the shard map and retries. Retries are safe because writes are idempotent.
Raft group per range — the leader is the sole writer for its keys. It appends {key, delta, client_id, request_id} to the log, waits for a majority acknowledgment, applies the entry to its RocksDB state machine, and replies. Critically, the leader can batch: thousands of increments arriving within a millisecond become a single log entry. One Raft group can comfortably sustain 100k+ ops/s per key with this group commit.
Config / placement service — owns the shard map, rebalances leaders, and coordinates range splits.
5. Concurrency Control: Why Single-Writer Wins
Three common options:
- Optimistic CAS: simple on any KV store, but under contention the retry rate scales with concurrent writers. At 200k writes/s on one key it becomes a retry storm and throughput collapses.
- Distributed locks: add a network round trip and lease management to every write. Without fencing tokens, a paused lock holder can write after its lease expires, silently corrupting the counter.
- Per-key single writer via sharded consensus (chosen): all writes to a key are serialized by one Raft leader, so there are no conflicts and no retries. The batching behavior described above is a direct consequence of this design.
The trade-off is that leader election adds ~1–3 s of write unavailability per range on failover. That's acceptable given the durability and throughput guarantees it provides.
6. Idempotency — Where Exactly
Effectively-once semantics require that the dedup check and the counter update happen in the same replicated log entry and the same state-machine apply. If they are separate operations, a leader failover between them leaves a window where the update applied but the dedup record was not written, so the next retry double-counts.
The correct sequence:
- Leader receives write with
(client_id, request_id). - Appends a single log entry containing both the delta and the dedup record to the Raft log.
- On apply, checks dedup first. If found, returns the stored result. If not, applies the delta and writes the dedup entry atomically.
- Because this state is replicated, a retry that arrives after a leader failover is still caught.
Dedup entries expire after a TTL longer than the client's maximum retry window. Clients must generate a new request_id after that window — at that point, the original outcome is safe to assume final.
7. Partition Tolerance
This design is CP per key. A minority partition cannot commit writes or serve linearizable reads; it returns errors. Clients retry against the majority side once they receive a routing hint.
The explicit trade-off: a counter whose replicas are split by a network partition becomes unavailable for writes on the minority side. That's the price of never losing an acknowledged increment and never double-counting. For pure view counters where approximate values are acceptable, an eventual-consistency path (CRDT-based, no Raft) is a valid alternative — name that choice explicitly.
8. Clock Skew
Clocks are deliberately excluded from ordering decisions. All ordering comes from (raft_term, log_index).
Clocks appear in two places only:
- Leader leases for local reads: a leader can serve reads locally if its lease guarantees it is still the leader. This is only safe if clock drift is bounded — subtract a drift margin or use Raft ReadIndex (a heartbeat round to confirm leadership) instead.
- Dedup TTL expiry: use the leader's apply-timestamp from the log entry, so every replica expires entries at the same logical time regardless of wall-clock drift.
9. Hotspot Mitigation
When a single counter exceeds what one leader can handle even with batching, split it into N virtual sub-counters: key#0 … key#N-1.
- Writes are fanned out to a randomly chosen sub-counter; each sub-write is independently deduplicated.
- Reads sum all N sub-counters; read-after-write uses a version vector of N versions.
- Sub-counters can live on separate Raft groups, distributing both CPU and network load.
The cost is that reads become slightly heavier. For a viral counter at 200k writes/s, N = 4–8 is usually enough to drop per-shard load to a comfortable range.
10. Monitoring and Rollback
Key signals to watch:
- Raft commit latency — spikes mean replication is falling behind.
- Dedup hit rate — a sudden rise signals a client retry storm; a sudden drop could mean clients are skipping idempotency keys.
- Range leader distribution — imbalance shows hotspots the placement service hasn't rebalanced yet.
- Write rejection rate on minority partitions — expected during splits, alarming if sustained.
For rollback: because every mutation is a Raft log entry, you can replay the log to any prior version in a test environment. In production, counters are append-only — a "rollback" means writing a compensating delta and marking the bad deployment epoch in the dedup table so re-replayed writes from that window are idempotent. Avoid Raft log truncation as a rollback mechanism; it risks divergence across replicas.
Common Mistakes
- Using wall-clock timestamps for ordering — breaks under any meaningful drift.
- Putting the dedup check outside the replicated state machine — creates a window for double-counting on failover.
- Choosing CAS without quantifying the retry rate under the stated hotspot load.
- Forgetting to state the CAP trade-off; "both consistent and available" is not a real answer for a partitioned key.