Chapter 17 of 27 · Part 8: Cross-cutting concerns

Observability

When a request crosses many services, no single log file or dashboard shows what went wrong. This chapter makes FTGO visible: which instance is broken, where a request spent its time, and whether customers are getting what they were promised.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 16 we made FTGO's services production-ready: tokens and mutual TLS for security, externalized configuration, and a chassis that gives every service health checks and metrics. That left one problem open: with dozens of services in production, nobody can see what is happening across them.

This chapter

How does the FTGO team find out that something is wrong, where it is, and why, before customers call? By the end you can add health checks, aggregate logs, trace one request across services, collect metrics, and alert on service level objectives that measure what users feel.

Dozens of services, and nobody can see inside

Problem

Thursday lunch. Customer support reports that checkout takes ten seconds and some orders stay "pending". The CPU and memory dashboards look fine. The team opens a terminal and starts reading logs, but Order Service, Kitchen Service, Accounting and the API Gateway run as about thirty containers, each writing its own log. An hour later they still do not know which service is slow.

In the monolith, one log file and one process told most of the story. With microservices, one customer request touches several services, each with several instances, and a problem can hide in the calls between them. The team needs more than a dashboard of machine numbers.

There are two ways to think about this. Monitoring is something you do: you watch for the problems you predicted and alert on them. Observability is a property of the system: how well you can understand what is going on inside from what it sends out. An observable system lets you ask questions you never planned to ask, which is exactly what you need for a failure you did not predict.

Monitoring and observability Monitoring An activity you do Alerts on problems you predicted Weak against new failures Observability A property of the system Ask questions you never planned Built from external outputs The more observable a system, the faster you find what went wrong.
Solution · Observability patterns

Make every service emit what operators need, and collect it centrally. Six patterns cover this: a health check, aggregated logs, distributed tracing, metrics, exception tracking and an audit log.

Six observability patterns Observability see inside a running system Health GET /health Logs searchable Tracing one request Metrics numbers Exceptions dedupe + alert Audit log who did what

Be wary of the popular "three pillars" (metrics, logs, traces). It is too simple: the three overlap, and "one tool per pillar" is often a sales pitch. A more useful view is that every output is an event. From one stream of events you can build a trace, a searchable index, or aggregated numbers. Aim for a system you can understand, not a pile of tools. Each building block answers a different question:

Building blockAnswers
Health checkIs this instance able to serve requests?
Log aggregationWhat happened on every instance?
Distributed tracingWhere did one request spend its time?
Metrics aggregationWhat are the trends? When do we need capacity?
SLOs and alertingAre we doing OK, and who gets woken?
Semantic monitoringIs the business behaving as expected?
Testing in productionCan we catch problems before users do? (see chapter 15)
Cost

Each building block is code in every service plus infrastructure to collect, store and query what it emits. The cheapest one comes first: knowing whether each instance can do its job at all.

Running is not the same as healthy: health checks

Back to Thursday lunch. The first question is simple: is any instance plainly broken?

Problem

One of the four Accounting instances lost its database connections an hour ago. The process is still running, so the platform thinks it is fine and keeps sending it a quarter of all card authorizations. Each one hangs and then fails. Customers who land on that instance see a ten-second checkout and an error.

Solution · Health check API

Each service exposes an endpoint, such as GET /health, that checks the things it needs to work, such as its database and message broker, and returns 200 if it can serve requests or 503 if it cannot. The infrastructure calls it to decide whether to send traffic to the instance or restart it.

Health check API Invoker monitor, K8s, registry GET /health health handler Checks DB, broker 200 or 503 send traffic or not A service can be running yet broken. The infrastructure uses this to route traffic or restart it.

The caller can be a monitoring tool, a service registry, or Kubernetes. Kubernetes splits the idea in two: a readiness probe says whether to send traffic to a pod now, and a liveness probe says whether to restart it. The chassis from chapter 16 usually provides the endpoint.

What should the service itself do when it hits an error it cannot handle? Usually, let it crash.

What to do when a service hits an error Abort and restart (default) Let the process exit Kubernetes restarts the pod Risk: in-flight work is lost Resume operation (rare) Keep running after the error Use when aborting loses data Example: a video upload service Kubernetes also lets you define readiness and liveness probes for finer health checks.

Restarting gives a clean state, and the platform does it for you. Resume only when aborting would lose work that cannot be redone, such as a half-received video upload. Either way, code defensively: expect bad input, hidden bugs and flaky dependencies such as the message broker, and test the error paths, not only the happy path.

Cost

A health check that tests too much can mark every instance unhealthy when one shared dependency blips, and the platform then restarts all of them at once. And a health check only answers "up or down" for one instance. It cannot tell the team why checkouts are slow on the instances that are up.

Thirty log files, one question: log aggregation

The broken Accounting instance is out of rotation, but checkouts are still slow. The answer must be in the logs, somewhere.

Problem

To follow order 4711, an engineer must find which Order Service instance took it, open that container's log, then guess which Kitchen and Accounting instances it called and open their logs too. Some containers have already been restarted, and their logs are gone with them.

Solution · Log aggregation

Each service writes its log to standard output. The platform collects every instance's output and ships it to a central log server, where it is indexed. Engineers search all services at once, and set alerts on log patterns.

Log aggregation (ELK) Services log to stdout Log pipeline Logstash, Fluentd Log server Elasticsearch You Kibana: search, alert

The common open-source stack is ELK: a pipeline such as Logstash or Fluentd ships the logs, Elasticsearch stores and indexes them, and Kibana searches and alerts. A local agent on each machine does the shipping, so services need no special API. Do learn how your pipeline can lose log lines in transit, so a missing line does not mislead you.

Keep it simple and let the platform collect standard output. Where you read logs grows with the system:

Where to read logs Docker Compose one merged stream kubectl logs one pod at a time Aggregation Fluentd + Elastic Dashboards Kibana, Grafana Kubernetes has no built-in log aggregation. Use third-party tools, not your own.

Treat a log aggregation tool as a prerequisite for running microservices, not a later improvement. Logs can hold sensitive data, so limit who can read them and do not log what you do not need.

Errors deserve their own channel. With exception tracking, each service reports exceptions to a service that groups duplicates, alerts the team, and tracks each one until it is resolved. A thousand copies of the same Accounting timeout become one item, not a thousand log lines.

Cost

Central logs cost storage and need care with sensitive data. They also show many separate lines. The team can now see that Order Service, Kitchen and Accounting all logged something about order 4711, but not which call was slow, or how the lines fit together into one request.

Where did the time go? Distributed tracing

Logs say what each service did. The team needs to see one request as a whole.

Problem

Placing an order takes ten seconds. The gateway calls Order Service, which calls Consumer Service, Kitchen Service and Accounting. Every service says it is "a bit slow". Nobody can say which call takes eight of the ten seconds.

Solution · Distributed tracing

Give each external request a unique trace id at the edge and pass it on every call between services. Each service records a span, one timed step with a start and an end, tagged with the trace id. A tracing server joins the spans into one timeline per request.

Distributed tracing User API gateway Order svc Zipkin GET /orders/1 trace XYZ, span A X-B3-TraceId: XYZ child span B report spans view the timeline A trace is one request. A span is one timed step. The trace id also links all the log lines.

In this example the gateway starts trace XYZ with span A and passes the id to Order Service in a header (X-B3-TraceId, the format used by Zipkin). Order Service records child span B, and both report their spans to the tracing server. Put the trace id in every log line too: then one search in the log server returns every line for order 4711, across all services.

Distributed tracing pipeline Instrument OpenTelemetry API Local agent buffers, adds tags Collector builds the trace Viewer Jaeger or similar Sampling: keep every error, but maybe only 1 in 100 normal successes.

Pick tools that support the open OpenTelemetry API. Many libraries already emit spans through it, and you can switch the tracing back end later without changing service code. On Thursday the trace shows it at once: eight of the ten seconds are spent in the call from Order Service to Accounting.

Cost

Every service must pass the trace headers on, which is one more reason for a chassis or a mesh. Storing every span is expensive, so you sample, and a sampled trace shows single requests, not trends. Is Accounting slow for everyone, since when, and is it getting worse?

See trends, not single requests: metrics

A trace explains one request. To see the shape of the whole system, the team needs numbers over time.

Problem

The team suspects Accounting has been getting slower all week as order volume grows, but cannot prove it. Nobody knows how many orders FTGO handles per minute at peak, so nobody knows whether Accounting needs more instances before next Friday.

Solution · Application metrics

Each service records metrics, such as requests per second, latency and orders placed, and sends them to a metrics server that stores, graphs and alerts on them. A metric sample has a name, a value, a timestamp and dimensions, such as service and instance.

Application metrics OrderService placed_orders++ Metrics endpoint /actuator/prom.. Prometheus pulls metrics Grafana graphs, alerts A sample has a name, value, timestamp and dimensions. Push (CloudWatch) or pull (Prometheus).

Metrics travel in one of two ways. With push, the service sends them to the server, as with AWS CloudWatch. With pull, the server scrapes an endpoint on each instance, as Prometheus does. In FTGO's Spring Boot services that endpoint is /actuator/prometheus, and Grafana draws the graphs.

Metrics: group and resolution Group by (needs metadata) Whole system One service One instance Keep at different resolution Last 30 min: every 10 s Last month: hourly average Long history shows trends and drives capacity planning and autoscaling.

Tag every sample with where it came from, so you can look at Accounting's latency for the whole system, one service, or one instance. Keep recent data in fine detail and older data as averages: every 10 seconds for the last half hour is enough to debug, an hourly average over a month is enough to see a trend. Those trends drive capacity planning and, in chapter 22, autoscaling.

Cost

Metrics are cheap to add, so services soon emit thousands of them. Someone has to decide which numbers matter and when a number is bad enough to act on. Alert on all of them and the team drowns.

Wake people only when users feel it: SLOs and alerts

Now the team has plenty of signals. The question is which of them should page a person.

Problem

After Thursday the team adds alerts for every metric: CPU above 80 percent, any error log, any instance restart. The pager goes off forty times in one night, mostly for things that fixed themselves. On the night when checkout really breaks, the on-call engineer has stopped reading the alerts.

For a distributed system, "up" or "down" means little. One sick bee does not make a sick hive: one Kitchen instance restarting is normal, not an outage. What matters is whether users get acceptable behavior, so define what acceptable means.

Solution · Service level objectives and error budgets

A service level agreement (SLA) is the promise to users. A service level objective (SLO) is the team's own target, set tighter than the promise. A service level indicator (SLI) is what you measure to check it, such as the share of checkouts that finish within 2 seconds. The gap between the target and 100 percent is the error budget.

From promise to measurement SLA promise to users SLO team target SLI what you measure Error budget allowed misses 99.9% availability per quarter leaves about 2 h 11 min of downtime to spend.

The budget is meant to be spent. With budget left, the Order team can try a risky change. With the budget gone, reliability work comes first. That gives teams room to experiment without arguing about every release.

Alert on the SLO, the thing users feel, and not on every cause. Too many alarms overwhelm people: at the Three Mile Island nuclear accident, operators faced so many alarms at once that they could not tell which ones mattered. For every alert, ask: should this wake someone at 3 a.m.? A routine disk failure on one node can wait for working hours. A good alert passes the criteria from Steven Shorrock's work on alarm design:

What makes an alert good Alerts should be Relevant Unique Timely Prioritized and also Understandable Diagnostic Advisory (what to do) Focusing attention Criteria from Steven Shorrock's alarm design work, a useful test for any alert.
Cost

Good SLOs take work: choosing the indicators, agreeing the targets with the business, and tuning the alerts. And technical signals can all be green while the business is failing: every service answers fast, but no new restaurant can sign up because a form posts to the wrong place.

Is the business working? Semantic monitoring and audit logs

Latency and error rates describe the machinery. The last step is to watch what the machinery is for.

Problem

A release changes how Order Service reads delivery addresses. Every request returns 200 quickly, so no alert fires. But orders from one city now fail validation further down the line, and FTGO sells a fifth less that evening. Nobody notices until the finance report on Monday.

Solution · Semantic monitoring

Write down a model of how the business should behave, measure it, and alert when reality leaves the model. For example: new customers can register, and FTGO places a certain number of orders an hour at peak.

Semantic monitoring State the model sign-ups, sales per hour Measure it real users + synthetic Alert on the model not on every error Example: new customers can register, and we sell $20,000 an hour at peak.

Measure the model with real user traffic and with synthetic transactions: a fake customer that places a known test order every few minutes, as in the testing-in-production techniques of chapter 15. If the fake order stops succeeding, someone hears about it within minutes, not on Monday.

A business also needs to know who did what: which support agent refunded order 4711, which restaurant owner changed a price. An audit log records each user action. There are three ways to write one:

Three ways to write an audit log In business logic Simple but tangled, easy to miss AOP Reliable but little business context Event sourcing Automatic but harder to query

Aspect-oriented programming (AOP) wraps every method call in audit code automatically, so nothing is missed, but it only knows method names, not business meaning. With event sourcing from chapter 10, the event store already is an audit log of every change.

Cost

A business model must be written down and kept current, and synthetic transactions need test data that never reaches a real restaurant. Above all, observability only shows a failure. On Thursday the team could now see within a minute that Accounting was slow, but Order Service's threads were still stuck waiting for it, and the failure was still spreading.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Health check APIA running but broken instance keeps receiving trafficToo broad a check can take every instance out at once; says nothing about why
Log aggregationLogs scattered over many containers, lost on restartStorage, a pipeline to run, care with sensitive data
Exception trackingThe same error buried in thousands of log linesAnother service to report to and triage
Distributed tracingNo way to see where one request spent its timeEvery service must pass trace headers; sampling hides trends
Application metricsNo view of trends, load or capacityThousands of numbers; deciding which matter
SLOs, error budgets and alertsAlert floods, and no shared idea of "good enough"Indicators and targets to choose and tune
Semantic monitoring and synthetic transactionsTechnical signals are green while the business failsA business model and test data to maintain
Audit loggingNobody knows which user did whatTangled code, little context, or harder queries, depending on the method

Recap

Quick check

CPU and memory dashboards look fine, but users say checkout is slow. What should you have had in place?
Show answer

Signals about what users feel: an SLO on checkout latency, with distributed tracing across the services in the request so you can see which hop is slow. Host metrics alone rarely show a problem in the call chain.

One of FTGO's Kitchen Service instances can no longer reach its database, but its process keeps running. Restaurants report that about a third of tickets never arrive. What is missing, and what fixes it?
Show answer

A health check. With a /health endpoint that tests the database connection, Kubernetes' readiness probe stops sending work to the broken instance and its liveness probe restarts it. Aggregated logs, searchable by trace id, would show which instance was failing.

The Order team has a 99.9 percent quarterly availability SLO and has used only a few minutes of downtime this quarter. They want to try a risky change to how orders are stored. What does the error budget suggest?
Show answer

The budget, about 2 hours 11 minutes per quarter, is mostly unspent, so the team has room to take the risk. If the budget were used up, reliability work would come first.

Still open

FTGO can now see a failure within minutes: which instance, which call, how many users. But seeing a failure does not stop it. A slow Accounting service can still tie up Order Service's threads and take the whole checkout down with it.

Next: 18 Resilience and stability patterns →