Design a Distributed Metrics Logging and Aggregation System
1. Introduction
In modern distributed systems, observability is not a luxury—it is a fundamental requirement. Every microservice, every container, every network call, and every user interaction generates signals that, when properly collected and analyzed, reveal the health, performance, and behavior of the entire system. A Distributed Metrics Logging and Aggregation System is the backbone of this observability stack.
Consider a company like Netflix running thousands of microservices across multiple AWS regions. When a latency spike occurs in their video streaming pipeline, engineers need to identify which service is causing the bottleneck within seconds, not minutes. Without a robust metrics infrastructure, debugging becomes a needle-in-a-haystack exercise that can cost millions in lost revenue and degraded user experience.
The Problem
At scale, metrics present unique engineering challenges:
- Volume: A single service instance can emit hundreds of metrics per second. Multiply by thousands of instances across hundreds of services, and you are looking at billions of data points per day.
- Velocity: Metrics must be ingested in real-time. A 30-second delay in detecting a CPU spike can mean the difference between proactive scaling and reactive firefighting.
- Variety: Metrics come in different shapes—counters, gauges, histograms, summaries, timers, and custom types. Each has different aggregation semantics.
- Distributed Nature: Data originates from hundreds or thousands of machines, across multiple data centers and cloud regions. Centralizing this data without losing fidelity or overwhelming the network is a serious distributed systems problem.
Business Motivation
- Incident Detection: Automated alerting based on metrics reduces mean time to detection (MTTD) from hours to seconds.
- Capacity Planning: Historical metrics enable predictive scaling, reducing both over-provisioning costs and under-provisioning risks.
- Performance Optimization: P50, P95, P99 latency metrics reveal user-perceived performance issues that averages hide.
- SLA Compliance: Metrics provide the evidence needed to demonstrate SLA adherence to customers and regulators.
- Cost Attribution: Per-team or per-service metrics enable chargeback models that drive engineering efficiency.
Real-World Examples
- Google: Borgmon and later Monarch form the backbone of Google's internal monitoring. Monarch processes over 1 billion samples per second.
- Netflix: Atlas, their open-source time-series database, ingests over 1.5 billion measurements per minute.
- Uber: M3, their distributed metrics platform, processes trillions of data points daily.
- LinkedIn: InGraphs and later their migration to Kafka-based pipelines handle billions of metrics per day.
- Amazon: CloudWatch processes trillions of metrics from millions of AWS resources.
- Datadog: Processes over 1 trillion data points per day from their SaaS monitoring platform.
Evolution of Metrics Architecture
- Monolithic Era (2000s): Centralized collection servers like Nagios. Pull-based, single points of failure.
- Scalable Time-Series (2010s): Graphite, InfluxDB, OpenTSDB. Better write throughput, but still centralized storage.
- Agent-Based (2015+): StatsD, Collectd, Telegraf. Local aggregation reduced network overhead.
- Cloud-Native (2018+): Prometheus, Thanos, Cortex. Pull-based with service discovery. Kubernetes-native.
- Observability Pipelines (2020+): OpenTelemetry, Fluent Bit, Vector. Vendor-neutral collection with streaming processing.
- eBPF-Based (2022+): Cilium, Pixie. Kernel-level metrics without code instrumentation.
2. Real Interview Context
This system design question appears frequently at top-tier technology companies because it tests a wide range of distributed systems concepts in a single problem.
Companies That Ask This Question
| Company | Variation | Level |
|---|---|---|
| Design a monitoring system for Borg | L5-L6 | |
| Meta | Design Facebook's internal metrics pipeline | E5-E6 |
| Uber | Design M3 distributed metrics platform | Staff+ |
| Netflix | Design Atlas time-series aggregation | L6-L7 |
| Amazon | Design CloudWatch metrics backend | SDE II-SDE III |
| Design metrics collection at scale | Staff+ | |
| Datadog | Design a SaaS metrics pipeline | L5-L6 |
| Cloudflare | Design edge metrics aggregation | Staff+ |
Why Interviewers Choose This Problem
- Data Modeling: Can the candidate design appropriate schemas for high-write, time-series workloads?
- Scale Handling: Does the candidate understand the challenges of ingesting billions of data points per day?
- Storage Trade-offs: Time-series databases have unique compression, retention, and query patterns.
- Stream Processing: Real-time aggregation requires understanding of windowing, tumbling windows, and state management.
- Distributed Systems Fundamentals: Consistency vs. availability, fault tolerance, and graceful degradation.
- Production Readiness: Monitoring the monitoring system (meta-observability).
Skills Being Evaluated
Technical Skills
- Time-series data modeling and storage
- Stream processing and aggregation
- High-throughput write optimization
- Data retention and compaction
- Query optimization for time-series data
- Load balancing and request routing
System Design Skills
- Gathering requirements and making trade-offs
- Back-of-the-envelope estimation
- High-level architecture design
- Component selection and justification
- Deep diving into critical components
- Discussing failure modes and recovery
Common Mistakes Candidates Make
- Skip Requirements: Jumping straight into architecture without clarifying functional and non-functional requirements.
- Ignore Scale: Designing for thousands of metrics instead of billions. Not considering write amplification.
- Over-Engineer Storage: Using a general-purpose database like PostgreSQL for time-series data without considering compression and partitioning.
- Forget Retention: Not discussing data retention policies, compaction, or tiered storage.
- Ignore Hot Keys: Popular metric names (like CPU usage for a popular service) can create hot partitions.
- No Meta-Observability: Not discussing how to monitor the monitoring system itself.
- Skip Aggregation: Not pre-aggregating data at different granularities (1-minute, 5-minute, 1-hour).
What Distinguishes Senior from Junior Answers
- Discusses tiered storage (hot/warm/cold) and data lifecycle management
- Addresses the cardinality problem explicitly
- Considers multi-tenancy and isolation
- Designs for graceful degradation when components fail
- Discusses the meta-observability problem
- Considers cost implications of different storage choices
- Talks about data consistency guarantees (at-least-once vs. exactly-once)
- Uses a single database without discussing partitioning
- Does not consider the write-to-read pipeline
- Ignores data retention and cleanup
- Does not discuss alerting or dashboarding
- Assumes infinite storage without discussing tiering
3. Functional Requirements
Before designing any system, we need to clearly define what it must do. The following functional requirements capture the essential capabilities of a distributed metrics logging and aggregation system.
Metrics Collection (FR-01 to FR-10)
- FR-01: Support multiple metric types: counters (monotonically increasing), gauges (can increase or decrease), histograms (distribution of values), summaries (precomputed quantiles), and timers.
- FR-02: Accept metrics via both push (agents send to collection endpoints) and pull (system scrapes endpoints) models.
- FR-03: Support multiple transport protocols: HTTP/HTTPS, gRPC, UDP (for StatsD-compatible agents), and Kafka for high-volume ingestion.
- FR-04: Support metric tagging/labeling with key-value pairs for dimensional querying (e.g.,
http_requests_total{method="GET", status="200", service="api-gateway"}). - FR-05: Support metric names up to 256 characters and hierarchical naming conventions.
- FR-06: Support batch ingestion of metrics, accepting up to 10,000 metric samples per request.
- FR-07: Support metric metadata (description, unit, type) registration.
- FR-08: Handle out-of-order metrics arrival with configurable grace periods.
- FR-09: Support monotonically increasing counters with automatic delta computation.
- FR-10: Support metric value validation (non-negative for counters, valid ranges for gauges).
Metrics Storage (FR-11 to FR-15)
- FR-11: Store raw metric data for a configurable retention period (default: 30 days high-resolution, 1 year downsampled).
- FR-12: Support automatic downsampling/aggregation at configurable intervals (1-minute to 1-hour rollups).
- FR-13: Support tiered storage: hot (last 24h, SSD), warm (7 days, HDD), cold (30+ days, S3).
- FR-14: Support metric deletion by name pattern, label matchers, or time range.
- FR-15: Support data export in standard formats (Prometheus, OpenMetrics, CSV, Parquet).
Metrics Querying (FR-16 to FR-23)
- FR-16: Support time-range queries with arbitrary start and end timestamps.
- FR-17: Support aggregation functions: sum, avg, min, max, count, rate, delta, percentiles (P50, P95, P99), and standard deviation.
- FR-18: Support dimensional filtering with label selectors (equals, not-equals, regex, set membership).
- FR-19: Support grouping by label dimensions.
- FR-20: Support mathematical operations on metrics: arithmetic (+, -, *, /), derivative, and integral.
- FR-21: Support metric comparison across time windows (this week vs. last week).
- FR-22: Return query results within 2 seconds for 99% of queries.
- FR-23: Support a query language for complex expressions (similar to PromQL or M3QL).
Alerting (FR-24 to FR-30)
- FR-24: Support rule-based alerting with configurable thresholds, durations, and severities.
- FR-25: Support alert notification via email, Slack, PagerDuty, webhooks, and SMS.
- FR-26: Support alert aggregation and deduplication to prevent alert storms.
- FR-27: Support alert silencing during maintenance windows.
- FR-28: Support alert escalation policies.
- FR-29: Provide alert history and audit trail.
- FR-30: Support composite alerts (alert when multiple conditions are true simultaneously).
Dashboarding (FR-31 to FR-35)
- FR-31: Web-based dashboard builder with drag-and-drop capabilities.
- FR-32: Multiple chart types: line, area, bar, heatmap, gauge, table, text annotations.
- FR-33: Dashboard templating with dynamic variables.
- FR-34: Dashboard sharing via URL with configurable access permissions.
- FR-35: Real-time dashboard updates with configurable refresh intervals.
Multi-Tenancy and Access Control (FR-36 to FR-40)
- FR-36: Multiple tenants with isolated metric namespaces.
- FR-37: Role-based access control (RBAC) with roles: admin, editor, viewer.
- FR-38: API key authentication for programmatic access.
- FR-39: SSO integration via SAML/OIDC.
- FR-40: Audit logging for all administrative actions.
4. Non-Functional Requirements
| Attribute | Requirement | Rationale |
|---|---|---|
| Scalability | 10 million metric samples per second ingestion | Enterprise customers with thousands of services |
| Availability | 99.99% uptime (52 min/year) | Must be available when production systems have incidents |
| Reliability | Zero data loss (at-least-once delivery) | Lost metrics during incidents can mask root cause |
| Latency | Write p99 < 50ms | Read p99 < 2s | Alerting depends on fresh data; dashboards must be responsive |
| Durability | Replication factor of 3 | Post-mortem analysis data must survive failures |
| Security | TLS 1.3 in transit, AES-256 at rest | Metrics may contain sensitive operational data |
| Fault Tolerance | Operational with 33% node failures | Node failures should not cause monitoring gaps |
| Maintainability | Zero-downtime rolling deployments | Maintenance cannot coincide with production incidents |
| Observability | Self-monitoring (meta-observability) | A blind monitoring system is worse than none |
| Cost | < $0.10 per million samples/month | Metrics volume grows linearly; cost must scale sub-linearly |
| Compliance | SOC 2 Type II, GDPR | Enterprise customers require regulatory compliance |
5. Requirement Prioritization
Must Have
- Metric ingestion via HTTP and gRPC
- Support for counters, gauges, histograms, and timers
- Time-range queries with aggregation functions
- Label/dimension-based filtering and grouping
- Automatic downsampling at configurable intervals
- Data retention with tiered storage
- Rule-based alerting with notification channels
- Multi-tenant isolation
- 99.99% availability for ingestion pipeline
- At-least-once delivery guarantee
Should Have
- Web-based dashboard builder
- Alert aggregation and deduplication
- PromQL-compatible query language
- Dashboard templating with variables
- API key and SSO authentication
- Rolling deployments without downtime
- Self-monitoring (meta-observability)
- Data export in standard formats
Nice to Have
- eBPF-based auto-discovery of metrics
- Machine learning-based anomaly detection
- Natural language querying
- Cost attribution dashboards
- Custom retention policies per tenant
- OpenTelemetry native support
Out of Scope
- Distributed tracing (separate system)
- Log aggregation (separate system)
- Real-time streaming analytics (use dedicated stream processor)
- Custom plugin ecosystem
- Mobile app for dashboard viewing