Streaming Analytics: Building a Live Product Popularity Service
System DesignModel answerLast updated
Design a distributed system that processes purchase event streams in real time and continuously exposes the most popular products across multiple time horizons.
You're building a service that processes a continuous feed of purchase transactions and maintains up-to-date rankings of the most frequently purchased products. Each transaction arrives as a record containing customer_id, item_id, and timestamp.
Your system must simultaneously track and serve the most popular K items across different observation periods:
- Short-term trend windows (such as the past 5 minutes or past hour)
- Medium-term windows (such as the trailing 24 hours)
- Calendar-aligned aggregations (today's totals so far, plus completed historical days)
Design the complete architecture and explain your approach to:
- Event schema and output format — what fields belong in the incoming events and in the popularity rankings you expose
- Ingestion layer design — durable messaging infrastructure, how you partition the stream, and strategies for load balancing when certain products dominate traffic
- Time window implementation — techniques for computing overlapping time ranges efficiently, managing bucket granularity, and handling calendar boundaries
- Ranking computation — data structures and algorithms for maintaining sorted popularity lists, including both precise and space-efficient approximation methods
- Timestamp semantics — dealing with events that arrive delayed, out of sequence, or duplicated; defining when a time window closes
- Persistent state strategy — where aggregation state lives, how it's organized, checkpointing, and automatic cleanup
- Reliability guarantees — recovery from failures and whether you provide exactly-once or at-least-once processing
- Horizontal scaling approach — distributing work across machines, handling imbalanced data, and elasticity
- Read path architecture — how clients query current rankings, and whether you support real-time subscriptions
- Performance tuning — trade-offs between result freshness, computational cost, and ranking precision
Assume the system handles tens of thousands of transactions per second normally, with spikes reaching hundreds of thousands during promotional events. The product catalog contains tens of millions of items with highly skewed popularity. The ranking depth K is around 100, and read traffic is in the thousands of queries per second with tight latency requirements.
Hints
Hint 1
Think about how to avoid recomputing every overlapping window from scratch—can you incrementally update by adding new data and removing expired data?
Hint 2
A single extremely popular product can create a hotspot. Consider local aggregation before shuffling data across the network.
Hint 3
For very large time windows, storing exact counts for every product may not be feasible. Investigate probabilistic data structures that can estimate heavy hitters with bounded error.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Streaming Product Popularity Service
Overview and Requirements Clarification
Start by establishing concrete numbers with your interviewer. The design changes significantly based on scale.
Functional scope:
- Process purchase events continuously and maintain popularity rankings
- Support multiple concurrent time horizons: short (5 min, 1 hour), medium (24 hours), and daily calendar periods
- Expose current top-K items for each window through a query interface
- Handle the "today so far" running view plus finalized historical daily snapshots
Scale parameters to discuss:
- Event throughput: approximately 50,000 purchases/second average, 500,000/second peak load (about 4 billion events daily)
- Catalog size: roughly 100 million distinct products following a power-law distribution
- Ranking depth: K = 100 for client consumption, but precompute top 1,000 internally for flexibility
- Latency targets: short windows updated within 5 seconds, longer windows within 30 seconds, daily finalization within minutes after midnight
- Read load: approximately 10,000 queries/second with sub-50ms p99 latency
- Accuracy needs: precise counts preferred for daily reporting; bounded approximation acceptable for real-time short windows if it reduces infrastructure cost
Critical schema addition: The basic schema lacks deduplication capability. Extend to:
{
event_id: string, // unique identifier for dedup
customer_id: string,
item_id: string,
quantity: int, // support multi-unit purchases
event_timestamp: long, // when purchase occurred
ingestion_timestamp: long
}
Architecture Components
Event Sources → Message Bus (Kafka) → Stream Processor (Flink/Spark Structured Streaming)
├─ Deduplication
├─ Item-keyed aggregation
└─ Per-window ranking
↓
Serving Layer (Redis + DynamoDB)
↓
Query API ← Clients
Raw events archived to S3 → Batch reconciliation job (nightly)
Ingestion and Partitioning Strategy
Message infrastructure: Use Apache Kafka with 7-day retention. This provides:
- Durability for replay during failure recovery
- Multiple consumer groups for different processing pipelines
- Compaction support for changelog topics
Partitioning choices:
Initially partition by customer_id or event_id for uniform distribution. This keeps deduplication logic colocated—duplicate detection needs all instances of an event in the same partition.
However, aggregation requires grouping by item_id. Implement a two-stage approach:
- Pre-aggregate locally within each partition before reshuffling
- Repartition by
item_idfor global aggregation
Hot-product mitigation: When a single product receives massive traffic (viral item, flash sale), naive partitioning creates bottlenecks:
- Local pre-aggregation: Before repartitioning, combine events into small time buckets (1-second intervals) per item within each source partition. This reduces shuffle volume by 10-100x for popular items.
- Dynamic key salting: Detect items exceeding a threshold and split them across multiple partition keys:
(item_id, random_0_to_N). Add a subsequent merge stage that re-groups these salted shards by the originalitem_idand sums their counts. - Critical ordering: Merge salted counts before selecting top-K. Ranking salted partial counts produces incorrect results.
Efficient Window Computation
Computing independent sliding windows is prohibitively expensive—a 24-hour window sliding every 10 seconds creates 8,640 overlapping instances. Each event would be counted thousands of times.
Micro-bucket technique: Divide each window into small fixed-size buckets. Maintain a rolling collection of bucket counts and compute window totals through addition and subtraction:
| Window Type | Bucket Size | Buckets Retained | Update Frequency |
|---|---|---|---|
| 5 minutes | 10 seconds | 30 | Every 10 sec |
| 1 hour | 1 minute | 60 | Every 1 min |
| 24 hours | 5 minutes | 288 | Every 5 min |
| Today | Single tumbling window | N/A | Every 1 min |
Per-item state structure:
{
item_id,
bucket_ring: [count_bucket_0, count_bucket_1, ...],
current_total,
head_index // circular buffer pointer
}
When the watermark advances:
- Add the newly complete bucket to
current_total - Subtract the bucket that just aged out (e.g., the 31st oldest bucket for a 5-minute window)
- Slide the ring forward
Daily window handling:
Use tumbling windows aligned to timezone-aware midnight boundaries. Emit running IN_PROGRESS snapshots every minute. When the watermark passes day_end + allowed_lateness, mark as FINALIZED. Late stragglers route to a dead-letter queue for nightly batch correction.
Top-K Ranking Algorithms
Exact two-phase approach (baseline):
Phase 1 - Local ranking: Each parallel processing task owns a disjoint subset of items through consistent hashing. Each task maintains exact counts and extracts its local top-1000. Since every item is fully aggregated in exactly one task, the true global top-K must appear in the union of local candidate sets.
Phase 2 - Global merge: A coordinator task receives P × 1000 candidates (where P = parallelism) and selects the global top-1000 using a min-heap. Complexity is O(P·K log K) per emission.
Handling count decrements: Standard min-heaps don't support efficient decrements (as buckets expire). Solutions:
- Maintain a balanced search tree or skip list indexed by
(count, item_id)forO(log N)updates andO(K)retrieval - Lazy evaluation: only recompute ranks for items whose counts changed plus previous top-K members
Approximate algorithms for memory-constrained scenarios:
Exact aggregation for 100M items × 288 buckets × multiple windows exceeds reasonable memory budgets for 24-hour windows.
Space-Saving algorithm:
- Maintains exactly
mcounters - Guarantees that any item appearing more than
N/mtimes is tracked - Overestimation error bounded by
N/mper item - Summaries are mergeable across distributed tasks
Count-Min Sketch with candidate tracking:
- Width
w = ⌈e/ε⌉and depthd = ⌈ln(1/δ)⌉for error boundεNwith probability1-δ - Sketches support addition/subtraction, enabling bucket-based windowing
- Keep one sketch per time bucket; sum active buckets for current window
- Combine with a heap tracking heavy-hitter candidates
Practical configuration:
- Use exact counting for 5-minute, 1-hour, and daily windows (manageable state)
- Apply Count-Min Sketch for 24-hour window (too many buckets × items)
- Include error bounds in API responses for approximate results
Event-Time Processing and Late Data
Watermark generation:
Use bounded-delay watermarks: watermark = max_observed_timestamp - allowed_delay. Set per-window lateness budgets based on freshness requirements:
| Window | Lateness Tolerance | Reasoning |
|---|---|---|
| 5 min | 30 sec | Favor freshness over completeness |
| 1 hour | 2 min | Balanced |
| 24 hour | 10 min | More tolerance acceptable |
| Daily | 1 hour before finalization | Then batch correction |
Configure idle-source handling to prevent stalled partitions from blocking watermark advancement.
Late event handling: Events within tolerance update the appropriate bucket retroactively and trigger re-emission. Events exceeding tolerance go to a side-output topic for offline reconciliation—a nightly batch job recomputes exact daily counts from archived S3 data and publishes corrections.
Deduplication:
Maintain a Bloom filter or compact hash table of event_id values within the lateness window (e.g., last 2 hours). This catches duplicates caused by retry logic or multi-path delivery.
State Management
Embedded state stores: Use the stream processor's native state backend (RocksDB in Flink, state stores in Kafka Streams). Organize state with hierarchical namespaces:
window_type/item_id/bucket_index → count
window_type/rankings → top_k_list
Checkpointing: Configure periodic snapshots (every 2-5 minutes) to distributed storage (S3, HDFS). Balance checkpoint frequency against recovery time and overhead.
State TTL and compaction:
- Automatically expire bucket data older than maximum window size + lateness
- Use changelog compaction for ranking snapshots (only retain latest)
- Implement background cleanup to prevent unbounded growth
Fault Tolerance
Processing guarantees: Implement exactly-once semantics using:
- Kafka transactional producer for atomic writes
- Two-phase commit between state checkpoints and output
- Idempotent writes to serving layer using versioned updates
Fallback to at-least-once if exactly-once overhead is unacceptable, and implement idempotency at the serving layer through monotonic version numbers.
Recovery behavior:
On failure, restore from last checkpoint and replay from corresponding Kafka offsets. Emit a RECOVERING status during catch-up to signal potentially stale data.
Horizontal Scaling
Elastic parallelism: Configure the stream processor with dynamic task allocation based on lag metrics. Key-based partitioning automatically redistributes when scaling.
Skew handling:
- Monitor per-task load metrics
- Dynamically apply salting to items exceeding threshold
- Consider data-aware rebalancing strategies
Coordinator bottleneck: The global top-K merge task can become a bottleneck. Mitigate by:
- Hierarchical merging (tree-structured aggregation)
- Sampling local candidates more aggressively
- Increasing merge parallelism for independent windows
Serving Layer
Storage architecture:
- Redis: In-memory caching of current top-K for all active windows; sub-millisecond reads
- DynamoDB or Cassandra: Durable storage of historical daily rankings; consistent reads for reporting
Data schema:
{
"window_id": "5min|1hour|24hour|2024-01-15",
"computation_time": 1705334400000,
"status": "CURRENT|FINAL|CORRECTED",
"version": 12345,
"rankings": [
{"item_id": "B001", "count": 1523, "error_bound": 0},
...
]
}
Query API:
GET /top-products?window=5min&k=100
GET /top-products?date=2024-01-15&k=100
Push model (optional): Implement WebSocket or Server-Sent Events for clients requiring live updates. The stream processor publishes ranking changes to a pub/sub system (Redis Pub/Sub, NATS), which broadcasting services consume.
Performance Trade-offs and Tuning
Latency vs. completeness:
- Shorter allowed lateness → faster window closure → lower completeness
- Tune per window based on use case (real-time dashboards tolerate more dropped late events than financial reports)
Accuracy vs. cost:
- Exact counting: 10-100x more memory but guaranteed precision
- Approximate methods: 95-99% accuracy with 10x less memory
- Hybrid: exact for important windows, approximate for less critical
Throughput vs. granularity:
- Smaller buckets → smoother updates but more computation
- Larger buckets → chunkier updates but reduced overhead
- Match bucket size to emission cadence
Common mistakes to avoid:
- Computing sliding windows independently (combinatorial explosion)
- Ranking before merging salted counts (produces wrong results)
- Neglecting late-data handling (silent data loss)
- Unbounded state growth (memory leaks)
- Synchronous blocking I/O in hot path (kills throughput)
This architecture scales to billions of events daily while providing sub-second freshness for short windows and strong accuracy guarantees for business-critical daily reporting.