Build a thread-safe sliding-window percentile monitor
Data Structure DesignModel answerLast 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:
addwill 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_secondsshould 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
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is supporting high concurrent write throughput while computing percentiles over a bounded time window with fixed memory. Storing raw samples doesn't scale: memory grows without limit and sorting millions of values is prohibitively expensive.
Solution: time-sharded histogram with striped locking.
1. Histogram bucketing
Map each latency value to a bucket in a fixed-size histogram. Use a log-linear scheme that offers:
- Exact buckets for small values (0–127 ms, one bucket each)
- Logarithmic bucketing above that: divide each power-of-two range
[2^k, 2^(k+1))into 64 sub-buckets
This gives about 1,664 total buckets covering 0 ms to ~24 days with relative error under 2%. The bucket index is computed in O(1) using bit operations.
2. Time slicing with a ring buffer
Divide the window into W one-second slots arranged in a ring. Slot t % W holds counts for second t. Each slot stores:
- An epoch timestamp (which second it represents)
- The histogram buckets for that second
When a writer arrives at second t and finds slot t % W belongs to an earlier epoch, it resets the slot before incrementing. This provides lazy expiration: old data is overwritten on-demand rather than scanned and deleted.
3. Striping for concurrency
Within each time slot, create S independent shards (e.g., 8), each protected by its own lock. Writers choose a shard based on their thread ID hash. This spreads concurrent writers across multiple locks, dramatically reducing contention compared to a single global lock.
In languages with atomic primitives (Java's LongAdder, C++ atomics), locks can be eliminated entirely. Python requires explicit locks since counts[i] += 1 is not atomic.
4. Percentile query
To compute the p-th percentile:
- Read the current time
now - For each shard, acquire its lock and check if
now - epoch < W. If so, copy its counts - Merge all valid snapshots into a single histogram
- Walk the merged histogram, accumulating counts until reaching rank
ceil(p * total_count) - Return the representative value of that bucket
Each shard is read atomically, but different shards are read at slightly different instants—acceptable for monitoring use cases.
Complexity
add: O(1) per call—bucket index computation, modulo arithmetic, and one lock acquisitionpercentile: O(W · S · B) where W = 60, S = 8, B = 1,664. This can be optimized to O(B) by maintaining a running aggregate and incrementally updating it as time slices enter/exit the window- Space: O(W · S · B) ≈ 6 MB of counters, independent of request volume
Edge cases and trade-offs
- Empty window: Return 0.0 when no data is present
- Clock choice: Use monotonic time (
time.monotonic()in Python) to avoid wall-clock adjustments - Thread ID hashing: Mix bits before modulo to avoid pathological clustering from aligned addresses
- Window granularity: The window is quantized to whole seconds, so effective length is between W-1 and W seconds
- Clamping: Negative values clamp to 0; values beyond the histogram's range clamp to the top bucket
Code
import math
import threading
import time
from array import array
class _Shard:
"""A single time-slice fragment with its own lock."""
__slots__ = ("lock", "epoch_sec", "buckets")
def __init__(self, num_buckets: int):
self.lock = threading.Lock()
self.epoch_sec = -1
self.buckets = array("q", bytes(8 * num_buckets)) # 64-bit counters
class LatencyMonitor:
# Log-linear histogram: 128 exact buckets, then 64 sub-buckets per power of two
EXACT_LIMIT = 128
SUB_BUCKETS = 64
MAX_VAL = (1 << 31) - 1
NUM_BUCKETS = EXACT_LIMIT + (MAX_VAL.bit_length() - 7) * SUB_BUCKETS # ~1664
STRIPES = 8
def __init__(self, window_seconds: int, clock=time.monotonic):
if window_seconds <= 0:
raise ValueError("window_seconds must be positive")
self.window = window_seconds
self.clock = clock
# Create W * S shards in a flat list
self.shards = [_Shard(self.NUM_BUCKETS)
for _ in range(window_seconds * self.STRIPES)]
@classmethod
def _bucket_index(cls, val: int) -> int:
"""Map a latency value to a histogram bucket."""
val = max(0, min(val, cls.MAX_VAL))
if val < cls.EXACT_LIMIT:
return val
# Find the highest set bit position
msb = val.bit_length() - 1
# Extract the top 6 bits after the MSB to determine sub-bucket
shift = msb - 6
sub = (val >> shift) - cls.SUB_BUCKETS
return cls.EXACT_LIMIT + (msb - 7) * cls.SUB_BUCKETS + sub
@classmethod
def _bucket_value(cls, idx: int) -> float:
"""Return the representative value for a bucket."""
if idx < cls.EXACT_LIMIT:
return float(idx)
offset = idx - cls.EXACT_LIMIT
power = offset // cls.SUB_BUCKETS + 7
sub = offset % cls.SUB_BUCKETS
low = (cls.SUB_BUCKETS + sub) << (power - 6)
high = (cls.SUB_BUCKETS + sub + 1) << (power - 6)
return (low + high) / 2.0
def _stripe_index(self) -> int:
"""Hash thread ID to choose a shard stripe."""
tid = threading.get_ident()
# Fibonacci hashing to mix bits
hashed = (tid * 2654435761) & 0xFFFFFFFF
return (hashed >> 16) % self.STRIPES
def add(self, latency_ms: int):
"""Record a latency measurement."""
bucket = self._bucket_index(latency_ms)
now_sec = int(self.clock())
slot = now_sec % self.window
shard = self.shards[slot * self.STRIPES + self._stripe_index()]
with shard.lock:
# Lazy expiration: reset if this shard is stale
if shard.epoch_sec != now_sec:
shard.buckets = array("q", bytes(8 * self.NUM_BUCKETS))
shard.epoch_sec = now_sec
shard.buckets[bucket] += 1
def percentile(self, p: float) -> float:
"""Compute the p-th percentile over the window."""
now_sec = int(self.clock())
merged = [0] * self.NUM_BUCKETS
total = 0
# Snapshot all valid shards
for shard in self.shards:
with shard.lock:
age = now_sec - shard.epoch_sec
if not (0 <= age < self.window):
continue
snap = shard.buckets[:] # Fast array copy
for i, count in enumerate(snap):
if count:
merged[i] += count
total += count
if total == 0:
return 0.0
# Find the bucket containing the target rank
target_rank = max(1, math.ceil(p * total))
cumulative = 0
for i, count in enumerate(merged):
cumulative += count
if cumulative >= target_rank:
return self._bucket_value(i)
return self._bucket_value(self.NUM_BUCKETS - 1)
Common mistakes
- Storing all samples: Memory grows unbounded and sorting is O(n log n) at query time
- Single global lock: Creates severe contention; throughput collapses under high concurrency
- Scanning to expire data: O(n) expiration on every write or read; the lazy reset approach is O(1)
- Using wall-clock time: Vulnerable to NTP adjustments; monotonic clocks are essential
This design achieves millions of writes per second with fixed memory and sub-millisecond percentile queries, making it suitable for production request monitoring.