In-Memory Store with Sliding-Window Request Counter
System DesignModel answerLast updated
Design a thread-safe key-value store that tracks how many operations occurred in any recent time window, without storing one entry per request.
Background
You are building an in-memory key-value store that needs to report its own traffic. Engineers want to query how many operations the store has handled over a recent rolling interval — useful for dashboards, alerting, and adaptive rate limiting — without adding significant overhead to the hot path.
Task
Implement a class with the following interface:
class TrackingKVStore:
def __init__(self):
pass
def put(self, key, value):
"""Insert or update a key. Counts as one operation."""
def get(self, key):
"""Return the value for key, or None if absent. Counts as one operation."""
def recent_ops(self, window_seconds: int) -> int:
"""Return the total number of put + get calls in the last window_seconds."""
Both put and get count toward the metric, including get calls for keys that do not exist.
Requirements
- The store must be safe to use from multiple threads simultaneously.
recent_opsmust return a reasonably accurate count. A small bounded error (less than one second's worth of traffic) is acceptable.putandgetmust stay fast: do not block them on expensive aggregation work.- Design for up to 100,000 operations per second.
Example
store = TrackingKVStore()
store.put('x', 10)
store.put('y', 20)
store.get('x')
print(store.recent_ops(60)) # 3, assuming all calls happened within the last 60 seconds
print(store.recent_ops(0)) # 0
What is expected
Walk through your design choices before writing code. Cover:
- How you store operation counts without logging every timestamp
- How you keep
putandgetoff the slow path - How you handle concurrent reads and writes
- Memory usage, time complexity of each method, and the trade-offs you are making
Hints
Hint 1
Logging one timestamp per request seems straightforward, but at 100k ops/s over a 1-hour window that is 360 million entries. Think about what granularity you actually need and whether you can aggregate eagerly instead of storing raw events.
Hint 2
A circular array where each slot represents one second, identified by (epoch_second % array_length), lets you recycle old slots without a background cleanup thread. What do you need to store per slot so you can tell whether it holds current or stale data?
Hint 3
A single shared lock for all metric writes becomes a bottleneck at high throughput. Consider partitioning the metric storage across several independent counters and combining them only at query time — similar to how a striped hash map reduces contention on the data side.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify before designing
A few things are worth confirming upfront:
- Maximum window. Assume callers never ask for more than one hour (3,600 s). This caps the memory budget.
- Precision. One-second granularity is fine. The count can be off by up to one bucket at the trailing edge of the window.
- What "counts". Both
putandgetcount, including cache misses onget. - Return value.
recent_opsreturns a raw count, not a rate. If the caller wants ops/s, they divide. Confirm which is needed. - Optimization target. Writes happen at up to 100k/s;
recent_opsis called rarely by comparison. Optimize the write path and allow the read to do proportionally more work.
Why not store individual timestamps?
At 100,000 ops/s over a 60-minute window, a naive timestamp log would hold 360 million entries — several gigabytes of memory — and every get or put would append to it. Pruning stale entries either happens lazily on the hot path (slowing writes) or requires a background thread (added complexity). Neither is a good trade.
Core data structure: a ring buffer of second-level buckets
Allocate a fixed circular array of length C = 3600 (the maximum window in seconds). Each slot holds two values: the epoch-second it was last written to, and a count of operations during that second.
Recording an operation:
- Compute
sec = int(now)andi = sec % C. - If
stamps[i] != sec, the slot contains data from a prior cycle. Reset it: setstamps[i] = secandcounts[i] = 0. - Increment
counts[i].
This is lazy expiry — no background sweeper, no per-request allocation.
Querying a window of W seconds:
Iterate over the integers sec in (now - W, now]. For each, look up i = sec % C. If stamps[i] == sec, add counts[i]. The stamp check discards slots whose data belongs to a prior cycle.
Memory: O(C) regardless of traffic. 3,600 slots × 2 integers is roughly 30–60 KB, compared with gigabytes for a timestamp log.
Concurrency design
There are two independent shared resources, and each gets its own strategy.
Key-value data — shard locks. Divide the dict into S shards (typically 16), with each shard protected by its own lock. put and get acquire only the lock for hash(key) % S, so operations on different keys rarely contend.
Metrics — stripe the ring buffers. A single global lock on the metric array would serialize all 100k writes per second. Instead, create S independent _BucketWindow instances. Each operation records into the stripe chosen by thread_id % S. Writers contend only with the small fraction of threads sharing their stripe. recent_ops sums across all stripes, but reads each stripe under its own short lock. The result may miss a handful of in-flight increments — acceptable for an operational metric.
Implementation
import threading
import time
class _BucketWindow:
"""Ring buffer of per-second counters with lazy slot expiry."""
def __init__(self, capacity: int):
self.capacity = capacity
self.stamps = [-1] * capacity # which epoch-second owns this slot
self.counts = [0] * capacity
self.lock = threading.Lock()
def record(self, sec: int) -> None:
i = sec % self.capacity
with self.lock:
if self.stamps[i] != sec: # stale data from a prior cycle
self.stamps[i] = sec
self.counts[i] = 0
self.counts[i] += 1
def count_window(self, now_sec: int, window: int) -> int:
total = 0
with self.lock:
for s in range(now_sec - window + 1, now_sec + 1):
i = s % self.capacity
if self.stamps[i] == s:
total += self.counts[i]
return total
class TrackingKVStore:
def __init__(
self,
max_window: int = 3600,
num_stripes: int = 16,
clock=time.monotonic,
):
self._clock = clock # injectable for deterministic tests
self._max_window = max_window
self._n = num_stripes
# Striped key-value storage
self._shards = [{} for _ in range(num_stripes)]
self._shard_locks = [threading.Lock() for _ in range(num_stripes)]
# Striped metric windows
self._windows = [_BucketWindow(max_window) for _ in range(num_stripes)]
def _record(self) -> None:
sec = int(self._clock())
stripe = threading.get_ident() % self._n
self._windows[stripe].record(sec)
def put(self, key, value) -> None:
idx = hash(key) % self._n
with self._shard_locks[idx]:
self._shards[idx][key] = value
self._record() # metric work happens outside the data lock
def get(self, key):
idx = hash(key) % self._n
with self._shard_locks[idx]:
value = self._shards[idx].get(key)
self._record()
return value
def recent_ops(self, window_seconds: int) -> int:
if window_seconds <= 0:
return 0
window = min(int(window_seconds), self._max_window)
now_sec = int(self._clock())
return sum(w.count_window(now_sec, window) for w in self._windows)
A few implementation notes worth mentioning aloud:
time.monotonic()instead of wall-clock time prevents NTP corrections from moving the clock backward and corrupting bucket assignments._recordruns after releasing the shard lock. Metric overhead never extends the time a data lock is held.- The injected
clockparameter makes unit tests deterministic without mocking global time.
Complexity
| Method | Time | Space |
|---|---|---|
put / get | O(1) | — |
recent_ops(W) | O(S × W) — at most 16 × 3,600 = 57,600 cheap steps | — |
| Total space | O(K + S × C) | K = number of keys; metric memory is fixed |
If recent_ops is called frequently and W is large, you can maintain a running total per stripe: add on each record, subtract when a slot is recycled. That reduces recent_ops to O(S), but only works for a single fixed window size. Mention it as a follow-up trade-off.
Edge cases
- Idle gaps longer than
Cseconds: stale slots are identified by the stamp mismatch and skipped. No phantom counts accumulate. - Window larger than
max_window: clamp tomax_windowrather than raising — callers querying a 2-hour window get the best available answer. - Zero or negative window: return 0 immediately.
- Partial current second: the current second is included in full. The real window is
(now - W, now]at one-second resolution, so the maximum error is one second's worth of traffic at the boundary.
Key trade-offs to state out loud
- Exact log vs. bucketed counts. An exact timestamp deque gives perfect precision but O(QPS × W) memory and per-request pruning cost on the hot path. Buckets give bounded memory and bounded error — the right trade for a monitoring metric.
- Lazy expiry vs. background sweeper. Lazy expiry needs no extra thread and has no timer-drift risk. A sweeper would help only if you needed precomputed multi-resolution aggregates.
- Stripe count. More stripes reduce write contention but make
recent_opsproportionally more expensive. 16 is a reasonable default; the right number depends on core count and observed contention.