Rolling-Window Key-Value Store with Live Average
Data Structure DesignModel answerLast updated
Design a key-value store that expires entries older than a configurable time window and supports O(1) average-case get, put, and average queries.
Rolling-Window Key-Value Store with Live Average
You are building a lightweight in-memory store for a metrics pipeline. The store accepts numeric readings tagged by a string key. Each reading is only meaningful for a fixed duration: once a reading is older than window_ms milliseconds it is considered stale and must never be surfaced to callers.
Implement the class RollingStore with these three methods:
put(key, value)
Record value for key, timestamped at the current time. If key already exists (expired or not), this call replaces it entirely and resets its timestamp to now.
get(key) -> float | None
Return the stored value for key if it exists and is not stale. Return None if the key is absent or has expired. This call must not change the key's timestamp.
average() -> float | None
Return the mean of every value that is currently within the window. If no values are live, return None (do not return 0 and do not raise a division error).
Rules and constraints
- An entry with timestamp
tsis valid whents >= now - window_ms. An entry exactlywindow_msold is still valid; the boundary is inclusive on the older end. - You can assume that all currently valid entries fit in memory at any one time, but the full history of all writes does not. Your implementation must free expired data.
- The system is single-threaded; no concurrency concerns.
- Inject the clock as a callable so that tests can control time without sleeping.
window_msmust be a positive integer; reject0or negative values.
What you are expected to produce
- The implementation in your language of choice.
- A discussion of the data structures you chose and why.
- Time and space complexity for each method, including the amortized argument.
- At least two design trade-offs or edge cases you considered.
Example
store = RollingStore(window_ms=10_000, clock=mock_clock)
mock_clock.set(t=0)
store.put("cpu", 40)
store.put("mem", 80)
store.average() # → 60.0
mock_clock.set(t=5_000)
store.put("cpu", 50) # refreshes "cpu" timestamp to t=5000
store.average() # → 65.0 (both keys still valid)
mock_clock.set(t=10_001)
# "mem" was inserted at t=0; now - window_ms = 10_001 - 10_000 = 1 → ts 0 < 1, expired
store.get("mem") # → None
store.average() # → 50.0 (only "cpu" at t=5000 survives)
mock_clock.set(t=20_000)
store.average() # → None (all entries expired)
Hints
Hint 1
Think about what ordering property put() gives you for free: since every new timestamp equals 'now' and the clock never goes backward, insertion order and timestamp order are always the same. Does that suggest a simpler sort strategy than a heap?
Hint 2
You need O(1) lookup by key and O(1) removal of the oldest entries. Two separate data structures, each good at one of those things, can be linked together — this is the same pairing used in an LRU cache.
Hint 3
Rather than scanning all entries on every average() call, maintain a running sum and update it incrementally on every put and every eviction. What bookkeeping lets you keep that sum exact when a key is overwritten before it expires?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Data Structure Choice
Three operations, three requirements:
- O(1) lookup by key → hash map from key to
(value, timestamp). - O(1) ordered eviction → a structure that keeps entries sorted by timestamp so stale entries are always at one end. Because
putalways stamps withnow, and the clock is non-decreasing, every new or refreshed entry belongs at the tail. Insertion order equals timestamp order automatically — no heap or sort needed. A doubly linked list maintained by anOrderedDict(Python) orLinkedHashMap(Java) handles this perfectly. - O(1) average → a running
totaland the map's length as the count. Update both on every mutation.
The overall structure is identical to an LRU cache, except the eviction criterion is age rather than frequency.
Eviction is lazy: at the start of every public call, pop from the head while the head entry is stale. Because the list is sorted, the first valid head means every remaining entry is valid, so the loop stops immediately in the common case.
Why the Invariants Hold
After every eviction sweep:
- The map contains exactly the non-stale entries.
- They are ordered oldest-to-newest (head to tail).
totalequals the sum of their values.
put preserves this: it moves the key to the tail with the current timestamp. If the key already existed, its old value is subtracted from total before the new value is added — preventing double-counting. If the old entry had already expired, the eviction sweep removes it first, so the update becomes a clean insert.
get runs the eviction sweep but never moves the key or updates the timestamp, satisfying the spec's requirement.
Complexity
| Method | Amortized | Worst case (single call) |
|---|---|---|
put | O(1) | O(k) |
get | O(1) | O(k) |
average | O(1) | O(k) |
k is the number of entries that expire since the previous call. The amortized argument: each put creates at most one node, and each node is evicted exactly once. Total eviction work across any sequence of N puts is O(N).
Space is O(n) where n is the number of currently valid keys.
Edge Cases Worth Mentioning
- Empty or fully expired window.
average()returnsNone, not0. - Overwriting an unexpired key. Subtract the old value, add the new one, move to the tail. Do not create a second entry.
- Overwriting an already-expired key. Eviction runs first, so the stale entry is gone before the insert; it behaves like a fresh key.
- Exact boundary. An entry exactly
window_msold (ts == now - window_ms) is still valid. The cutoff ists < now - window_ms. - Floating-point drift. Repeatedly adding and subtracting doubles accumulates rounding error. For integer values use integer arithmetic. For doubles, reset
totalby recomputing it from scratch when the map empties — this naturally clears any drift without extra bookkeeping. - Non-monotonic clock. The sorted-list assumption breaks if the clock jumps backward (e.g., after an NTP step). Clamp with
now = max(clock(), last_now)to make it monotonic.
Common Mistakes
- Running a linear scan over all entries inside
average()instead of maintaining a running sum — that makesaverageO(n). - Using a min-heap for eviction — it works but is O(log n) per operation and unnecessary given the monotonic-timestamp property.
- Forgetting to subtract the old value on overwrite, which causes the running sum to drift and the average to be wrong.
- Returning
0.0instead ofNonewhen the window is empty.
Trade-offs Worth Discussing
Exact vs. approximate eviction boundary. With lazy eviction, a burst of simultaneous expirations hits one caller with O(k) work. For a soft-realtime system you could evict a fixed number of entries per call (bounded incremental eviction), trading exactness for predictable latency.
Time-bucketed aggregates. Real metrics systems partition the window into B fixed-width buckets, each storing a partial sum and count. This bounds per-call work to O(B), tolerates approximate expiry boundaries, and is the standard approach in tools like Prometheus. Worth mentioning as the production alternative to the exact design above.
Python Implementation
from collections import OrderedDict
from typing import Callable, Hashable, Optional
class RollingStore:
"""
Key-value store that only surfaces entries written within the last window_ms.
Validity: ts >= now - window_ms (inclusive on both ends).
"""
def __init__(
self,
window_ms: int,
clock: Optional[Callable[[], int]] = None,
) -> None:
if window_ms <= 0:
raise ValueError("window_ms must be positive")
self._window = window_ms
self._clock: Callable[[], int] = clock or (
lambda: int(__import__("time").time() * 1000)
)
# OrderedDict preserves insertion order → ascending timestamp order.
# Value: (numeric_value, timestamp_ms)
self._data: "OrderedDict[Hashable, tuple[float, int]]" = OrderedDict()
self._total: float = 0.0
self._last_now: int = 0
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _now(self) -> int:
"""Monotonic wrapper around the injected clock."""
ts = max(self._clock(), self._last_now)
self._last_now = ts
return ts
def _evict(self, now: int) -> None:
"""Remove all entries older than now - window_ms from the head."""
cutoff = now - self._window
while self._data:
key, (value, ts) = next(iter(self._data.items()))
if ts >= cutoff:
break # head is valid → everything behind it is valid too
self._data.popitem(last=False)
self._total -= value
# Reset total to zero when the store empties to clear any FP drift.
if not self._data:
self._total = 0.0
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def put(self, key: Hashable, value: float) -> None:
now = self._now()
self._evict(now)
existing = self._data.get(key)
if existing is not None:
self._total -= existing[0] # remove old contribution
self._data.move_to_end(key) # reposition to tail (newest ts)
self._data[key] = (value, now)
self._total += value
def get(self, key: Hashable) -> Optional[float]:
self._evict(self._now())
entry = self._data.get(key)
return None if entry is None else entry[0]
def average(self) -> Optional[float]:
self._evict(self._now())
n = len(self._data)
return None if n == 0 else self._total / n