Fix Lost Updates in a Multithreaded Page Hit Counter
Last updated: November 29, 2026
Quick Overview
A service counts page hits in a shared dictionary updated from many threads, and totals come out lower than the request logs. Explain the race and implement a counter that is correct and scales under contention.
0
0
0 solved
A service counts page hits in a shared dictionary updated from many threads, and totals come out lower than the request logs. Explain the race and implement a counter that is correct and scales under contention.
Race conditions on shared counters are a staple fundamentals question at Google because the bug looks innocent. Interviewers check that you can explain why `counts[k] += 1` is not atomic, then pick a fix that balances correctness and contention.
What the Interviewer Expects
- Explains read-modify-write as the source of lost updates
- Shows why a single global lock is correct but contended
- Implements lock striping by key hash
- Provides a consistent snapshot without deadlock
- Mentions alternatives like per-thread counters or atomics
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you avoid locks entirely with per-thread shards?
- How do you choose the number of stripes?
- How would you report counts to a monitoring system every 10 seconds?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
incr(key)from many threads must never lose an update.get(key)returns the current count;snapshot()returns a consistent view of all keys.- High throughput when many threads hit different...
High-Level Design
The bug: counts[k] += 1 is load, add, store. Two threads can both load 41 and both store 42, losing one hit. Even with the GIL in CPython, a thread switch can occur between those bytecodes. One glob...