SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Three Pillars of Observability
  • Logging Best Practices
  • Log Aggregation
  • Metrics and Instrumentation
  • Distributed Tracing
  • Alerts and Monitoring
  • Dashboards and Runbooks
  • SLOs and Error Budgets
  • Incident Management and Postmortems
  • Profiling
  • Audit Logs
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Observability

Metrics and Instrumentation

Add counters, gauges and histograms to your code, so you can measure how it behaves.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Metrics are numbers about your system, measured over time: how many requests, how many errors, how long they took. Instrumentation means adding a few lines of code that produce those numbers.

  • Metrics are cheap and small. They answer "is something wrong, and how big is it?" in a single glance.
  • There are three main kinds: a counter (only goes up), a gauge (goes up and down) and a histogram (counts how many values fell in each range).
  • Watch the tail (p95, p99), not only the average. The average hides the slow requests that real users feel.

02Concept: What is it?

A metric is a measurement with a name, a number, a timestamp and a few labels. For example: http_requests_total, with labels method=GET and status=500, was 1,284 at 10:15:00. A monitoring system collects this number again and again (every 15 or 60 seconds), so you get a line over time.

Instrumentation is how the numbers get created. Your code (or a library, or a proxy next to it) increments a counter on every request, sets a gauge for the queue size, and records every request time into a histogram. Tools such as Prometheus, StatsD, Datadog and OpenTelemetry then collect and store them.

From code to a graph
πŸ§‘β€πŸ’»Your codecounter.inc()
→↓in memory
πŸ“€Exporter/metrics or push
→↓scrape every 15 s
πŸ—ƒοΈTime-series storePrometheus, etc.
→↓
πŸ“ˆGraphs and alerts
Your app only keeps small counters in memory. A collector reads them on a schedule, and a store keeps the history.

The three basic types

βž•Counter
Only goes up (it resets to zero on restart). Requests served, errors, bytes sent. You graph its rate per second, not the raw number.
🌑️Gauge
Goes up and down. Current queue length, memory in use, active connections, temperature.
πŸ“ŠHistogram
Counts values into buckets (up to 50 ms, up to 100 ms ...). From the buckets you can estimate percentiles such as p95 and p99.
🧠Averages lie about the slow ones
If 99 requests take 100 ms and 1 request takes 10 seconds, the average is about 200 ms and looks fine. But 1 user in 100 waited 10 seconds. A percentile such as p99 shows that user. Use the visualizer below to see it.

03Real-Life Example

🍡The Dashboard of a Car
A car dashboard does not show you every part of the engine. It shows a few numbers: speed, fuel, engine temperature and a warning light. You glance at it while driving. If the temperature needle moves into the red zone, you know something is wrong and stop to look closer. Metrics are the dashboard of your software. They tell you that something is wrong and how bad, and then you open the logs or traces to find out why.
Car dashboard
Metrics
Speedometer
A gauge or a rate (requests per second)
Trip counter that only goes up
A counter (total requests)
Fuel level
A gauge (disk space left, queue size)
Engine temperature, warning light
An error rate with an alert
Lap times on a track
A histogram of request times
Mechanic fitting the sensors
Instrumentation
Too many gauges to read
Too many metrics and labels
What a dashboard tells you, and what it does not
πŸ“ˆMetricerror rate jumped
→↓something is wrong
πŸͺ΅Logswhat happened
→↓which request?
🧡Tracewhere it went slow

04Why Do We Need It?

🚨Notice problems first
A graph of the error rate shows trouble before users write to support.
πŸ”ŽFind where to look
Metrics narrow a huge system down to one service, one endpoint or one machine.
πŸ“Measure goals
An SLO such as 99.9% availability or p99 under 300 ms needs real numbers.
πŸ“ˆPlan capacity
Trends in traffic, CPU and disk tell you when to add servers before you run out.
πŸ§ͺCheck releases
Compare error rate and latency before and after a deployment (see canary releases).
πŸ’°Cheap to keep
A number per minute costs far less than storing every log line or trace.
You cannot fix, tune or promise what you do not measure. Metrics are the cheapest way to measure everything, all the time.

05Where Do We Use It?

🌐Web and API servers
Requests, errors and latency per endpoint. The first metrics most teams add.
πŸ—„οΈDatabases
Connections in use, slow queries, replication lag, cache hit ratio.
πŸ“¬Queues and workers
Queue length, age of the oldest message, jobs per second, failures.
πŸ–₯️Machines and containers
CPU, memory, disk, network. Often collected by an agent, with no code changes.
πŸ’ΌBusiness events
Orders placed, payments failed, sign-ups. A drop here can be the first sign of a hidden bug.
☸️Orchestrators and proxies
Kubernetes, load balancers and service meshes publish their own metrics for free.

06Types / Parts / How It Works

Choose the right type

TypeBehaviourExampleHow you read it
CounterOnly increaseshttp_requests_totalAs a rate: requests per second over the last 5 minutes
GaugeGoes up and downqueue_length, memory_bytesAs the current value, or its min and max
HistogramCounts per bucket, plus a sum and a countrequest_duration_secondsPercentiles estimated from the buckets (p95, p99)
SummaryPercentiles computed inside the apprequest_duration (client-side p99)Exact for one instance, but cannot be added across instances

Two checklists for what to measure

RED for services, USE for resources
RED (things users call)
🚦Raterequests per second
πŸ’₯Errorsfailed per second
⏱️Durationhow long (p50, p95, p99)
USE (things that do work)
πŸ“ŠUtilizationhow busy (%)
⏳Saturationhow much waits in line
πŸ›‘Errorsfaults on the resource
Pick the checklist that matches what you are looking at.

Google's SRE book names the four golden signals: latency, traffic, errors and saturation. RED is close to the first three, and USE adds the view from the machine side.

Labels (dimensions)

Labels split one metric into many time series, for example one per endpoint and status code. This is powerful, but each unique combination of label values is a separate series that must be stored. The number of unique combinations is called cardinality.

VisualizerAverages vs percentiles, and labels that multiply seriesRaise the share of slow requests and watch the average stay calm while p99 jumps. Then add a user_id label and see how many series that creates.

1. One sample of 1,000 request times

Average
124 ms
looks fine
p50
76 ms
the typical user
p95
172 ms
1 in 20 is slower
p99
1959 ms
1 in 100 is slower
Over 1 second
20
of 1,000 requests
A histogram metric stores counts per bucket. Each bar is cumulative: how many requests took this long or less (le = less than or equal).
le 50 ms
273
le 100 ms
644
le 200 ms
980
le 500 ms
980
le 1000 ms
980
le 2000 ms
991
le 5000 ms
1000
le +Inf
1000
The average is only 124 ms, so a dashboard of averages stays green. But p99 is 1959 ms: 20 of 1000 requests waited more than 1 second. Those are real users.

2. Labels multiply the number of time series

Add one more label to the request counter
Base series
400
4 methods x 5 status x 20 endpoints
Series stored
400
x 1
Only method, status and endpoint. A small, fixed set of series.

The request times come from a fixed formula, not a real system, and the label counts are illustrative. Real percentiles from a histogram metric are estimates, because they are read from the bucket edges.

07How to Use It / Steps / Implementation

Adding metrics to a service

  1. 1
    Start with RED
    For every service: requests per second, errors per second, and request duration as a histogram. Label by endpoint, method and status class only.
  2. 2
    Use a standard library
    Use your platform's client (Prometheus client, Micrometer, OpenTelemetry). Most web frameworks have middleware that records request metrics for you.
  3. 3
    Pick sensible histogram buckets
    Choose buckets around your goal. If your target is 300 ms, you want buckets near 100, 200, 300 and 500 ms, so the percentile estimate is accurate where it matters.
  4. 4
    Name things clearly
    Use a unit in the name (seconds, bytes), a _total suffix for counters, and the same label names everywhere.
  5. 5
    Keep labels low-cardinality
    Labels should have a small, fixed set of values: endpoint, status class, region. Never use user ids, order ids, emails or raw URLs.
  6. 6
    Add business metrics
    Count what the business cares about (orders, payments, sign-ups). A drop is often the first sign of a quiet failure.
  7. 7
    Graph rates and percentiles
    For counters, graph the per-second rate. For latency, graph p50, p95 and p99 together, not the average.
Example: a counter and a histogram (pseudo-code)
requests = Counter("http_requests_total", labels=["method", "endpoint", "status"])
latency  = Histogram("http_request_duration_seconds", buckets=[0.05, 0.1, 0.2, 0.5, 1, 2, 5])

def handle(request):
    start = now()
    response = run(request)
    requests.labels(request.method, request.route, response.status_class).inc()
    latency.observe(now() - start)
    return response
⚠️Do not put an id in a label
A label such as user_id or request_id creates a new time series for every value. A million users means a million series, and the monitoring system can run out of memory. Put ids in logs and traces instead.

08Key Terms to Know

TermMeaning in easy words
MetricA named number measured over time, such as requests per second
InstrumentationCode (or a library) that records metrics, logs or traces from your application
CounterA value that only goes up (and resets on restart). You read its rate
GaugeA value that can go up and down, such as queue length
HistogramCounts of values per bucket, used to estimate percentiles
Percentile (p95, p99)The value below which that share of requests fall. p99 = 99 of 100 were faster
Label / tagA key and value attached to a metric (for example endpoint=/pay) that splits it into series
CardinalityThe number of unique label combinations. High cardinality is expensive
Time seriesOne metric with one set of label values, stored as numbers over time
Scrape (pull) vs pushThe collector reads the app's numbers on a schedule (pull), or the app sends them out (push)
SLI / SLOA measured quality number (SLI), and the target you promise for it (SLO)

09Pros, Cons and Trade-offs

βœ… Pros
  • Small and cheap to store, even for huge systems
  • Fast to query, so good for dashboards and alerts
  • Shows trends and gives early warning
  • Works for every kind of component
  • Standard tools and libraries exist
⚠️ Cons
  • Shows that something is wrong, but rarely why
  • Aggregation hides single bad requests
  • High-cardinality labels can overload the system
  • Percentiles from histograms are estimates
  • You only see what you decided to measure

Trade-offs

ChoiceWe gainWe lose
More labelsFiner detail (per endpoint, per region)More series, more cost, slower queries
Fewer labelsA cheap and stable systemHarder to find which part is broken
Short scrape interval (5 s)Sharper graphs, faster alertsMore data and load on the app and the store
Long scrape interval (60 s)Low costShort spikes can fall between two samples
Histogram bucketsPercentiles across many instancesEstimates, and bad buckets give bad numbers
Summary (client percentiles)Accurate for one instanceCannot be combined across instances

10Common Problems and Mistakes

Common mistakes

  1. Watching the average only. The slowest 1% of users have a bad time, and the graph stays green.
  2. Averaging percentiles. The average of two p99 values is not the p99 of the combined traffic. Merge the histograms first.
  3. Labels with unbounded values. User ids, URLs with ids in them, or error messages as labels.
  4. Graphing a raw counter. It only climbs, and resets on restart. Graph its rate.
  5. Buckets that do not fit. If all requests land in one bucket, the percentile tells you nothing.
  6. No metrics for the business. The servers look healthy while no one can pay.
  7. Hundreds of unused metrics. They cost money and hide the few that matter.

Things to watch

πŸ’₯Cardinality explosion
A new label with many values can fill memory in minutes. Review labels in code review.
πŸ•³οΈGaps in data
If a scrape fails, you have a hole in the graph. Alert on missing data too.
πŸ”Counter resets
A restart sets a counter to zero. Rate functions handle this, raw subtraction does not.
⏱️Clock and window choices
A rate over 5 seconds is noisy, and over 1 hour hides spikes. Pick windows on purpose.

11Real-World Examples

πŸ”₯Prometheus
A widely used open-source system. It pulls numbers from /metrics endpoints and stores them as time series.
πŸ“ˆGrafana
A common tool for drawing dashboards from many data sources, including Prometheus.
πŸ”­OpenTelemetry
A vendor-neutral standard and set of libraries for metrics, logs and traces.
☁️Cloud monitoring
Amazon CloudWatch, Google Cloud Monitoring and Azure Monitor collect metrics from their own services automatically.
🐢Commercial platforms
Datadog, New Relic and similar services offer hosted metrics, dashboards and alerts.
⚑StatsD style
Apps send small UDP messages to an agent that rolls them up. Simple and fast to add.
πŸ“Note
Product features and default settings change over time. Check the current documentation before you pick bucket sizes or limits.
Mini case: finding a slow checkout
πŸ“ˆp99 latencyup on /checkout
→↓only this endpoint
πŸ”ŽBreak down by labelone region, one version
→↓then
🧡Open a traceslow payment call
Symptom Narrow down Cause
The dashboard says where to look. The deeper tools say why.

12Related Topics to Read Next

Three Pillars of Observability→

Metrics are one of the three views, next to logs and traces.

Distributed Tracing→

Traces explain why a slow request was slow.

Alerts and Monitoring→

Alerts are built on top of metrics.

Dashboards and Runbooks→

Where your metrics are shown and acted on.

Latency vs Throughput vs Bandwidth→

The numbers you will measure most often.

Canary Releases→

Metrics decide whether a new version is safe to roll out.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Metric: a number over time with labels. Instrumentation = code that records it.
  • βœ”Types: counter (only up), gauge (up and down), histogram (buckets).
  • βœ”Latency: look at p50, p95 and p99, not just the average.
  • βœ”What to measure: RED for services, USE for resources, plus the four golden signals.
  • βœ”Labels: few values only. Never user ids or raw URLs (cardinality).
  • βœ”Counters: graph the rate, not the raw total.
  • βœ”Percentiles: merge histogram buckets first, never average the p99 values.
  • βœ”One line: β€œMetrics tell you that something is wrong and how big it is. Logs and traces tell you why.”
← Previous
Log Aggregation
Next β†’
Distributed Tracing