Observability: Metrics, Logs, Traces, and SLOs, from 'It Seems Slow' to Finding the Cause
System Design series · Part 6 Reliability (5 of 5)
- Redundancy, Failover, and Disaster Recovery: From Availability Numbers to Restore Drills
- Timeouts, Retries, Backoff, and Jitter: How Retries Save a System, and How They Bring It Down
- Circuit Breakers and Bulkheads: Keep One Broken Downstream from Taking Down the Whole System
- Rate Limiting: Algorithms, Distributed Rate Limiting, and How It Differs from Load Shedding
- Observability: Metrics, Logs, Traces, and SLOs, from 'It Seems Slow' to Finding the Cause
System Design series Part 6-5 | Previous: Rate Limiting | Next: Monolith vs Microservices | Series map
Read first: Part 1-2 Latency, Throughput, and p99.
Scenario and problem
On Friday evening, customer support forwards a few complaints: “Signing up takes forever after I press the button.” “Sometimes I get an error.”
The on-call engineer opens the monitoring: average response time is 120 ms, about the same as usual; CPU is at 40%; the error rate is 0.3%. Everything looks normal.
But the complaints are real. Here is what is actually happening: for users who pay with one particular bank’s credit card, every call from the payment service to that bank takes 8 seconds. These users are only 2% of the total, and the average does not show it at all. To find it, the engineer has to answer a chain of questions:
- Is every user slow, or only one group? (metrics, split by dimension)
- Where does a slow request spend its time? (trace)
- What happened in that part? (log)
- Is this bad enough to wake someone up in the middle of the night? (SLO and alerts)
- Complaints from supportOn Friday evening, customer support forwards a few complaints: signing up takes forever after pressing the button, and sometimes there is an error.
- Monitoring looks fineThe on-call engineer opens the monitoring: average response time is 120 ms, about the same as usual; CPU is at 40%; the error rate is 0.3%. Everything looks normal.
- Only 2% wait 8 secondsHere is what is actually happening: for users who pay with one bank's credit card, every call from the payment service to that bank takes 8 seconds. These users are only 2%, and the average does not show it at all.
- Questions to answerTo find it, you have to keep asking: which group of users is slow (metrics split by dimension), where a slow request spends its time (trace), what happened in that part (log), and whether it is bad enough to wake someone up at night (SLO and alerts).
Monitoring answers “did a known problem happen”: is CPU over 80%, is the disk full. Observability answers the questions you did not think of in advance: without changing code or redeploying, it lets you infer what happened inside the system from the data the system emits.
The simplest approach and its limits
- Every server writes log files, and when something breaks you SSH in and
grep: with 12 servers you log in to 12 machines, and a request that passes through 4 services has to be pieced together from 48 files (the stateless services post); when autoscaling removes a machine, its logs disappear with it - Looking only at averages: the average hides the long tail; when 2% of users wait 8 seconds, the average rises by only 0.16 seconds (the Latency and p99 post)
- Alerting on everything: CPU over 70%, a notification for every 5xx, hundreds a day. The on-call person learns to ignore every alert, and the real incident gets buried
Core mechanism
Three signals
| Signal | What it answers | Cost profile | Example |
|---|---|---|---|
| Metrics | Overall trends and ratios: how many, how fast, how often things fail | Independent of traffic; depends on the number of dimension combinations | p99 latency of the sign-up API, requests per second, error rate |
| Logs | What happened at a point in time, with the most detail | Proportional to traffic | payment failed bank=XYZ status=504 duration=8012ms |
| Traces | Which services a request passed through, and how long each part took | Proportional to traffic; usually sampled | Sign-up → payments → bank API took 8 seconds |
The three are useful only when you can jump between them: see p99 rise in the metrics, click through to the slow traces from that period, and from one part of a trace find the logs with the same trace ID. What ties the three together is the trace ID.
Metrics: what to watch
RED for services:
- Rate: requests per second
- Errors: error rate
- Duration: the latency distribution (p50, p99, not the average)
USE for resources:
- Utilization: how much is in use, for example how many connections in the pool are taken
- Saturation: how much is waiting, for example the number of requests queued for a connection. This shows a problem earlier than utilization does
- Errors: for example, the number of timeouts while acquiring a connection
Google’s SRE book calls these the four golden signals: latency, traffic, errors, and saturation.
Cardinality explosion
Every distinct combination of label values is a separate time series. http.server.requests across 30 endpoints × 2 methods × 6 status codes is about 360 series, and each histogram multiplies that by dozens of buckets. Add a memberId label with 100,000 members and it becomes 36 million series, and the monitoring system runs out of memory.
The rule: metrics labels may only use a bounded set of values (endpoint, status code, bank code, plan tier). Unbounded values such as user IDs, order IDs, and email addresses go into logs and traces. Paths must also use the template (/v1/lectures/{id}), not the actual path (/v1/lectures/42). Spring uses the template by default; take extra care with the metrics you write yourself.
Logs: structured
2026-11-22 21:03:11 WARN Payment failed, member 1024, bank XYZ, took 8012msA person can read a log like this, but to “find every payment through bank XYZ in the past hour that took over 5 seconds”, you have to write a regular expression to parse it. A structured log outputs JSON directly, and every field can be queried and aggregated:
{"@timestamp":"2026-11-22T13:03:11.482Z","log.level":"WARN","message":"payment failed",
"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","bank":"XYZ","status":504,"duration_ms":8012}Log volume gets out of hand easily: 12 servers, 200 requests per second on each, 10 lines per request, 500 bytes per line, adds up to 12 MB per second, about 1 TB a day. Log only the essentials for normal requests; for detailed debugging information, use traces, or adjust the log level dynamically when you need it.
Traces: a timeline across services
gantt
title A slow sign-up request (trace 4bf92f…)
dateFormat x
axisFormat %L ms
section gateway
POST /v1/registrations :0, 8240
section Sign-up service
Check seats (MySQL) :20, 35
Call payments :60, 8150
Write sign-up (MySQL) :8160, 8200
section Payment service
Call bank XYZ :80, 8110
When a request enters the system, it gets a trace ID, and each step of processing it passes through creates a span that records the start time, the duration, and attributes. The trace ID travels downstream in an HTTP header: the W3C Trace Context standard defines the format of the traceparent header, and OpenTelemetry, Micrometer Tracing, and most services support it.
Asynchronous boundaries are where traces break most easily: after a request writes to Kafka or RabbitMQ, the consumer has to restore the trace context from the message headers when it processes the message, or the trace breaks in two at the queue. In Spring Kafka and Spring AMQP, observation has to be enabled on both the template and the listener.
Sampling: recording a full trace for every request costs as much as logs do. Spring Boot samples 10% by default.
- Head sampling: decide whether to record as soon as the request arrives. Simple, but 90% of the errors and slow requests are thrown away too
- Tail sampling: collect every span first, and once the whole trace is finished, decide which ones to keep: every error, everything over 1 second, and a random 5% of the rest. It works well, but the collector has to buffer the data, and the architecture is more complex (for example, tail sampling in the OpenTelemetry Collector)
SLOs and alerts
An SLI (Service Level Indicator) measures service quality, for example “the share of sign-up requests that complete successfully within 1 second”. An SLO (Objective) is the target, for example “99.9% over 30 days”.
An SLO defines an error budget: 30 days × 24 hours × 60 minutes × 0.1% = 43.2 minutes. Failures within the budget are acceptable and do not need to wake anyone up; only when the budget is being used up too fast do you need to act.
The burn rate is how fast the budget is being used. A burn rate of 1 means the budget runs out exactly at 30 days; a burn rate of 14.4 means 2% of the budget is gone in 1 hour, and at that pace the whole budget is gone in a little over two days. The multiwindow alerts that Google’s SRE Workbook recommends:
| Burn rate | Long window | Short window | Budget consumed | Response |
|---|---|---|---|---|
| 14.4 | 1 hour | 5 minutes | 2% | Page on-call immediately |
| 6 | 6 hours | 30 minutes | 5% | Page on-call immediately |
| 1 | 3 days | 6 hours | 10% | Open a ticket, handle it during working hours |
The long window makes sure the problem is serious enough; the short window makes sure the problem is still happening “now”, so the alert does not keep firing after things have recovered.
Alert on symptoms, not causes: “the burn rate of sign-up errors is above 14.4” is a symptom users can feel; “CPU above 80%” is a possible cause, but if CPU is at 80% and users are not affected, there is no need to wake anyone up at night. Cause metrics belong on dashboards, for troubleshooting, not for paging people.
Audit logs are not ordinary logs
Ordinary logs are for debugging: they can be sampled and deleted after 7 days. Audit logs answer “who did what, and when”, for example when a user insists they never canceled their sign-up, or when an admin changed a speaker’s revenue share:
- No sampling; every entry must be recorded
- Append only; no updates or deletes
- Retention follows regulations and business needs, usually much longer than for ordinary logs
- Stored separately from ordinary logs, in a place with stricter permissions
Comparing options
| Approach | Strengths | Cost |
|---|---|---|
| Separate tools (Prometheus, ELK, Jaeger) | Each is mature and can be self-hosted | Three systems; you integrate the jumping between them and the correlation yourself |
| OpenTelemetry + a single backend | Standard data format and propagation; switching backends needs no code changes | The ecosystem is still changing fast |
| Commercial SaaS | Nothing to operate; the three signals come integrated | Billed by data volume, expensive at high volume; telemetry leaves your environment |
What the talk platform chose: the application produces data with Micrometer and OpenTelemetry and sends it over OTLP to a collector; the collector handles sampling and masks sensitive data, then forwards everything to the backend. The code depends only on the standards, and the backend can be swapped.
In Java
1. Dependencies and configuration
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-opentelemetry</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>spring:
application:
name: registration-service
management:
server:
port: 9090 # management endpoints on a separate port, not exposed publicly
endpoints:
web:
exposure:
include: health,prometheus # expose only the endpoints you need
metrics:
distribution:
percentiles-histogram:
http.server.requests: true # emit a histogram so the backend can compute p99 over any time range
tracing:
sampling:
probability: 1.0 # send everything to the collector, which does tail sampling
opentelemetry:
tracing:
export:
otlp:
endpoint: http://otel-collector.internal:4318/v1/traces
logging:
structured:
format:
console: ecs # JSON format; traceId and spanId from the MDC are included automatically- A sampling rate of 1.0 assumes a collector that does tail sampling; when you send straight to the backend, keep the default 10% or adjust it to your traffic
- A p99 computed in the application (percentiles) cannot be merged across servers; histograms can be merged in the backend first and the p99 computed from that
2. Business metrics and a custom observation
@Service
public class CheckoutService {
private final PaymentGateway payments;
private final ObservationRegistry observations;
private final MeterRegistry meters;
public CheckoutService(PaymentGateway payments, ObservationRegistry observations, MeterRegistry meters) {
this.payments = payments;
this.observations = observations;
this.meters = meters;
}
public ChargeResult charge(ChargeRequest request, String idempotencyKey) {
ChargeResult result = Observation.createNotStarted("registration.payment", observations)
.lowCardinalityKeyValue("bank", request.bankCode()) // bank codes are bounded, so they can be a label
.highCardinalityKeyValue("member.id", String.valueOf(request.memberId())) // goes into the trace only, not into metrics
.observe(() -> payments.charge(request, idempotencyKey));
meters.counter("registration.payment.result", "result", result.status().name()).increment();
return result;
}
}- One
Observationproduces both metrics (a timer) and a trace (a span) lowCardinalityKeyValuebecomes a metrics label;highCardinalityKeyValueappears only in the trace. Put the member ID in the wrong one and you get a cardinality explosion- The “payment latency split by bank” dimension is exactly what finds the problem in the scenario
3. Audit logs
@Component
public class AuditLog {
// A separate logger, routed in the logging config to its own appender and storage location
private static final Logger AUDIT = LoggerFactory.getLogger("AUDIT");
public void record(String actor, String action, String target, String outcome) {
AUDIT.atInfo()
.addKeyValue("audit.actor", actor)
.addKeyValue("audit.action", action) // e.g. registration.cancel
.addKeyValue("audit.target", target) // e.g. registration:918
.addKeyValue("audit.outcome", outcome)
.setMessage("audit")
.log();
}
}The ECS format outputs the addKeyValue fields together with the trace ID from the MDC. The audit log’s appender writes to append-only storage (for example, object storage with Object Lock enabled), kept and authorized separately from ordinary logs. When regulations are stricter, write the audit record to the database in the same transaction as the business data, or send it through an Outbox, so that “doing it” and “recording it” never succeed on only one side.
4. Burn-rate alerts
# Prometheus alerting rule: 99.9% availability SLO for the sign-up API
groups:
- name: registration-slo
rules:
- alert: RegistrationErrorBudgetFastBurn
expr: |
(
sum(rate(http_server_requests_seconds_count{uri="/v1/registrations",status=~"5.."}[1h]))
/ sum(rate(http_server_requests_seconds_count{uri="/v1/registrations"}[1h]))
) > (14.4 * 0.001)
and
(
sum(rate(http_server_requests_seconds_count{uri="/v1/registrations",status=~"5.."}[5m]))
/ sum(rate(http_server_requests_seconds_count{uri="/v1/registrations"}[5m]))
) > (14.4 * 0.001)
labels:
severity: page
annotations:
summary: "Sign-up API has used 2% of its error budget within 1 hour"The configuration and code above follow the official Spring Boot 4.1, Micrometer, and Prometheus documentation, and have not been run.
Pitfalls and gotchas
- Looking only at averages: the long tail is completely hidden
- Using user IDs as metrics labels: the number of time series explodes, and the monitoring system falls over before the application does
- Computing percentiles in the application: each server’s p99 cannot be averaged into an overall p99; emit histograms instead
- Traces breaking at asynchronous boundaries: queues,
@Async, and thread pools you create yourself do not pass the context along - Head sampling throws away the errors: at 10% sampling, 90% of error traces are never kept, and those are exactly the ones you need most
- Too many alerts: alerting on causes and over-sensitive thresholds teach the on-call person to ignore alerts. Every alert that wakes someone up must correspond to a situation that needs a person to act right away
- Dashboards only engineers can read: during an incident, customer support and managers also need to know how far the impact reaches. SLOs and error budgets are a language everyone understands
- The monitoring system fails together with the system it monitors: if monitoring is deployed in the same availability zone and depends on the same database, you see nothing during the incident. Have at least one check that probes from outside
- Wrong log level: DEBUG left on in production makes log volume and cost explode, and can also write sensitive data into the logs
Security
- Secrets and personal data in logs: the
Authorizationheader, session cookies, passwords, full request bodies, national ID numbers, and credit card numbers should never appear in logs. One benefit of structured logs is that you can mask by field; the collector can filter once more. Access to the log system is usually looser than access to the database, so writing something there amounts to leaking it to more people - Log injection: newline characters in user input can forge a fake entry in a plain-text log and mislead a later investigation. Structured logs escape the whole value as one JSON string, which is safer; with plain text, filter out newlines
- Exposed management endpoints: Actuator’s
heapdumpcontains everything in memory (connection passwords, tokens, user data), andenvandconfigpropscan leak configuration. Put management endpoints on a separate port, expose only the ones you need, allow access only from the internal network, and require authentication - Trace context sent from outside: clients on the internet can send their own
traceparentandbaggageheaders. An attacker can force “sampled” to drive up your costs, or carry arbitrary data into internal services through baggage. Start a new trace at the edge, or trust only context that comes from inside, and never treat the contents of baggage as trusted data - Metrics cardinality is also an attack surface: if a label’s value comes from user input (for example, using the request path as-is as a label), an attacker who sends lots of different paths can blow up the monitoring system. Spring uses a fixed label value for paths that do not exist, and the metrics you write yourself must follow the same principle
- Audit logs must resist tampering: the first thing an attacker usually does after getting in is erase their tracks. Write audit logs somewhere the attacker cannot modify with the same permissions (another account, append-only storage); when you need a stronger guarantee, have each record include the hash of the previous one, forming a chain you can verify. All servers must keep their clocks in sync, or you cannot reconstruct the order of events afterwards
- Record who viewed the audit logs, too: audit logs themselves contain sensitive information, so querying them must be audited as well
- Use monitoring to detect attacks: the login failure rate, the share of 403s, how often rate limits trigger, and traffic from unusual countries are all early signals of a security incident (the Rate Limiting post). These metrics need alerts, and you must be able to jump from an alert to the related logs and traces
- Sending telemetry to an external service: with a SaaS monitoring service, personal data in logs and traces leaves your environment, which may bring in personal data protection laws and data residency requirements. Mask or remove it in the collector before sending
When to use it, and when not to
- Always do: structured logs with trace IDs, histograms for the RED metrics, at least one user-facing SLO with burn-rate alerts, and audit logs kept separate from ordinary logs
- Depends on scale: distributed tracing has limited value with only one or two services, and becomes almost indispensable once the number of services grows and call chains get longer; bring in tail sampling when traffic grows large enough that cost becomes a problem
- Do not: set an alert on every metric; put unbounded labels in metrics; write full request bodies into logs before you have a masking mechanism
Further reading: evaluating LLM agents with traces and replayed incidents, in the Agent series Part 5-4 Evaluation and Observability.
References
- Google, Site Reliability Engineering, Chapter 6 “Monitoring Distributed Systems”: https://sre.google/sre-book/monitoring-distributed-systems/
- Google, The Site Reliability Workbook, Chapter 5 “Alerting on SLOs”: https://sre.google/workbook/alerting-on-slos/
- W3C Recommendation — Trace Context: https://www.w3.org/TR/trace-context/
- OpenTelemetry Documentation — Sampling: https://opentelemetry.io/docs/concepts/sampling/
- Spring Boot Reference — Tracing, Metrics, Observability: https://docs.spring.io/spring-boot/reference/actuator/tracing.html
- Spring Boot Reference — Structured Logging: https://docs.spring.io/spring-boot/reference/features/logging.html
- Micrometer Documentation — Observation API: https://docs.micrometer.io/micrometer/reference/observation.html
- Brendan Gregg, “The USE Method”: https://www.brendangregg.com/usemethod.html
- OWASP — Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- Further interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments