KatInterview

In-Memory Store with Sliding-Window Request Counter

System DesignModel answer
MediumModel answerSystem Designconcurrencymetricsring-buffer

Last 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_ops must return a reasonably accurate count. A small bounded error (less than one second's worth of traffic) is acceptable.
  • put and get must 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 put and get off 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.