Sliding-Window Trending URLs with Deduplication
Data Structure DesignModel answerLast updated
Design a data structure that tracks the most-visited URLs over a configurable recent time window, with idempotent inserts and efficient eviction.
Sliding-Window Trending URLs
You are building a real-time analytics backend that ingests a continuous stream of page-visit events. Each event carries three fields:
event_id— a globally unique string identifier for the eventurl— the page that was visitedts— the time the visit occurred, in milliseconds
Implement a tracker that supports the following operations:
record(event_id, url, ts)
Registers one visit. The tracker should:
- Silently ignore duplicate
event_ids (retries may arrive; treat them as no-ops). - Silently ignore events that arrive too late, defined as more than a configurable lateness budget
Lms behind the furthest-ahead timestamp the tracker has ever seen. - Otherwise, store the event and update all internal state.
top_urls(T, K, now)
Returns the K most-visited URLs whose timestamps fall in the half-open interval (now − T, now], ordered by visit count descending. Break ties alphabetically by URL so results are deterministic. T will never exceed the tracker's configured maximum window size W.
unique_count(T, now)
Returns the number of distinct URLs visited in the same interval (now − T, now].
Configuration
The tracker is constructed with three parameters:
W— the maximum window size in ms (no query will ask for a span longer than this).L— the maximum lateness in ms (events older thanmax_seen_ts − Lare dropped).g— bucket granularity in ms. Time is divided into buckets of widthg. Smaller values are more precise but use more memory.
Requirements and constraints
- Inserts should be efficient: aim for better than O(N) per event where N is the number of distinct URLs in the window.
- Memory must stay bounded: old data outside the window should be evicted automatically as the clock advances.
- Out-of-order events within the lateness budget
Lmust be accepted and counted correctly. - Deduplication by
event_idmust also expire over time — a global ever-growing set of seen IDs is not acceptable.
What is expected in your answer
Walk through the data structures you would choose and why. Explain how correctness is maintained across inserts, evictions, and queries. Analyze time and space complexity. Discuss how you would extend the design to support multiple concurrent writer threads and horizontal sharding across machines.
Example
W = 10_000 ms, L = 2_000 ms, g = 1_000 ms
record("e1", "a.com", 1000)
record("e2", "a.com", 2000)
record("e3", "b.com", 2000)
record("e1", "a.com", 1000) # duplicate → ignored
top_urls(T=5000, K=2, now=5000)
# window is (0, 5000]: a.com×2, b.com×1
# → [("a.com", 2), ("b.com", 1)]
unique_count(T=5000, now=5000)
# → 2
Hints
Hint 1
Time-bucketing is the key to bounded memory and automatic dedup expiry: store event IDs per bucket so they expire for free when the bucket is evicted, instead of keeping a single ever-growing seen-ID set.
Hint 2
For the live count structure, think about what operations you actually need: you only ever increment by 1 on insert and decrement by 1 per click on eviction. A doubly-linked list of frequency nodes (LFU-style) gives O(1) increment and decrement while letting you read the top counts by walking from the high end.
Hint 3
For sub-window queries (T < W) or a now value behind the current clock, the live structure covers the full window W and cannot be used directly — fall back to scanning only the relevant buckets and aggregating their per-bucket counters.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarify the contract first
Before writing any code, pin down the parameters. The tracker is configured with W (max window), L (max lateness), and g (bucket width in ms). These three values define every trade-off in the design.
The internal clock advances monotonically: clock = max(largest ts seen in any accepted event, largest now seen in any query). The live window is always (clock − W, clock].
An event is dropped if:
ts < clock − L(arrived too late)event_idwas already recorded in its bucket (duplicate)
Three structures, one job each
1. Time buckets
Divide the timeline into slots of width g. Each bucket at index i covers [i*g, (i+1)*g) and stores:
- a
Countermappingurl → hit countwithin that bucket - a
setofevent_ids seen in that bucket
Only the buckets within [clock − W − L, clock] need to be retained. When the clock advances, expired buckets are popped from the low end.
Storing IDs per bucket (not globally) means dedup state expires automatically with the bucket — no unbounded set.
2. A live frequency structure for window W
Rather than re-scanning all buckets on every query, maintain an incremental count over the full window. The only operations needed are +1 on insert and −1 per click on eviction — never arbitrary deltas. That matches an LFU-style doubly linked list perfectly:
- A
dictmaps each URL to a node in a doubly linked list. - Each node holds a count value and the set of URLs with that count, in ascending order.
- Increment: move the URL to the next higher node (create it if needed). O(1).
- Decrement: move the URL to the next lower node (remove its node if empty, remove the URL from the live structure if count hits 0). O(1).
- Top-K: walk backward from the tail (highest count), collecting URLs until K are gathered. O(K + number of ties at the boundary).
3. A deque of bucket indices for eviction ordering
A deque holds bucket indices in insertion order. When the clock advances, pop from the left while the front index is below the new low edge, decrement the live structure for every URL count in that bucket, and discard the bucket.
Correctness invariant
The live frequency structure always equals the sum of all per-bucket counters for buckets with index in
[floor(clock − W) / g, floor(clock) / g].
recordtouches exactly one bucket and increments the live structure by the same amount — atomically from the invariant's perspective._advanceremoves whole buckets from the deque and decrements the live structure bucket by bucket.- Because the clock is at least as large as any accepted timestamp, no bucket beyond
floor(clock/g)can exist.
For top_urls(T, K, now):
- If
now ≥ clockandT = W, the live structure is the exact answer. - Otherwise —
T < W, ornowlags behind the current clock — fall back to scanning only the buckets whose indices fall inside(now − T, now], merge their counters, then return the top-K from the merged result. This path is O(T/g × distinct URLs per bucket) but is correct for arbitrary sub-windows.
unique_count follows the same two-path logic: use the live structure's key count for the full-window case, or count distinct URLs across the relevant buckets otherwise.
Complexity
| Operation | Time | Notes |
|---|---|---|
record | O(1) amortized | bucket lookup + LFU update; eviction cost is paid once per bucket |
top_urls (T=W, now≥clock) | O(K) | walk from tail of freq list |
top_urls (sub-window) | O((T/g) × U) | U = avg distinct URLs per bucket |
unique_count | O(1) / O(T/g × U) | same two paths |
Space: O(W/g × U) for buckets plus O(U) for the live structure, where U is distinct URLs in the window. Both are bounded by W and g.
Common mistakes
- Global event-ID set. It grows forever and never reclaims memory. Per-bucket sets expire for free.
- Re-building top-K from scratch on every query. Sorting all URLs on each call is O(U log U) and unnecessary. The LFU structure gives O(1) incremental maintenance.
- Moving the clock backward. The clock must be strictly monotonic. A late query
nowshould not evict data that a future query with a largernowwould still need. - Off-by-one on the half-open interval. The window is
(now − T, now], so a hit at exactlynowis included and a hit at exactlynow − Tis excluded. Be consistent in bucket boundary comparisons.
Concurrency extension
For multiple writer threads, the two main contention points are the bucket map and the live structure. A practical approach:
- Stripe the bucket map by
(bucket_index % S)acrossSindependent shards, each with its own lock. Writers only contend on the same stripe. - The live frequency structure is written on both insert and eviction. Protect it with a single read-write lock: many concurrent readers for queries, exclusive access for writers.
- Alternatively, accept slightly stale top-K results by snapshotting the live structure periodically (e.g., every 100ms) and serving queries from the snapshot. This eliminates read contention entirely.
Horizontal sharding
Partition the event stream by URL hash across N nodes. Each node maintains its own tracker and answers sub-window queries independently. A coordinator fans out each top_urls query to all N nodes, merges the per-shard counts (a simple merge of K-length sorted lists per shard is O(N×K)), and returns the global top-K. unique_count requires a HyperLogLog union at the coordinator layer rather than a simple sum, since the same URL can appear on multiple shards if the hash function changes or resharding has occurred.