In-Memory Event Deduplication with a Sliding Time Window
System DesignModel answerLast updated
Design a low-latency, high-throughput in-memory service that suppresses duplicate events within a configurable 10-minute window at 100k events/sec.
Background
Distributed systems that use at-least-once delivery guarantees — message queues, webhook retriers, event buses — routinely emit the same logical event more than once. Upstream retries after a network hiccup, publisher crashes mid-flush, and consumer-side reprocessing on restart all produce bursts of identical messages. Downstream services need a fast, cheap gate that absorbs those bursts before they propagate.
You are asked to design an in-memory deduplication service that sits in front of downstream consumers. It receives a stream of events, each identified by a stable deduplication key, and tells the caller whether the event is new or a duplicate of something already seen within the last 10 minutes.
What to Design
Functional Scope
- Single atomic operation:
check_and_record(key) → NEW | DUPLICATE. A caller must not have to issue a separate read and then a write; those two steps must be fused into one atomic operation. - 10-minute deduplication window. Support and be able to discuss two variants:
- Fixed from first seen: the key expires exactly 10 minutes after the first time it was recorded, regardless of how many duplicates arrive in between.
- Sliding refresh: each new duplicate resets the 10-minute clock, keeping the key alive as long as duplicates keep arriving.
- Predictable memory reclamation: expired keys must be cleaned up continuously. Large, bursty eviction sweeps that cause latency spikes are unacceptable.
Non-Functional Requirements
| Property | Target |
|---|---|
| p99 check latency | < 2 ms |
| Peak throughput | 100,000 events / second |
| Concurrency | Thread-safe; no lock-convoy bottlenecks on multi-core hardware |
| Memory | Bounded and predictable; sized at startup |
| Clock resilience | Immune to wall-clock adjustments and NTP steps |
Scale Assumptions
- Event rate: 100,000 / second sustained at peak.
- Window: 600 seconds.
- Maximum live keys in memory at any moment: ~60 million.
- Key size: 128-bit hash (16 bytes).
What Is Expected
Walk through your design as you would in a real interview. Cover:
- Clarifying questions you would ask before drawing anything.
- A back-of-envelope memory estimate that motivates your data structure choices.
- The core data structures and how they handle both window policies correctly.
- How and when expired keys are reclaimed without causing latency spikes.
- Your concurrency model — how you achieve thread safety at 100k ops/sec.
- How you handle the clock — which clock source, and why.
- The availability trade-off: pure volatile state vs. some form of persistence.
You do not need to write production code, but pseudocode for the core check-and-record logic is expected.
Hints
Hint 1
Before choosing a data structure, work out how many bytes 60 million entries would require under a naive approach (e.g., a standard concurrent hash map) and under a flat open-addressing table. The gap is large enough to drive your entire design.
Hint 2
Correctness and reclamation can be decoupled: the expiry check on every read guarantees exact semantics, while a separate bucketed structure handles bulk cleanup lazily. This separation also makes it easy to support both window policies with the same code path.
Hint 3
A single global lock is obviously wrong, but a single lock per shard at 64 shards and 100k ops/sec means roughly 1,500 ops/sec per lock — low enough that striped locking is simple and effective. Mention what you would do differently at 10× scale.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarifying Questions First
Before sketching any structure, nail down four things:
Atomicity. The operation must be a single check_and_record. A separate contains followed by insert is a data race: two threads processing the same key can both observe it absent and both return NEW. This is non-negotiable.
Window policy. Fixed-from-first-seen is simpler and safer for compliance-style events where the same alert legitimately recurs after the window expires. Sliding refresh is better for retry-storm suppression but can permanently suppress a key if retries never stop. Design should support both, configurable per call or per key type.
Failure direction. A false DUPLICATE (dropping a real new event) is almost always worse than a leaked duplicate. This means: when in doubt, return NEW. It also means a process restart that forgets state is acceptable only if downstream consumers are themselves idempotent.
Time base. Use local processing time on a monotonic clock, not publisher-embedded timestamps. A clock skew or a malicious publisher should not be able to pin keys open forever.
2. Memory Math
At 100k events/sec over a 600-second window:
- Max live keys: 100,000 × 600 = 60 million
- Raw key bytes: 60M × 16 B = 960 MB
- Naive
ConcurrentHashMap(JVM): ~100–150 bytes per entry due to object headers, node allocations, and boxing → 6–9 GB plus heavy GC pressure - Flat open-addressing table (key_hi u64 + key_lo u64 + timestamp u32 + padding): ~24 bytes/slot at 0.75 load factor → 80M slots × 24 B = ~1.9 GB, allocation-free after startup
The naive map is off the table. The design must be built around a flat, pre-allocated structure.
3. Core Data Structures
The design uses two cooperating structures per shard:
Index — flat open-addressing hash table. Pre-allocated at startup to the expected peak capacity. Each slot holds key_hi, key_lo, and last_tick (a u32 of deciseconds since process start on CLOCK_MONOTONIC, which wraps only after ~13 years). No dynamic allocation ever happens after startup, so there are no GC pauses and no resize spikes.
Expiry ring — circular array of 60 time slices, each 10 seconds wide. Each slice is an append-only list of keys recorded or refreshed during that slice. The ring drives bulk reclamation; it is not involved in correctness.
Why two structures? The index gives exact, per-read expiry checks. The ring amortizes the cost of finding and deleting expired entries — you never scan 60M keys to find the ones that aged out.
4. Check-and-Record Logic
check_and_record(key, now_tick, policy):
slot = index.find(key)
if slot exists and (now_tick - slot.last_tick) < WINDOW_TICKS:
# Key is live — it's a duplicate
if policy == SLIDING:
slot.last_tick = now_tick # reset the clock
ring[current_slice].append(key) # re-register for future reclamation
return DUPLICATE
# Key is absent or logically expired
if slot exists:
slot.last_tick = now_tick # reuse the physical slot
else:
index.insert(key, now_tick)
ring[current_slice].append(key)
return NEW
Three properties make this correct and efficient:
- Exact semantics on every read. The
now_tick - last_tick < WINDOWcheck happens inline. A key that is logically expired but not yet physically removed is treated asNEW. Reclamation lag never affects correctness. - Lazy ring reclamation. When the wall clock advances past a slice boundary, that slice becomes eligible. A housekeeping step (run incrementally per call, or on a background thread) iterates the oldest slice: for each key, delete it from the index only if
slot.last_tickstill falls in the expired range. If the key was refreshed (sliding policy), its tick is newer, so the stale ring entry is silently skipped. - Bounded incremental work. Process at most N entries per housekeeping step (e.g., 64). A large slice is never drained in one pause. Worst-case reclamation lag is one full slice (10 seconds), costing at most ~1.7% extra memory. That is a good trade.
Alternatives and why they fall short:
- Two generational tables swapped atomically — cleanup is trivial (drop old table), but lookups probe two tables and expiry becomes approximate (10–20 min window instead of exactly 10).
- Linked hash map — exact TTL ordering with O(1) ops, but two pointer fields plus a per-node allocation costs ~3× the memory and causes GC churn at 60M entries.
- Per-key timers / timer wheel — 60M live timers are expensive to maintain. The bucketed ring is effectively a coarse-grained timer wheel without per-key nodes.
5. Concurrency Model
Partition the key space into S shards (64–256, a power of two ≥ core count) by the high bits of the hash. Each shard owns its index and its ring, and holds one lock.
At 100k ops/sec spread across 64 shards, each lock sees ~1,500 ops/sec. Critical sections are a single hash probe (~200 ns) plus at most one array append. Lock contention is negligible and the implementation stays simple.
For 10× scale or latency targets tighter than 500 µs, migrate to a thread-per-core, shared-nothing model: route each request to its owning core via lock-free SPSC queues. No locks at all, cache lines stay hot. The trade-off is added routing latency (~1 µs cross-core hop) and more complex deployment.
6. Clock Handling
Always use CLOCK_MONOTONIC (or clock_gettime(CLOCK_MONOTONIC) on Linux) for all window arithmetic. It is never stepped by NTP, survives leap seconds gracefully, and is cheap (~20 ns per call). Wall clock is used only for logging and metrics.
Never use publisher-embedded timestamps for expiry. A clock-skewed or replayed event could bypass the window entirely.
One useful guard: if a publisher timestamp is more than one window duration stale, flag it as suspicious rather than silently deduplicating — a 10-minute-old retry has already missed the protection window.
Monotonic time does not survive a process restart. Any persisted state (see below) must store wall time and be rebased against CLOCK_MONOTONIC on recovery, accepting NTP-accuracy skew at startup.
7. Availability Trade-offs
| Mode | Durability | Complexity | Risk on restart |
|---|---|---|---|
| Pure volatile | None | Minimal | Duplicates leak for up to one window (10 min) |
| Write-ahead log (WAL) | Durable | Moderate | State recoverable; replay cost proportional to window |
| Hot standby | Near-durable | High | Failover in seconds; standby consumes same event stream |
Pure volatile is the right default when downstream consumers are idempotent or when a 10-minute duplicate window on restart is acceptable. The WAL approach appends (key, wall_timestamp) to a sequential log; on recovery, replay only entries within the current window. A hot standby mirrors the same partitioned stream and builds identical state; its value is eliminating restart gaps entirely, at the cost of double the memory and operational overhead.
Common Mistakes to Avoid
- Separate
contains+insertcalls instead of a single atomiccheck_and_record. - Using wall clock or publisher timestamps for window math — both are non-monotonic.
- Blocking GC-based eviction (e.g., relying on Java's
expireAfterWritein Caffeine) at 60M entries — GC pauses will blow the p99 budget. - Sizing the table dynamically — resizes at 60M entries are expensive and cause latency spikes.
- Forgetting to validate the stale ring entry's tick before deleting under sliding policy — this causes premature eviction of recently refreshed keys.