Real-Time Event Tracking with Rolling Window Aggregations
System DesignModel answerLast updated
Design a high-throughput pipeline that ingests behavioral events, deduplicates them, and serves accurate activity counts over 1-minute, 1-hour, and 24-hour sliding windows.
Background
Consumer platforms rely on near-real-time behavioral signals — things like content impressions, search clicks, follow actions, and page visits — to power fraud detection, personalization, and live engagement dashboards. You are asked to design a system that continuously captures these signals from client applications and answers low-latency queries about what a user did over the last minute, last hour, or last 24 hours.
Functional Requirements
- Event ingestion: Accept events containing a user ID, an action type, a target resource ID, free-form metadata, and a timestamp generated on the client.
- Deduplication: Guarantee that retried or replayed events are counted only once, using a per-event unique identifier supplied by the client.
- Aggregation API: Expose an endpoint that returns either a count breakdown by action type or a list of raw recent events for a specific user, for any of three windows: past 1 minute, past 1 hour, past 24 hours.
- Late arrivals: Correctly handle events that arrive out of order or up to 10 minutes after their client-side timestamp.
Non-Functional Requirements
- Throughput: 500 million daily active users producing roughly 50 billion events per day — approximately 600,000 events per second on average, spiking to 1.5 million per second.
- Freshness: A newly ingested event must be visible in query results within 5 seconds.
- Read latency: P99 under 50 ms for the 1-minute window, under 200 ms for the 1-hour and 24-hour windows.
- Durability and availability: No data loss once an event is acknowledged; 99.99% ingestion availability.
What to Cover
- API contracts — the ingestion endpoint and the query interface, including how you model windows and pagination.
- Pipeline architecture — the components between the client and the storage layer (message bus, stream processor, caches, persistent stores).
- Aggregation strategy — how pre-aggregation avoids full scans at read time, and how you handle window boundaries accurately.
- Deduplication and late-arrival mechanics — the state management and watermarking approach you would use.
- Scalability and trade-offs — partitioning choices, hot-key mitigation, and retention policies.
Hints
Hint 1
Start by sizing the problem numerically. 50B events/day works out to ~600K/s average and ~1.5M/s peak. Pin down event size (Protobuf/Avro at ~400 bytes) and figure out peak ingress bytes and dedup state size before drawing any components. Numbers should drive your architecture choices.
Hint 2
Avoid scanning raw events at query time. Instead, pre-aggregate in the stream processor into fixed-size time buckets (e.g., 5-second or 1-minute buckets) and store them in a tiered way: Redis for the hot short-term window, a wide-column store for longer retention. The query layer just sums whichever buckets fall inside the requested window.
Hint 3
Deduplication at 1.5M/s with a 10-minute window means you need to track roughly 900M event IDs concurrently. Consider where that state lives (local Flink RocksDB state vs. external Redis) and what the trade-offs are. Think about how late arrivals interact with already-emitted bucket counts and what side-output or reconciliation strategy you would use for events that fall outside the lateness bound…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the Problem First
Before any architecture decisions, establish the numbers.
- Throughput: 50B events/day ≈ 600K/s average, 1.5M/s peak. Design for 2–3M/s headroom.
- Event payload: ~400 bytes in Protobuf or Avro → ~600 MB/s peak ingress, ~25 TB/day raw, ~6–8 TB compressed.
- Dedup state: 10-minute window at peak = ~900M in-flight event IDs. At ~20 bytes per ID with overhead, that is ~50–100 GB. It must be sharded or kept in local stream-processor state, not a single Redis node.
- Key design question to raise with the interviewer: Are queries about the actor ("what did user X do?") or the target ("who interacted with resource Y?")? Each requires a different partition key. Assume both, defaulting to
user_idas the primary key.
2. API Design
# Ingestion (batched; up to ~100 events per call)
POST /v1/events
Body: {
"events": [{
"event_id": "01HZ...", // client-generated UUIDv7 (time-ordered)
"user_id": 123,
"action": "CONTENT_VIEW",
"target_id": 456,
"client_ts": 1718000000123,
"metadata": { ... }
}]
}
→ 202 Accepted (only after a durable broker ack)
# Query
GET /v1/users/{user_id}/activity
?window=1m|1h|24h
&mode=counts|events
&actions=CONTENT_VIEW,CLICK // optional filter
&limit=100&cursor=...
→ {
"window": "1h",
"as_of": 1718000005000, // returned so callers can reason about freshness
"counts": { "CONTENT_VIEW": 42, "CLICK": 7 }
}
Clients generate the event_id so retries reuse the same ID. The as_of field makes the freshness guarantee observable. The gateway stamps server_ts on arrival and clamps client_ts to server_ts when clock skew exceeds ~10 minutes.
3. Architecture
Clients → Load Balancer → Ingestion Gateway (stateless)
│ acks=all, RF=3
▼
Kafka "raw-events"
(~1,500 partitions, keyed by user_id)
│
┌────────────────────┼──────────────────┐
▼ ▼ ▼
Flink (event-time) Archiver → S3/HDFS Late-events topic
dedup + bucket agg (Parquet, hourly) (>10 min late)
│
┌─────────┴───────────┐
▼ ▼
Redis Cluster Cassandra
(5-sec buckets, (minute buckets, 48h TTL;
2h TTL; hourly buckets, 90d TTL)
sorted sets for
recent-event lists)
└────────────┬──────────────────┘
▼
Query Service
(+ short-TTL result cache)
Kafka uses user_id as the partition key so all events for a user land on the same partition. Retention is 7 days for replay. acks=all with min.insync.replicas=2 and multi-AZ brokers delivers the durability and availability targets.
Flink keys its operators by user_id, co-locating dedup state and aggregation state in the same task. RocksDB-backed state with 10-second checkpoints gives exactly-once guarantees. Flink flushes only changed buckets to storage every 1–2 seconds, keeping freshness under 5 seconds while batching writes from high-traffic users.
4. Aggregation Strategy: Tiered Pre-Aggregated Buckets
The core insight is that you should never scan raw events at query time.
| Window | Read source | Buckets read |
|---|---|---|
| 1 min | Redis 5-second buckets | 12 buckets → 1 HMGET |
| 1 hour | Cassandra minute_counts | 60 rows from one partition |
| 24 hours | Cassandra hourly_counts + minute_counts for edge hours | ~22 hourly + ≤120 minute rows |
Cassandra schema:
-- minute-level granularity, 48h retention
CREATE TABLE minute_counts (
user_id bigint,
day date,
minute_ts timestamp,
action text,
count counter,
PRIMARY KEY ((user_id, day), minute_ts, action)
) WITH default_time_to_live = 172800; -- 48h
-- hour-level granularity, 90d retention
CREATE TABLE hourly_counts (
user_id bigint,
month text,
hour_ts timestamp,
action text,
count counter,
PRIMARY KEY ((user_id, month), hour_ts, action)
) WITH default_time_to_live = 7776000; -- 90d
Flink writes absolute upserts, not increments. When Flink replays from a checkpoint after failure, it re-emits the same values, keeping the sink idempotent. This achieves end-to-end exactly-once semantics without distributed transactions.
For the "recent events" mode, a Redis sorted set per user (scored by event time, capped at ~1,000 entries) serves the minute and hour views. Older events are read from a Cassandra table partitioned by (user_id, day) and clustered by event_ts DESC.
5. Deduplication and Late-Arrival Handling
Deduplication is handled in Flink via a MapState<event_id, Boolean> per user with a TTL of 15 minutes (the 10-minute lateness bound plus margin). Because state is keyed by user_id, every lookup is local — no network hop. At 900M IDs in the window, this state fits in RocksDB on disk.
An alternative is a Redis SET event_id NX EX 900 at the gateway, which deduplicates before Kafka. The trade-off: it adds a synchronous network round-trip per event at 1.5M/s and creates a dependency that, if unavailable, can block ingestion. A Bloom filter in front of the Flink state can cut memory pressure by an order of magnitude if exact dedup is relaxed slightly for the oldest part of the window.
Late arrivals are handled with event-time processing and a bounded-out-of-orderness watermark of 30 seconds (fast enough for the 1-minute window, covers typical network jitter). Allowed lateness is set to 10 minutes. When a late event arrives within that bound, Flink updates the affected bucket in state and re-emits a corrected absolute count as an upsert — downstream stores converge to the right value. Events arriving more than 10 minutes late go to a side-output topic, are tracked in metrics, and are reconciled by a nightly batch backfill job. They are never silently dropped.
One trade-off to state explicitly: the 1-minute window is provisional. A query issued within 30 seconds of the current minute boundary may not reflect all events yet. Making as_of visible in the response lets callers decide whether that is acceptable.
6. Scalability Trade-offs
Hot users. A user with millions of followers generating millions of target events can hot-spot a Kafka partition and a Cassandra partition. Mitigations: write-side salting (spread across N sub-partitions and merge at read time), or capping per-user write rates with a token bucket at the gateway.
Storage sizing. Redis holds ~12 buckets × active action types × online users. For ~10M concurrently active users, this is tens of GB — manageable on a modest cluster. Cassandra uses TWCS (Time-Window Compaction Strategy) because writes are time-ordered and TTL-based deletion is the norm.
Common mistakes to avoid:
- Scanning raw events at query time — fatal at this scale.
- Using increments (INCR) instead of absolute upserts — makes checkpoint recovery non-idempotent.
- Putting all dedup state in a single external Redis — both a bottleneck and a durability risk.
- Ignoring late-arrival handling — minute-level counts will be systematically wrong during bursts of retried traffic.