Building a Global Music Chart Aggregation System
System DesignModel answerLast updated
Design a scalable streaming pipeline that computes country-level song popularity rankings from millions of play events with 10-minute refresh cycles.
Problem
You're building a music analytics platform that displays popularity rankings. Design a system that processes streaming play events and generates country-specific song rankings, refreshing the results every 10 minutes.
The platform receives a continuous stream of play events containing fields like user identifier, song identifier, country code, and timestamp. Your system should maintain current rankings for each country and serve them through a read API.
Core Requirements
Functional:
- Accept a high-volume stream of play events
- Calculate the top 10 most-played songs for each country every 10 minutes
- Expose an API endpoint that returns the current rankings for any country
- Support reprocessing historical data when corrections or recalculations are needed
Non-Functional:
- Handle duplicate events gracefully without inflating counts
- Scale to millions of simultaneous users across 200+ countries
- Tolerate eventual consistency given the periodic refresh model
- Support traffic bursts during peak listening hours
Your Task
Present a complete architecture that addresses:
- End-to-end flow: How data moves from event generation to queryable rankings
- Data storage: Where and how you store both raw events and computed results
- Horizontal scaling: How the system handles load increases and avoids bottlenecks
- Correctness guarantees: How you ensure duplicate events don't corrupt rankings and how you enable safe reprocessing
Hints
Hint 1
Consider the write-to-read ratio: you'll process millions of events but serve relatively tiny result sets
Hint 2
Partitioning by country alone creates imbalanced load; think about composite keys
Hint 3
Event deduplication needs a strategy that works both in streaming and batch replay scenarios
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Global Music Chart Aggregation System
1. Scope and Scale Estimation
Begin by clarifying the ranking methodology. The simplest interpretation is a 10-minute tumbling window: every window is independent, showing the top songs for that specific interval. A rolling 24-hour chart would require summing 144 consecutive windows.
Also confirm what constitutes a valid play event—typically a minimum listen duration like 30 seconds to filter out skips.
Capacity planning:
- 50M peak concurrent users
- Average song duration ~3 minutes → ~300K events/second baseline
- Burst capacity: 1M+ events/second
- Event payload: ~200 bytes → 60 MB/s sustained, 200+ MB/s peak
- Daily volume: 20-30 billion events, roughly 4-6 TB raw data before compression
- Output data: 200 countries × 10 songs per country = ~2,000 records total, under 1 MB
The critical insight is massive write volume with minimal read data. The challenge lies entirely in the aggregation pipeline, not serving.
2. High-Level Architecture
Mobile/Web Apps → Load Balancer → Ingestion Service → Kafka → Stream Processor → Cache Layer (Redis)
↓ ↓
Archival (S3) OLAP Store (ClickHouse)
Flow:
- Ingestion service: Stateless HTTP servers validate events, enforce business rules (30s minimum), assign server-side timestamps, and publish to Kafka
- Message queue: Kafka buffers events with 7-day retention as the replay boundary
- Stream processor: Flink (or similar) performs deduplication, windowed aggregation, and ranking computation
- Serving layer: Redis holds current top-10 lists for low-latency reads
- Historical storage: S3 stores raw events partitioned by date/hour; ClickHouse stores per-window aggregates for analytics
3. Stream Processing Pipeline
Kafka Topic Configuration:
- 256 partitions (not 200 for countries—see partitioning strategy below)
- Replication factor 3 with min.insync.replicas=2
- Partition key:
hash(country + song_id)to distribute load evenly
Flink Job Stages:
Stage 1: Deduplication
- Key by
event_id(client-generated UUID that persists through retries) - Maintain stateful set of seen IDs with 90-minute TTL
- At 300K/s, 90 minutes = ~1.6B IDs ≈ 25-40 GB state spread across cluster
- Drop duplicates; pass unique events downstream
Stage 2: Windowed Counting
- 10-minute tumbling windows based on event time
- Watermarks with 2-minute allowed lateness
- Key by
(country, song_id)and count plays per window - Each unique song-country pair is processed on exactly one task
Stage 3: Local Top-K
- Each parallel task maintains a size-10 min-heap per country
- Only songs with enough plays to potentially rank emit downstream
- Dramatically reduces shuffle volume
Stage 4: Global Top-K Merge
- Re-key by
countryonly - Merge local top-10 candidates from all tasks
- This guarantees exact results: if a song ranks globally, it must rank locally on its processing task
Why This Works:
Since each (country, song_id) routes to a single task, that task sees all plays for that song. The true global top-10 cannot contain a song that wasn't in some task's local top-10. The merge handles at most parallelism × 10 candidates per country—trivial even for popular countries.
4. Data Storage Strategy
| Layer | Technology | Rationale |
|---|---|---|
| Event buffer | Kafka (7 days) | Replay window for recent corrections |
| Cold archive | S3 + Parquet, partitioned dt=YYYY-MM-DD/hour=HH | Immutable source of truth, cheap long-term storage |
| Window aggregates | ClickHouse, keyed by (country, window_start, song_id) | Historical analysis, trailing window queries |
| Live rankings | Redis with replication | Sub-millisecond reads, tiny dataset fits entirely in memory |
| Read API | CDN/API gateway with 60s TTL | Handles 100K+ QPS with minimal backend load |
The serving dataset is so small that caching at any layer is trivial. Every Redis instance holds all countries' data. Scaling reads means adding replicas or edge caching.
5. Idempotency and Replay Guarantees
Event-Level Idempotency:
- Clients generate a UUID
event_idbefore sending - Retries reuse the same ID
- Flink's stateful dedup ensures each ID is counted once
Processing-Level Idempotency:
- Flink checkpoints capture both Kafka offsets and operator state atomically
- Recovery from failure resumes from the last checkpoint without double-counting
Sink-Level Idempotency:
- All writes are keyed by
(country, window_start)and are overwrites, not increments - Redis updates use a compare-and-set pattern: only write if
new_window_end >= current_window_end - Replaying an old window doesn't regress the live rankings
Replay Procedure:
For recent failures (within 7 days):
- Reset Kafka consumer offsets to the affected time range
- Restart the streaming job from that point
- Outputs overwrite the corrupted windows
For historical corrections:
- Run a batch job (Flink batch mode or Spark) over S3 partitions for the affected date/hour ranges
- Use exact
DISTINCT event_iddeduplication (no TTL constraints in batch) - Write results to the same storage with a version tag
- Validate aggregate counts against raw event totals
- Atomically swap the serving layer to the new version
Late-arriving events beyond the watermark tolerance go to a side output for reconciliation in the next scheduled batch run.
6. Scaling and Hotspot Mitigation
Avoiding Hotspots:
- Don't partition by country alone—the US would overwhelm one partition while small countries sit idle
- Partition key
hash(country + song_id)spreads load across all partitions - Even if the US has 10× more traffic, it's distributed across 256 partitions
Handling Bursts:
- Kafka absorbs traffic spikes; Flink applies backpressure instead of dropping data
- Provision for 3-4× average throughput
- Horizontal scaling of ingestion services based on CPU/QPS metrics
Shuffle Optimization:
- Enable Flink's local pre-aggregation (mini-batches)
- Each task emits partial counts, not individual events
- Reduces network shuffle by 100-1000×
7. API Design
GET /v1/charts?country=US
Response:
{
"country": "US",
"window_start": "2024-01-15T10:00:00Z",
"window_end": "2024-01-15T10:10:00Z",
"computed_at": "2024-01-15T10:10:42Z",
"songs": [
{"rank": 1, "song_id": "s_4821", "title": "...", "plays": 52103},
{"rank": 2, "song_id": "s_9284", "title": "...", "plays": 48992},
...
]
}
Responses are cached at the CDN with 60-second TTL. Cache key includes country and window timestamp, so different windows don't collide.
8. Key Design Trade-offs
Exact vs. Approximate Counting:
- Count-Min Sketch or HyperLogLog reduces memory but introduces error
- With affordable state requirements (~40 GB for dedup), exact counting is feasible and preferred
Dedup TTL Duration:
- Longer TTL (90 min) provides stronger guarantees but increases state size
- Shorter TTL risks missing duplicates from slow networks
- Batch reconciliation jobs catch anything the streaming pipeline misses
Window Granularity:
- 10-minute windows balance freshness with computational efficiency
- For 10-second updates, simply reduce window size—the architecture is identical
- For trailing 24-hour charts, query the last 144 window aggregates from ClickHouse rather than computing a massive sliding window
9. Common Pitfalls
- Country-only partitioning creates severe hotspots
- Incremental sinks (e.g.,
UPDATE SET count = count + 1) break idempotency—use overwrites - Missing watermarks or event-time handling causes late data to be dropped silently
- No deduplication allows client retries to inflate play counts
- Forgetting the archival layer makes historical replay impossible after Kafka retention expires
10. Extensibility
For a 10-second refresh: just change the window size to 10 seconds. The architecture remains the same; you'll need more computational resources for the increased output rate.
For real-time updates: switch to a leaderboard data structure (sorted set in Redis) with incremental updates, though this sacrifices replay simplicity and increases complexity significantly.
For personalized recommendations: add a separate streaming path that joins play events with user profiles and song metadata, writing to a feature store.