Real-Time Sliding Window Visit Counter
System DesignModel answerLast updated
Design a system that tracks website page views over a rolling 60-second window and serves the current count with low latency at high traffic volumes.
Real-Time Sliding Window Visit Counter
Your task is to design a backend system that answers one question at any moment: how many page views has a website received in the last 60 seconds?
The site handles heavy traffic with sharp spikes. The count must be queryable in near real time — a few seconds of lag is acceptable, but not minutes.
What to cover
Define the metric precisely What counts as a page view? How do you handle bots, retries, and duplicate beacons? When does a unique-visitor count make more sense than a raw page-view count, and what does that change in the design?
Ingestion pipeline How do browser events reach your system? What happens when the event bus is temporarily unavailable? Walk through the path from browser beacon to durable storage.
Maintaining the rolling window Describe the core data structure and algorithm you use to compute the count for the most recent 60 seconds. Justify why you chose it over the alternatives.
Storage choices What do you write to, and why? Consider both the hot path (serving live counts) and the cold path (reconciliation and historical analysis).
Accuracy, deduplication, and late events How do you avoid double-counting retried events? What timestamp do you use for bucketing — client time or server time — and why? What is your policy for events that arrive after their window has closed?
Scaling and fault tolerance Walk through the back-of-envelope numbers. Where are the bottlenecks? How does the system behave when a consumer crashes and replays a batch of events?
Monitoring What signals tell you the count is drifting or the pipeline is falling behind?
Constraints and assumptions to state
You are expected to state your own assumptions about traffic volume, acceptable staleness, and accuracy tolerance before designing. A strong answer picks concrete numbers and defends them.
Hints
Hint 1
Before drawing any architecture, nail down the definition of 'visit'. Asking whether unique visitors or raw page views are needed changes the data structure entirely — a counter versus a cardinality estimator like HyperLogLog.
Hint 2
Think about why scanning raw timestamps per query is impractical at high traffic, and how pre-aggregating into one-second buckets reduces the query to a fixed-cost O(60) sum regardless of event rate.
Hint 3
Idempotency is the key to crash safety. Ask yourself: if a consumer replays 10 seconds of events after a restart, does the count stay correct? That question should drive your choice of how you write to your store.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is not the rolling window itself — that part is straightforward once you have bucketed counters. The score comes from how precisely you define the metric, how you handle crashes without double-counting, and how you reason about latency versus accuracy trade-offs.
1. Clarify Before Designing
What is a "visit"? This is the first question to ask.
- Page view: every successful page load counts once. Simplest definition and the right default here.
- Unique visitor: distinct users or devices in the window. Requires a cardinality structure (HyperLogLog or a dedup set), not a plain counter.
- Session: one count per user per inactivity gap. Irrelevant at 60-second granularity.
- Exclusions: known bot user agents, health-check endpoints, and prefetch requests should be filtered at the collector before the event enters the pipeline.
Proposed definition: count page views excluding known bots. Every page load carries a client-generated event_id; retries reuse the same ID, so duplicates can be dropped.
Scale assumptions (state these explicitly)
| Parameter | Value |
|---|---|
| Average traffic | 100K page views/s |
| Peak traffic | 1M page views/s |
| Event payload | ~200 bytes |
| Peak ingestion bandwidth | ~200 MB/s |
| Acceptable staleness | 2–5 seconds |
| Accuracy target | within ~0.1% in real time |
| Query load | ~100 QPS (dashboards, alerts) |
2. API Surface
Ingestion (fire-and-forget)
POST /collect
Body: { event_id, site_id, url, user_id?, client_ts }
Response: 204 No Content
The collector stamps server_ts and returns immediately. The beacon must never block page rendering.
Query
GET /visits/last-minute?site_id=...
Response: { count, window_start, window_end, as_of }
Include as_of so callers know how fresh the number is.
3. Architecture Overview
Browser beacon
|
v
Load Balancer -> Collectors (stateless, ~30 instances)
| validate, stamp server_ts, batch + compress
v
Kafka (topic: page_views, 128 partitions)
|
Stream Aggregators (one process per partition)
- filter bots, deduplicate by event_id
- bucket events into per-second counters
|
v
Redis (per-second hash buckets, TTL 10 min)
|
Query Service (reads 60 buckets, sums, caches ~1s)
Kafka -> S3 raw log -> hourly batch reconciliation job
4. The Rolling Window: Bucketed Counters
Why not scan raw timestamps? At 1M events/s the last 60 seconds holds up to 60M records. Scanning that per query is not viable.
The approach: bucket events by server_ts into one-second slots. Each slot holds the total count for that second. To answer a query, sum the 60 most recently completed buckets — O(60) regardless of traffic volume.
Redis layout:
key: visits:{site_id}:{epoch_second}
type: Hash
field: {partition_id} -> count (absolute total, not a delta)
TTL: 10 minutes
One hash per second, one field per Kafka partition. The query service reads 60 hashes with a pipelined HGETALL, sums all fields, and caches the result for about one second.
Stable window: serve [now − 62s, now − 2s) rather than including the currently-filling second. This prevents the visible jitter of a bucket whose count is still climbing.
Finer resolution: switching to 100 ms buckets gives more precision at the cost of 600 reads instead of 60. Rarely necessary.
5. Idempotent Writes and Crash Safety
INCRBY seems natural but breaks under replays. If an aggregator crashes after writing to Redis but before committing its Kafka offset, it replays those events and adds the counts a second time.
Instead, each aggregator writes the absolute count it has seen for a (partition, second) pair using HSET. A replay overwrites the field with the same or a corrected value — never inflates it. This makes writes idempotent and gives effectively exactly-once semantics when Kafka offsets are checkpointed alongside aggregator state.
6. Deduplication
Client beacons misfire and retry. Both the original and the retry carry the same event_id.
Each aggregator maintains an in-memory set of seen event_ids scoped to its assigned partitions, with a TTL slightly longer than the allowed lateness window (~2 minutes).
Memory cost at 1M/s × 120s = 120M IDs. At 16 bytes per UUID that is roughly 2 GB across the cluster, sharded naturally across partitions. If that is too much, a pair of rotating Bloom filters accepts a tiny false-positive undercount rate (~0.1%) in exchange for a 10–20× memory reduction.
Partition by event_id hash in Kafka so all retries of the same event land on the same consumer and the same dedup set.
7. Late and Out-of-Order Events
Use server_ts, not client_ts. Client clocks can be off by hours. With server timestamps, the only source of lateness is pipeline delay, which is measured in seconds.
Allowed lateness: keep buckets mutable for 5 seconds behind a watermark. Late events within that range update their bucket's hash field normally (idempotent write, so no double count).
Beyond the lateness limit: drop the event from the real-time count, increment a late_events_dropped counter, and let the nightly batch reconciliation job (reading raw Kafka logs from S3) produce the authoritative numbers.
The core trade-off: a tighter lateness window gives fresher numbers but slightly undercounts during spikes. A wider window is more complete but adds lag. 5 seconds is a reasonable default.
8. Scaling Analysis
| Component | Sizing |
|---|---|
| Collectors | ~30 instances handle 1M/s at ~33K events/s each |
| Kafka | 128 partitions at ~8K events/s per partition — comfortable |
| Aggregators | scale 1:1 with partitions |
| Redis writes | (128 partitions) × (buckets updated per second) ≈ a few hundred writes/s — trivially low because of pre-aggregation |
The pre-aggregation step is what makes Redis viable. Without it you would be writing 1M events/s directly into the store.
Hot-key risk: a single site_id on a single second gets at most 128 fields in one hash — fine. For per-site breakdowns at very high traffic, shard Redis by site_id.
9. Monitoring
- Pipeline lag: Kafka consumer group lag per partition. Alert if lag exceeds 10 seconds.
- Late-event drop rate: spikes here indicate clock skew or slow consumers.
- Redis write latency: p99 should stay under 5 ms.
- Count deviation: compare real-time totals against the batch reconciliation job once per hour. A persistent divergence above 0.5% signals a dedup or replay bug.
- Collector error rate: failed Kafka produces trigger local disk buffering; alert if the buffer grows.
Common Mistakes to Avoid
- Bucketing by client time — attackable, unreliable, and introduces large apparent lateness.
- Using
INCRBYinstead ofHSET— breaks idempotency and leads to overcounting on replays. - Scanning raw events per query — does not scale past a few thousand events/s.
- Including the current (still-filling) second in the window — causes noisy, jittery reads.
- Skipping the batch reconciliation layer — real-time counts are approximate by design; you need a ground-truth path.