Thread-Safe In-Memory Store and Sliding-Window Counter
Data Structure DesignModel answerLast updated
Find the concurrency bugs in an in-memory key-value store with expiry and a 300-second hit counter, then fix them with appropriate locking and describe how to test.
You have built two single-process, in-memory components and now need to make them safe for many threads.
Component 1: key-value store
put(key, value, ttl=None),get(key),delete(key).- Entries with a TTL expire lazily on read and may also be removed by a background sweeper.
Component 2: sliding-window hit counter
hit(ts)records one event at secondts.getHits(ts)returns the number of events in the last 300 seconds.- The implementation uses a circular array of 300 buckets, each holding a
(timestamp, count)pair.
Assume a workload such as 16 to 64 threads, a read-heavy store (about 90% reads), and a write-heavy counter (hits far outnumber queries).
What to cover in your answer
- List the concrete race conditions in each component. Describe specific thread interleavings, not just "there may be races."
- Propose fixes and compare them: a single global lock, lock striping, read/write locks, atomics/CAS, striped counters, and lock-free or copy-on-write designs. Discuss correctness and performance for each.
- Explain what consistency guarantee your
getHitsgives, and whether that is acceptable. - Describe how you would test and validate concurrent behavior.
Include code for the core of your fix.
Hints
Hint 1
For the store, look at every place where code does check-then-act or read-modify-write, especially the gap between noticing that an entry is expired and deleting it.
Hint 2
For the counter, a bucket's timestamp and count form one logical unit. Ask what happens if two threads at the same second both decide the bucket is stale, or if a reader sees half of an update.
Hint 3
Make the expiry delete conditional: only remove the entry if it is still the same version that was observed as expired. For testing, think about stress tests with invariant checks, many thread counts, and tools such as thread sanitizers.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. State your assumptions
Say up front what you are optimizing for: for example 16 to 64 threads, a read-heavy store, a write-heavy counter, one process. Also name the language model. In Java or C++ an unsynchronized hash map can corrupt itself during a resize. In Python the GIL makes a single dict operation atomic, but compound operations and x += 1 are not.
2. Race conditions
Key-value store
- Structural corruption. Two concurrent
puts trigger a resize in a non-thread-safe map, causing lost entries or an infinite loop. - Check-then-act.
if k not in store: store[k] = v. Both threads see "absent" and one write silently wins. The same applies toputIfAbsent. - Lost update.
store[k] = store[k] + 1on two threads yields +1 rather than +2. - Expiry vs. fresh write. Thread A reads
kand sees it expired. Thread B callsput(k, v2)with a new TTL. Thread A then runsdelete(k)and erases B's fresh value. A background sweeper has the same flaw. - Iteration during mutation. A scan or snapshot concurrent with writers throws or returns a torn view.
Hit counter
- Lost increment.
count[i] += 1is load, add, store, so concurrent hits overwrite each other. - Rotation race. Thread A sees
times[i] != tsand starts resetting. Thread B, at the samets, increments the old count. A then setscount = 1, wiping B's hit. Or both reset and one hit is lost. - Torn pair. A reader sees the new timestamp with the old count, or the reverse, and over- or under-counts.
- Read during rotation.
getHitssums buckets while writers rotate them, so the total is not a linearizable snapshot. - Deque variant. An append in
hitraces with expiry pops ingetHits.
3. Mechanisms and trade-offs
| Mechanism | Correctness | Performance | Use when |
|---|---|---|---|
| Global lock | Trivially correct, compound ops are easy | Serializes everything | Baseline, low contention |
Lock striping (hash(k) % N) | Correct per key; multi-key ops need ordered acquisition | Scales roughly with N | Default for the store |
| Read/write lock | Correct; beware writer starvation and upgrade deadlock | Only helps with long or very read-heavy reads | Scans, read-mostly data |
| Atomics / CAS | Correct for one word; ABA risk with pointers | Fast uncontended, retry storms under contention | Counters, version stamps |
| Striped counters (per-thread cells) | Sum is exact eventually, not a snapshot | Best write throughput | Write-heavy counters |
| Lock-free / copy-on-write | Hard; needs safe memory reclamation | Readers never block | Read-dominated, small data |
Two points worth making:
- Read/write locks are not free here. With lazy expiry, a
getcan need to delete, which turns a read into a write. Upgrading a lock is deadlock-prone. Instead, release the read lock, take the write lock, and re-validate before deleting. - Use compare-and-delete for expiry. Store a version (or the expiry time) with each value and remove the entry only if it is unchanged. This mirrors
ConcurrentHashMap.remove(key, expectedValue)and fixes the expiry-vs-write race for both lazy expiry and the sweeper.
4. Implementation sketch (Python)
import threading, time
class StripedKV:
def __init__(self, stripes=64):
self._n = stripes
self._locks = [threading.Lock() for _ in range(stripes)]
self._maps = [{} for _ in range(stripes)] # key -> (value, expires_at, version)
self._ver = 0
self._ver_lock = threading.Lock()
def _s(self, k):
return hash(k) % self._n
def _next_ver(self):
with self._ver_lock:
self._ver += 1
return self._ver
def put(self, k, v, ttl=None):
exp = time.monotonic() + ttl if ttl else float("inf")
ver = self._next_ver()
i = self._s(k)
with self._locks[i]:
self._maps[i][k] = (v, exp, ver)
def get(self, k):
i = self._s(k)
with self._locks[i]: # check and expire are atomic
e = self._maps[i].get(k)
if e is None:
return None
v, exp, _ = e
if exp <= time.monotonic():
del self._maps[i][k]
return None
return v
def expire_if_version(self, k, ver): # for the sweeper
i = self._s(k)
with self._locks[i]:
e = self._maps[i].get(k)
if e and e[2] == ver and e[1] <= time.monotonic():
del self._maps[i][k]
class HitCounter:
WINDOW = 300
def __init__(self):
self._times = [0] * self.WINDOW
self._counts = [0] * self.WINDOW
self._locks = [threading.Lock() for _ in range(self.WINDOW)]
def hit(self, ts):
i = ts % self.WINDOW
with self._locks[i]: # rotate and increment as one unit
if self._times[i] != ts:
self._times[i], self._counts[i] = ts, 0
self._counts[i] += 1
def get_hits(self, ts):
total = 0
for i in range(self.WINDOW):
with self._locks[i]:
if ts - self._times[i] < self.WINDOW:
total += self._counts[i]
return total
Why it is correct. Each bucket's (time, count) pair changes only under its own lock, removing the lost-increment, rotation and torn-pair races. get_hits is consistent per bucket but not a global snapshot, since hits may land in already-summed buckets. For monitoring this is fine, and you should say so explicitly. If an exact snapshot is required, take all bucket locks in index order or use a single lock.
Lock-free variant. In Java or C++, pack (timestamp, count) into one 64-bit word and update it with CAS: if the stored timestamp differs, CAS in (ts, 1), otherwise CAS in (ts, count+1). Retry on failure. For extreme write rates, use per-thread or per-core striped cells and sum them on read.
Complexity. Store operations are O(1) expected. hit is O(1). get_hits is O(300), a constant. Lock striping with 64 stripes means two random keys collide about 1.5% of the time.
5. Testing and validation
- Invariant stress tests. Run N threads each doing M
hits at a fixed timestamp, then assertget_hits == N*M. Do the same for increments through the store. - Expiry race test. One thread repeatedly
puts a short-TTL key while othersgetand the sweeper runs. Assert that a value is never deleted after a newer version was written. - Randomized history checking. Record operations with timestamps and check linearizability for the store (tools such as Jepsen's Knossos or Porcupine, or a simple model checker).
- Tooling. ThreadSanitizer for C++/Go,
jcstressfor Java. Run with more threads than cores and add random sleeps or yields to shake out interleavings. - Repeat and vary. Run thousands of iterations and several thread counts, since races are probabilistic.
- Benchmark. Measure throughput versus thread count for the global lock, striped and lock-free variants to justify the choice.
6. Common mistakes
- Locking
getandputindividually but leaving compound operations unprotected. - Reading the clock outside the lock and acting on a stale decision.
- Holding a lock while calling user callbacks, which risks deadlock.
- Using a read lock and then mutating inside it.
- Claiming
getHitsis exactly consistent without saying what the guarantee is. - Testing only with few threads, so races never show up.