Design a High-Throughput Event Aggregation System
System DesignModel answerLast updated
Build a distributed system for counting events by user, device, and region with real-time aggregation, deduplication, and time-windowed queries.
You need to architect a distributed service that tracks and aggregates application events across multiple dimensions. The system must handle events from users, devices, and geographic regions, providing both real-time and historical analytics.
Core Requirements
Your system should support:
- Writing operations: Accept event records with metadata (user_id, device_id, region, activity_type, timestamp)
- Reading operations:
- Retrieve total counts for any dimension combination
- Query counts over specific time ranges (fixed intervals or rolling windows)
- Estimate distinct entities (e.g., unique users per region)
- Offline behavior: Handle clients that buffer events locally for extended periods before syncing
Technical Constraints
- Write volume: ~10 billion events daily with 5× peak-to-average ratio
- Read freshness: Results should reflect recent writes within seconds
- Read performance: Sub-50ms p99 latency
- Duplicate handling: Retried events must not inflate counts
- Retention: Keep raw data for 30 days, aggregates longer
- Approximation: Unique counts may use probabilistic algorithms with <2% error
What to Cover
Design the complete system architecture including:
- API contracts for ingestion and retrieval
- Storage layer selection and data modeling
- Deduplication strategy across retries and network failures
- Time-based aggregation approaches (both fixed and sliding windows)
- Handling high-cardinality dimensions and traffic hotspots
- Client-side buffering and synchronization logic
- Capacity planning with concrete numbers
- Failure scenarios and recovery mechanisms
- Monitoring and operational considerations
Consider trade-offs between consistency guarantees, latency, cost, and complexity.
Hints
Hint 1
Think about how clients can reliably identify events across retries without server-assigned IDs
Hint 2
Consider separating the write path (optimized for throughput) from aggregation (optimized for query patterns)
Hint 3
Hot dimensions like popular regions will need special handling to avoid bottlenecks
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: High-Throughput Event Aggregation System
1. Requirements Clarification
Start by establishing boundaries and confirming assumptions with the interviewer.
Functional scope:
- Ingest events tagged with dimensions: user, device, region, activity type
- Support queries like: "count of login events in US-West last hour" or "unique users per activity today"
- Handle offline clients that sync after hours or days
Non-functional targets:
- Throughput: 10B events/day ≈ 115K/sec average, 600K/sec peak
- Latency: reads under 50ms p99, writes reflected within 5 seconds
- Durability: no data loss after acknowledgment
- Idempotency: duplicate submissions don't inflate counts
Scale estimation:
- Event payload ~120 bytes → 1.2 TB/day raw
- With 30-day retention and 3× replication: ~110 TB
- Aggregated counters: millions of unique dimension combinations
- HyperLogLog sketches for cardinality: 1-12KB each depending on density
2. API Design
POST /events/batch
Request: {
client_id: string,
events: [{
event_id: uuid, // client-generated, time-ordered
dimensions: {user, device, region, activity},
actor_id: string,
timestamp: iso8601,
value: int = 1
}]
}
Response: {
accepted: [event_id],
rejected: [{event_id, reason}]
}
GET /counts?key={dimension_combo}&window={start,end}&granularity={minute|hour|day}
Response: {
count: int,
series: [{timestamp, count}],
as_of: timestamp
}
GET /cardinality?key={dimension_combo}&window={start,end}
Response: {
estimate: int,
margin_of_error: float
}
Key decisions:
- Batch API reduces network overhead for offline sync
- Client-generated UUIDs (UUIDv7 preferred for time-ordering) enable idempotent retries
as_oftimestamp communicates data freshness to callers
3. Architecture Overview
[Mobile/Web Clients]
↓ (batch HTTP)
[API Gateway Layer] → rate limit, validate, auth
↓ (Kafka)
[Stream Processor] → dedup, aggregate, window
↓
[Storage Layer] → counters, sketches
↑
[Query Service] → stitch historical + real-time
Components:
- Client SDK: Buffers events in embedded storage (SQLite), batches periodically, retries with exponential backoff
- Gateway: Stateless service handling validation and producing to Kafka with idempotent producers
- Kafka: Partitioned log providing durability and replay capability
- Stream processor: Apache Flink or similar, maintains dedup state and computes windowed aggregates
- Primary store: Wide-column store (Cassandra/ScyllaDB) for counter tables
- Cache layer: Redis for hot recent data
- Batch store: S3/Parquet for long-term retention and reprocessing
4. Deep-Dive Topics
Idempotency and Deduplication
Challenge: Network failures cause retries; we need "effectively-once" semantics.
Solution approach:
- Client layer: Generate event_id before first attempt, reuse on retry
- Gateway to Kafka: Enable idempotent producer mode (handles broker retries)
- Stream processor: Maintain dedup state in RocksDB
- Key: event_id
- TTL: maximum offline window (7 days)
- Size: ~10B events × 16 bytes × 7 days = 1.1 TB partitioned across cluster
- Writes to storage: Include checkpoint offset/sequence; skip writes with non-advancing offsets
Trade-off: Dedup state adds memory cost and lookup latency. Alternative: accept small percentage of duplicates and use approximate counters (Count-Min Sketch) which tolerate overcounting. Choose based on accuracy requirements.
Time Windows
Support both fixed-interval (tumbling) and rolling (sliding) windows.
Storage strategy:
- Pre-aggregate into hierarchical buckets: minute → hour → day
- Schema:
(dimension_key, granularity, bucket_start) → {count, last_offset} - Minute buckets: keep 48 hours
- Hour buckets: keep 90 days
- Day buckets: keep 1+ years
Query execution:
- Tumbling window: Direct lookup of matching buckets
- Sliding window: Compose at read time
- Example: "last 24 hours" = current partial minute + 23 complete hours + yesterday's partial hour
- Requires ~25 row reads, feasible with prefix scan on ordered key
Late arrivals:
- In-stream: Watermarks with 10-minute allowed lateness
- Delayed sync (>10 min): Write corrections to historical buckets via upsert
- Very late (>7 days): Either reject or route to batch backfill job
Hot Key Mitigation
Popular dimensions (e.g., region=US, activity=pageview) can exceed single-partition capacity.
Techniques:
- Pre-aggregation: Gateway and stream processor batch per key before writing (reduces write volume 100-1000×)
- Dynamic sharding:
- Detect hot keys via streaming heavy-hitter detection (Count-Min Sketch)
- Split hot key into N sub-keys:
key#0,key#1, ...,key#N-1 - Write to shards, read and sum on query
- Load-based partitioning: Hash-partition Kafka by key, but for detected hot keys use random partition + two-stage aggregation
Query service caching: Redis holds recent high-traffic keys with short TTL (30-60s)
Unique Counting
Exact distinct counts require storing full sets (memory-prohibitive at scale).
Approach:
- Use HyperLogLog with precision p=14 (12KB per sketch, ~0.8% error)
- Store sketches per
(key, time_bucket) - Merge sketches for window queries (HLL union operation)
- Keep sketches only for aggregate dimensions (region, activity), not per-user
- For small cardinality (e.g., devices per user), maintain exact sets
Alternative: For very approximate needs, use Bloom filter-based approaches or sampled counting.
Offline Client Handling
Clients may be disconnected for hours or days.
Client-side:
- Buffer up to 10K events or 7 days of data
- When full, either drop oldest or pre-aggregate locally with synthetic event_id
- Include monotonic sequence number per device for gap detection
- Add jitter to sync timing to prevent thundering herd after mass outage
Server-side:
- Accept events with timestamps within reasonable bounds (< 7 days old, not future)
- Flag anomalies:
client_timestamp>>server_timestampsuggests clock skew - Rate-limit per client to prevent abuse
5. Storage Selection
| Layer | Technology | Rationale |
|---|---|---|
| Ingestion buffer | Kafka | High throughput, replay capability, industry-standard |
| Dedup state | RocksDB (in Flink) | Embedded, TTL support, scales with partitioning |
| Counter storage | ScyllaDB/Cassandra | Write-optimized, tunable consistency, wide-column model fits bucketed counters |
| Hot cache | Redis | Sub-millisecond reads, simple data model |
| Long-term | S3 + Parquet | Cost-efficient, batch analytics, immutable |
Why not native Cassandra counters? They lack idempotency—retries increment multiple times.
6. Failure Modes and Mitigations
- Gateway failure: Stateless, auto-scale, health checks route around failures
- Kafka broker down: Replication (RF=3), partition reassignment
- Stream processor failure: Checkpointing enables restart from last committed offset
- Storage unavailable: Writes buffer in Kafka (extended retention), reads fall back to stale cache
- Clock skew: Store both client and server timestamps, detect and clamp outliers
- Data corruption: Periodic reconciliation job compares stream output against batch recomputation from S3
7. Monitoring
Key metrics:
- Write path: ingestion rate, Kafka lag, dedup hit rate, processing latency
- Read path: query latency (p50/p95/p99), cache hit rate
- Accuracy: periodic reconciliation job compares real-time vs batch counts
- Business: events per user/device, top activities, regional distribution
Alerts:
- Kafka consumer lag > 5 minutes
- Query p99 latency > 100ms
- Dedup state memory approaching capacity
- Reconciliation discrepancy > 1%
8. Privacy Considerations
- Encrypt PII (user_id, device_id) at rest
- Implement data retention policies with automatic deletion
- Support user deletion requests (tombstone events, reprocess aggregates)
- Limit dimension cardinality exposed via query API to prevent re-identification
- Audit log for access to individual-level data
Common Mistakes to Avoid
- Trying to achieve true exactly-once across unreliable clients (use idempotency instead)
- Using database auto-increment IDs (breaks idempotency on retry)
- Storing every event individually for queries (pre-aggregate)
- Single-level aggregation (use hierarchical bucketing)
- Ignoring hot keys (leads to partition overload)
- Over-caching (freshness suffers) or under-caching (query load spikes)
This design balances scalability, cost, and operational complexity while meeting functional requirements. Adjust components based on specific constraints—for example, smaller scale might use managed services (AWS Kinesis, DynamoDB) instead of self-hosted infrastructure.