KatInterview

Build a thread-safe sliding-window percentile monitor

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencypercentileshistogram

Last updated

Implement a concurrent data structure that tracks latency measurements and computes approximate percentiles over a rolling time window with bounded memory.

You need to build a LatencyMonitor class that records request latencies and answers percentile queries over a recent time window. The monitor will be shared across many concurrent threads, so it must handle high write rates without becoming a bottleneck.

Implement the following interface:

class LatencyMonitor:
    def __init__(self, window_seconds: int):
        """Create a monitor with the given rolling window size."""

    def add(self, latency_ms: int):
        """Record a latency measurement in milliseconds."""

    def percentile(self, p: float) -> float:
        """Return the p-th percentile (e.g., 0.99 for p99) over the window."""

Requirements

  • Concurrency: add will be called by thousands of threads simultaneously. Use fine-grained locking or lock-free techniques to avoid contention.
  • Throughput: The system must sustain millions of writes per second.
  • Bounded memory: Memory usage must not grow with the number of recorded samples.
  • Sliding window: Only measurements from the last window_seconds should contribute to percentile calculations.
  • Approximation: Exact percentiles are not required; document any trade-offs between precision and performance.

Example

monitor = LatencyMonitor(window_seconds=60)
for i in range(1, 101):
    monitor.add(i)
print(monitor.percentile(0.99))  # approximately 99.0

Discussion points

  • How do you prevent unbounded memory growth while retaining enough information to compute percentiles?
  • What data structure balances write speed, read speed, and memory overhead?
  • How do you expire old data efficiently without scanning the entire dataset?
  • What granularity of locking minimizes contention across many concurrent writers?

Hints

Hint 1

Instead of storing every individual sample, aggregate measurements into fixed-size buckets

Hint 2

Partition the time window into smaller intervals and organize buckets by both time and thread to reduce lock contention

Hint 3

Use a log-linear histogram scheme where bucket width grows with magnitude to cover a wide range with bounded space