Build a Real-Time Error Aggregation Service with Top-K Tracking
System DesignModel answerLast updated
Design a distributed system that ingests exception logs from microservices, groups similar errors, and maintains a live top-10 most common exceptions dashboard.
Challenge
You need to architect a monitoring service that processes error reports from a large fleet of microservices and presents a live dashboard showing the 10 most frequently occurring errors in the past hour.
Requirements
Core Functionality
- Accept exception reports at a rate of millions per second
- Group similar errors together using an intelligent matching strategy
- Track rolling counts over a 60-minute window
- Expose an endpoint to retrieve occurrence counts for any error pattern
Quality Attributes
- Must remain operational through individual component failures
- Ingestion should be fast; processing can happen asynchronously
- Scrub sensitive information like email addresses and user IDs from stack traces
- Handle sudden traffic spikes without dropping data
What to Cover
- How you'll structure both the incoming events and the aggregated statistics
- Your pipeline for receiving, normalizing, and grouping errors into categories
- The mechanism for computing top-10 rankings continuously as new data arrives
- Storage choices balancing immediate query needs against historical analysis
Hints
Hint 1
Consider how grouping reduces the number of distinct items you need to track—this affects whether you need approximation algorithms
Hint 2
Think about pre-aggregating before writing to your main processing layer to avoid overwhelming downstream components with repetitive data
Hint 3
For a rolling time window, circular buffers of time buckets let you efficiently add new data and remove expired data
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Real-Time Error Aggregation Service
Understanding the Challenge
This problem tests your ability to design high-throughput data pipelines with stateful stream processing. The key insight is that grouping dramatically reduces cardinality—millions of individual error events collapse into thousands of error patterns, making exact counting feasible where it might seem impossible.
Scale Estimation
Start by establishing concrete numbers:
- Traffic: 1M events/second baseline, 3M/second peak
- Fleet size: ~5,000 services across ~200,000 hosts
- Event payload: ~2 KB uncompressed, ~500 bytes after compression
- Input bandwidth: 2–6 GB/second
- Daily storage: ~40 TB compressed
- Distinct patterns: roughly 50k–200k unique error signatures per hour (worst case: 1M)
- Latency budget: dashboard can lag by 10–30 seconds
- Accuracy: top-10 list should be exact or near-exact; slight over-counting from retries is fine
API Design
POST /events # batch upload, compressed; async 202 response
GET /top-errors?window=1h&limit=10&filter[service]=&filter[environment]=
GET /errors/{signature}/timeseries?start=&end=&resolution=1m
GET /errors/{signature}/details # pattern info plus example occurrences
Data Models
Incoming Event (post-sanitization):
id, timestamp, received_at, service_name, environment, host, version,
error_class, sanitized_message, stack_frames[{module, function, file, line, is_app_code}],
signature_hash, metadata, sampling_weight
Error Pattern Record (relational or key-value):
signature_hash (primary key), error_class, representative_frame, template_message,
first_observed, last_observed, owning_team, resolution_status, example_event_ids[]
Time-Series Aggregates (columnar analytics store):
(signature_hash, service_name, environment, time_bucket) → event_count
Store at 1-minute resolution, with hourly and daily rollups for long-term queries.
Architecture Overview
Client SDKs → Load Balancer → Ingestion Tier → Message Queue (raw events)
→ Normalization Workers (compute signatures) → Message Queue (grouped events)
→ Stream Processor (windowed aggregation) → Top-K Consolidator → Cache Layer
→ Parallel sinks: Analytics DB (counts), Object Storage (raw), Search Index (samples)
Client SDK Behavior
- Maintain an in-memory ring buffer with background flush every 1 second or 500 events
- Never block application threads; drop excess events and report the drop count
- Batch and compress before sending
Ingestion Tier
- Stateless HTTP servers scaled horizontally
- Verify authentication, validate schemas, apply per-service rate limits
- Write to durable message queue with acknowledgment
- Queue configuration: 3-replica persistence, 72-hour retention for replay, encrypted at rest
Normalization Strategy
The grouping algorithm is critical:
- Extract the error class and the top 5 application-owned frames (skip library/framework code)
- Use module and function names only—omit line numbers which change with every deployment
- Normalize the error message:
- Replace memory addresses, UUIDs, integers, strings in quotes, email addresses, and IP addresses with tokens like
<ADDR>,<UUID>,<NUM>, etc.
- Replace memory addresses, UUIDs, integers, strings in quotes, email addresses, and IP addresses with tokens like
- Compute
signature = hash(error_class + selected_frames + normalized_message)using a fast hash like xxHash - Allow custom grouping rules per project because heuristics both over-group and under-group
Pre-Aggregation Layer
Before the main stream processor:
- Each normalization worker maintains a 1-second in-memory map:
(signature, service, minute_bucket) → count - Emit count increments rather than individual events to the grouped queue
- This reduces downstream volume by 100–1000× and prevents hot-key bottlenecks
- Send full event details to a separate path; sample the first ~100 per pattern per minute for UI drill-down
Stream Processing for Top-K
Sliding Window Mechanism
- Partition the stream by signature hash so each pattern is handled by exactly one processor
- Each processor maintains an array of 60 minute-buckets per signature, plus a running total
- When time advances past a minute boundary, subtract the oldest bucket's value and reset it
- This gives 1-minute granularity for expiration (acceptable error margin)
Two-Level Top-K Computation
- Every 10 seconds, each partition emits its local top-50 using a min-heap
- A single coordinator merges these partial results into the global top-10
- Write the result to a replicated cache (Redis) with keys like
top_errors:1h:globaland per-service keys - This approach is exact because each signature is owned by one partition—if an error is in the global top-K, it must be in that partition's local top-K
Exact vs. Approximate Algorithms
With 1M signatures at 60 buckets and 4 bytes per counter, total state is ~240 MB distributed across the cluster—affordable for exact counting.
Use approximation only when:
- Cardinality explodes due to a bug (e.g., random hashes in messages)
- You need top-K across many dimensions (service × environment × version combinations)
For approximation, use Count-Min Sketch with Space-Saving:
- Configure ε = 0.001, δ = 0.01 → ~13,500 counters per sketch
- CMS only over-estimates, so report confidence intervals
- Verify final top-10 against exact counts from the analytics store
Fault Tolerance
- Use event-time windowing with 2-minute late-arrival grace period
- Checkpoint processor state to object storage every 30 seconds
- Commit message queue offsets atomically with checkpoints for exactly-once semantics
- On failure, restore from checkpoint and replay
Storage Strategy
| Purpose | Technology | Retention |
|---|---|---|
| Live top-K and current counts | Redis (replicated) | Minutes only |
| Per-signature time series | ClickHouse or Pinot, 1-min buckets | 30 days |
| Per-signature time series | ClickHouse or Pinot, hourly rollups | 1–2 years |
| Searchable event samples | Elasticsearch or ClickHouse | 14 days |
| Complete raw events | S3/GCS Parquet by date/service | 90 days |
| Pattern metadata | PostgreSQL or Cassandra | Indefinite |
The count-retrieval API reads Redis for the current hour and the analytics store for history.
Key Trade-offs
- Grouping granularity: Too loose and distinct bugs get hidden; too tight and one bug fragments across many groups. Custom rules provide an escape hatch.
- Exact vs. sketch: Trades memory and implementation complexity for bounded approximation error.
- Freshness vs. efficiency: Merge interval and flush period are tunable based on requirements.
- Raw event sampling: Dramatically cuts storage costs while keeping counts exact (they come from pre-aggregation).
What Strong Answers Demonstrate
- Beginning with concrete scale calculations
- Understanding that message queues decouple ingestion from processing
- A thoughtful signature algorithm that balances grouping accuracy
- Recognition that pre-aggregation prevents downstream overload
- Knowing that keyed partitioning enables exact distributed top-K computation
- Clear storage tiering based on access patterns and retention needs