16 min read
Observability and tracing with OpenTelemetry
In one sentence: A trace is the path of a request, piece by piece, with how long each one took. With OpenTelemetry, the shop leaves one per request, and in Jaeger you see a whole payment, from the API to PostgreSQL, Redis, the queue and the worker, and you find it from the X-Request-Id or from a log line.
What you will learn
- Tell which question each signal answers: logs, metrics and traces.
- Explain the pieces of OpenTelemetry and why the instrumentation is loaded with --import, before the shop.
- Read a payment’s trace in Jaeger: its spans, which one is the child of which, and where the time went.
- Follow a trace from one process to another with traceparent, also through the queue and the outbox.
Before you start, read: phase-3/08-errors-and-logs.md phase-9/07-events.md 03-contract.md
The problem
Section titled “The problem”Imagine a customer writes to you: “I waited twelve seconds to sign in to the shop.” In the log you find her request: POST /v2/session, 200, "ms": 12159. The log says how long it took, not where: PostgreSQL, Redis, the password?
With a payment it’s worse: the API answers in 11 ms, and the email is sent by another process, the worker, after going through the outbox and the queue. The requestId from Phase 3 only exists in one of the two.
Phase 9 left it written down: to follow a request through several services, there are TraceThe complete journey of one request through your system, from when it arrives until it is answered, through the database, the cache and other services. It is made of spans and shows where the time went.Go to definition. Here the shop leaves one per request.
The analogy
Section titled “The analogy”The analogy
When you send a parcel, they stick a label on it with a tracking number. Every warehouse it goes through reads it and writes down when it arrived and when it left. With the number you see the whole trip, and in which warehouse it got stuck.
Where the analogy breaks down
- A parcel is in one place at a time. In a trace, one piece happens inside another (the query, inside the request), and several at once.
- The label is stuck to the parcel. In a program, the number has to be passed by hand from one process to the next; if one forgets, the trip comes out split in two.
- Scanning a parcel costs little. Writing down every request took 30% of the API’s requests per second in our test.
How it really works
Section titled “How it really works”Monitoring isn’t the same as observing
Section titled “Monitoring isn’t the same as observing”Monitoring is checking what you already know can fail: does /health answer? ObservabilityThe ability to know what is happening inside a running program by looking only at what it sends out: logs, metrics and traces. If you can ask “why did this request take 3 seconds?” without having to add new code to find out, you have observability.Go to definition is being able to answer the questions you didn’t have ready, like the twelve seconds, with what the shop already emits, without deploying new code to find out.
Three signals, three questions
Section titled “Three signals, three questions”| Signal | What it is | What it answers | In the shop |
|---|---|---|---|
| Log | One line per event | What exactly happened with this request? | pino, since Phase 3 |
| MetricA number measured over time, like requests per second or the milliseconds a response takes. It weighs very little, so it is good for seeing trends and triggering an alert, although it does not say which request failed.Go to definition | A number over time | How many arrive, how many fail, how long do they take? | Prometheus, in lesson 5 |
| Trace | The path of a request, piece by piece | Where did it go, and where did the time go? | JaegerA program that receives traces and lets you see them on a web page as a timeline: which spans a request had and how long each one took. It is open source and understands OpenTelemetry.Go to definition, in this lesson |
They’re used in a chain: the metric warns you that something is wrong, the trace says where and the log says what. Logs and traces share an id: from a log line you jump to its trace, and the other way around.
A trace is a tree of spans
Section titled “A trace is a tree of spans”This is a payment’s trace, one line per piece: its name, the service, how long it lasted and when it started, counting from the beginning. The indentation says which one is inside which:
POST /v2/webhooks/payments shop-api 11.18 ms +0 ms pg-pool.connect shop-api 0.10 ms +1 ms pg.query:SELECT shop shop-api 0.87 ms +1 ms pg-pool.connect shop-api 0.07 ms +3 ms pg.query:BEGIN shop shop-api 0.22 ms +3 ms pg.query:INSERT shop shop-api 0.72 ms +3 ms pg.query:UPDATE shop shop-api 0.73 ms +4 ms pg.query:SELECT shop shop-api 0.87 ms +5 ms pg.query:INSERT shop shop-api 1.65 ms +7 ms pg.query:COMMIT shop shop-api 0.88 ms +9 ms redis-PUBLISH shop-api 3.67 ms +10 ms add shop.confirmation-email shop-worker 2.24 ms +880 ms redis-EVALSHA shop-worker 1.63 ms +881 ms process shop shop-worker 21.74 ms +888 ms pg-pool.connect shop-worker 7.96 ms +889 ms pg.connect shop-worker 7.19 ms +890 ms pg.query:SELECT shop shop-worker 1.31 ms +897 ms complete shop shop-worker 0.95 ms +909 ms redis-EVALSHA shop-worker 0.67 ms +909 msWe took it out of Jaeger and summarized it. Each piece is a SpanOne piece of a trace: a specific operation with its start, its duration and some data, like “PostgreSQL query, 12 ms”. A span can contain others, so the trace forms a tree.Go to definition: something that happened, with its start, its duration and some data. One that happens inside another is its child; the outer one, its parent. They all share the trace id.
Jaeger draws them as bars on a timeline, one under the other: the waterfall. This one reads like this:
- The API took 11 ms, about 6 of them in PostgreSQL, most in the payment’s TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition, from
BEGINtoCOMMIT(Phase 9). - For almost 870 ms nothing happens: the event waits in the table until the relayer, which looks every second, puts it in the queue (
add). - The worker does the job in 22 ms:
process, with one query, andcomplete.
Sending the email has no span: the shop doesn’t instrument nodemailer, the library that sends it. A trace only shows what someone decided to measure.
OpenTelemetry: from the library to Jaeger
Section titled “OpenTelemetry: from the library to Jaeger”The shop doesn’t create these spans by hand: OpenTelemetryAn open standard, with libraries for many languages, for a program to send traces, metrics and logs in a common format. Any tool that understands it, such as Jaeger or Prometheus, can receive them.Go to definition does, the open standard for emitting traces, metrics and logs in a common format. It’s four pieces in a chain:
- The instrumentationswrap pg, redis, pino, node:http and fetch(Hono and BullMQ bring their own)
create spans with
- OpenTelemetry’s APIthe functions to create spans
which hands them to the
- SDKgathers them in batches
which delivers them to the
- Exportersends them over OTLP, over HTTP
to OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
- Jaegerkeeps them and shows them
Careful: this “API” isn’t the shop’s. OpenTelemetry’s API is the functions a library uses to say “start a span” and “end it.” Without an SDK they do nothing, so a library can bring them without forcing anyone to keep spans. The SDK collects them, gathers them and gives them to the exporter.
An InstrumentationThe code that makes a program emit data about itself, such as spans or metrics. It can be automatic, with a library that wraps Hono or PostgreSQL for you, or manual, with lines you write yourself.Go to definition is the code that makes a library emit spans; OTLP, OpenTelemetry’s protocol. Many teams put a collector between the exporter and the destination, a program that receives, filters and distributes; the shop sends straight to Jaeger.
The shop picks its instrumentations one by one, in src/instrumentation.ts:
// What is measured, one by one (and not the forty of auto-instrumentations-node):instrumentations: [ // The requests that leave through node:http, like the notices to the delivery company // (safe-url.ts). The ones that arrive, no: for those a Hono span already exists (app.ts), with // the route. new HttpInstrumentation({ disableIncomingRequestInstrumentation: true }), // The ones that leave with fetch (openid-client, when talking to the identity provider). new UndiciInstrumentation(), // Each query to PostgreSQL and Redis, but only inside a request or a job (requireParentSpan): // the relayer asks PostgreSQL every second, and the worker waits for jobs in Redis nonstop, // and every time it would be a loose trace of one span. new PgInstrumentation({ requireParentSpan: true }), new RedisInstrumentation({ requireParentSpan: true, dbStatementSerializer: commandWithoutData, }), // On each log line, trace_id and span_id: from a line, to its trace in Jaeger. new PinoInstrumentation({ disableLogSending: true }),],HttpInstrumentation, only for the requests that go out: for the ones that come in,@hono/otelmakes the span, with the route’s name. One request, a single server span.requireParentSpan: true: PostgreSQL and Redis, only inside a request or a job; otherwise every question from the relayer would be a loose trace. That’s why those questions don’t show up.
Before anything else, startInstrumentation looks at OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. Without it, nothing starts, and the shop works as in Phase 9.
The instrumentation is loaded before the shop
Section titled “The instrumentation is loaded before the shop”Each instrumentation changes its library at the moment someone loads it with import, the statement that brings in the code of another file or Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition. If src/server.ts had already loaded pg, it would arrive late: there would be no PostgreSQL spans, and no error to warn you.
That’s why it goes first, with Node’s --import option: node --import ./src/instrumentation.ts src/server.ts, in the package.json scripts, the Dockerfile’s CMD and the worker in compose.yaml.
With import, Node also needs a hook: code Node runs every time it loads a file, to let the instrumentation change it. import-in-the-middle puts it there, with module.registerHooks.
Jaeger, in a separate Compose file
Section titled “Jaeger, in a separate Compose file”compose.yaml gains no service: Jaeger lives in a second file, compose.observability.yaml:
# Jaeger 2, pinned by its digest: it receives the traces over OTLP (OpenTelemetry's protocol, on# 4318 over HTTP) and shows them on its web page, on 16686. It keeps them in memory: they are lost# when it stops, and for practice that is enough. 4318 is not published: only the API and the# worker use it, inside Compose's network. The web page, only on your computer (127.0.0.1).jaeger: image: jaegertracing/jaeger:2.22.0@sha256:836b967b5abcf1f7758066aa6b348619267a2f1459f72d472840570f9bd88a17 ports: - '127.0.0.1:16686:16686' # Healthy when its health check (on 13133) says yes. The image has wget. healthcheck: test: ['CMD', 'wget', '-q', '--spider', 'http://127.0.0.1:13133/status'] interval: 2s timeout: 3s retries: 15Its web page, on 16686, only on your computer; 4318, where it receives, only inside Compose’s network. It keeps the traces in memory: when it stops, they’re lost. The same file gives the address to the API and the worker:
# The API and the worker send their traces to Jaeger (src/instrumentation.ts). With# OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, the whole URL, as is. OTEL_SERVICE_NAME: who each one is in# Jaeger. They start when Jaeger is healthy, so the first traces aren't lost.api: environment: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: http://jaeger:4318/v1/traces OTEL_SERVICE_NAME: shop-api depends_on: jaeger: condition: service_healthy
worker: environment: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: http://jaeger:4318/v1/traces OTEL_SERVICE_NAME: shop-worker depends_on: jaeger: condition: service_healthyCompose joins the two files if you give them to it with -f, or if your .env says COMPOSE_FILE=compose.yaml:compose.observability.yaml, as in “Try it.”
From the X-Request-Id to the trace
Section titled “From the X-Request-Id to the trace”Each request’s span is created by @hono/otel, the first MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition in src/app.ts, so it measures everything that comes after:
// Each request's span (Phase 10, lesson 4), the first one: that way it measures everything else.// @hono/otel creates it and names it with the route's template (GET /v2/orders/:id), not the URL.// Without instrumentation (without OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, in instrumentation.ts), it// does nothing.app.use(httpInstrumentationMiddleware());// requestId gives each request an identifier and returns it in the X-Request-Id header. It goes in// the span too, as shop.request_id: with the id the frontend sees, the trace is found in Jaeger.app.use(requestId());// This middleware puts it on the span. The URL's query (url.full) is stripped elsewhere, when// each span ends: removeQuery, in instrumentation.ts.app.use(async (c, next) => { trace.getActiveSpan()?.setAttribute('shop.request_id', c.get('requestId')); await next();});It’s named after the route’s template, GET /v2/orders/:id, never with an order’s id, to group the requests to the same route. And it carries the requestId as shop.request_id: with the X-Request-Id the frontend sees, you find the trace.
Context propagation: traceparent
Section titled “Context propagation: traceparent”For another process to carry on the same trace, someone has to pass it the id: that’s Context propagationPassing a trace’s identifier from one program to the next, usually in an HTTP header or in a queue message, so the spans of several programs end up in the same trace instead of in separate ones.Go to definition. Over HTTP it goes in a W3C standard HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition, traceparent. With the ids of a log line from “Try it,” it would be this one:
traceparent: 00-3c359d0e003c75766aac2eb1c507928b-3c43199ef117620a-01The version (00), the trace id (32 hexadecimal digits), the parent span’s id (16) and some flags (01: this trace is kept). The node:http and fetch instrumentations add it to every request that goes out, like the notice to the delivery company; and if one arrives with it, @hono/otel carries on that trace.
Through the queue and the outbox
Section titled “Through the queue and the outbox”In a queue, the id travels with the message. With the telemetry option, BullMQ saves in each job the trace it was written down in, and the worker carries on with it:
// The queue's traces (Phase 10, lesson 4). With telemetry, BullMQ makes a span when writing down each// job (add shop.<type>) and another when doing it (process shop), and it saves in the job, in Redis,// the trace it was written down in: the worker reads it and carries on in it. Without this, the trace// is cut off at the queue. It goes in the queue and in the worker; without instrumentation// (instrumentation.ts), it does nothing. shop: the name of whoever makes the spans, the same as the// queue's.const telemetry = () => new BullMQOtel({ tracerName: 'shop' });It wasn’t enough. Since Phase 9’s lesson 7, the API saves the event in outbox_events (the Transactional outboxA trick for not losing announcements: the order and the announcement to send are saved in the same database transaction, in an outbox table, and another program sends them afterwards. Either both are saved or neither is.Go to definition), and the relayer enqueues it, in another process and without a request. In the first test, the payment and the email came out in two traces: the relayer didn’t know which trace each event came from.
Step 44’s solution: save the trace with the event, in a new column, context (migration 012):
-- The trace and the span the event was saved in, in the format of the W3C Trace Context standard-- (the traceparent header): 00-<trace id>-<span id>-01. NULL if there are no traces (without-- OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) and in the events from before this migration: those are-- relayed all the same, each one in a trace of its own. It allows NULL and has no DEFAULT:-- PostgreSQL only notes that the column exists, without touching the rows that are already there.ALTER TABLE outbox_events ADD COLUMN context text;When the event is saved, in the payment’s transaction, propagation.inject writes the active span’s traceparent:
// Saves a job for later, inside the transaction tx: with its COMMIT, it is saved with everything// else; with a ROLLBACK, it disappears with everything else. Nothing goes to Redis yet.// Since Phase 10 (lesson 4), with the trace it is saved in (the payment's), in context:// propagation.inject writes it as the traceparent header of the W3C standard, the same one that// travels between services over HTTP. Without traces, it writes nothing, and context stays NULL.export async function saveOutbox(tx: Transaction, job: Job): Promise<void> { const carrier: { traceparent?: string } = {}; propagation.inject(context.active(), carrier); await tx .insert(outboxEvents) .values({ type: job.type, data: job, context: carrier.traceparent ?? null });}And the relayer reads it with propagation.extract and enqueues inside that trace:
// The opposite: it does something inside the trace that saved the event. propagation.extract reads// the traceparent, and context.with makes whatever happens inside (BullMQ's span when writing down// the job) a child of the payment's span. An event with no context (without traces, or from before// migration 012) starts a new trace.function inItsTrace<T>(traceContext: string | null, run: () => Promise<T>): Promise<T> { if (!traceContext) return run(); return context.with(propagation.extract(ROOT_CONTEXT, { traceparent: traceContext }), run);}- Relayerpropagation.extract:
carries on in the payment’s trace - Workerprocess shop,
in the same trace
That’s why, in the waterfall, add hangs from the payment’s span, even though another process did it almost 870 ms later.
From the log to the trace, and back
Section titled “From the log to the trace, and back”PinoInstrumentation adds trace_id, span_id and trace_flags to every log line written inside a span. From the trace_id you get to the trace in Jaeger, and from a trace’s id, with docker compose logs api worker --no-log-prefix | grep, to its lines, the worker’s included.
The logs stay on stdoutStandard output, the channel through which a program writes its results. Unless you say otherwise, it goes to the screen; it can be sent to a file or to another program.Go to definition: Jaeger only keeps traces. To search them from a web page, a team adds another tool, like Loki, which shows them in Grafana; Grafana arrives in lesson 5.
What never goes into a span
Section titled “What never goes into a span”A trace leaves the shop for another system, with other people and another retention time. A trace must not carry what the log doesn’t: no passwords, no tokens, no personal data. While reviewing step 44, two leaks came up, already fixed:
- The URL, with its query. The return from the identity provider carries the sign-in’s
codeandstatein it. A span processor,removeQuery, takes the query off every URL before exporting it. - The key of every Redis command. The keys of the attempt limits carry the email and the IP. Now the span only says the command and what the key is for:
// A trace must not carry what the log doesn't. Each Redis span writes down the command that was// sent (db.query.text), and the instrumentation, unless told otherwise, also writes down the key,// and in many commands all the values. The limits' keys carry the email and the IP of whoever tries// to sign in (limits:session-email:ana@example.com, from rate-limits.ts and redis-store.ts), and// that must not leave the shop. So only the command and the first part of the key, up to the// colon, which says what it is for: "ZADD limits:?", "PUBLISH shop:?". A key with no colon is not// written down.export function commandWithoutData(command: string, args: Array<string | Buffer>): string { const key = args[0] === undefined ? '' : String(args[0]); const colon = key.indexOf(':'); return colon > 0 ? `${command} ${key.slice(0, colon)}:?` : command;}ZADD limits:session-email:ana@example.com becomes ZADD limits:?, and a test in the step checks that no value in the trace contains the email.
Keeping everything costs: sampling
Section titled “Keeping everything costs: sampling”The shop keeps the trace of every request, and you’ll measure it: in our test, 30% fewer requests per second. In production you do SamplingKeeping only a share of the traces, for example one in ten, because keeping all of them would cost too much on a system with a lot of traffic. You decide what to keep when the trace starts or when it ends.Go to definition: you keep a part, at random when the trace starts (one in ten, for example), or when it ends, usually in a collector, to keep all the slow ones and the ones that fail.
Try it
Section titled “Try it”The goal: find a payment’s trace from its X-Request-Id and follow it to the worker; freeze Redis and see which span waits; and measure what tracing everything costs.
The outputs are from Node 26, on Linux, on October 24, 2026, on a MacBook with Docker in a 2 GB virtual machine. Your ids, times and numbers will be different. The tables are from autocannon 8.0.0; 9.0.0 prints the same ones.
Get the step ready
Section titled “Get the step ready”Put your project on step 44, as in the introduction, and add Jaeger with one line in your .env:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/44-tracing.tar.gztar -xzf 44-tracing.tar.gzcp -R 44-tracing/. shop-api/cd shop-apinpm installprintf '\nCOMPOSE_FILE=compose.yaml:compose.observability.yaml\n' >> .envdocker compose up -d --build --waitmigrate applies migration 012, and the jaeger service shows up. Open http://localhost:16686: it’s Jaeger’s web page. If docker compose port api 3000 says 3001, use that port (it happened to us).
A payment, with its X-Request-Id
Section titled “A payment, with its X-Request-Id”Carmen, the practice customer, signs in and orders a mug. These two commands don’t print anything: the cookie stays in carmen.txt, and the order’s id, in the variable ORDER:
curl -s -o /dev/null -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/sessionORDER=$(curl -s -b carmen.txt --json '{"productId":2,"quantity":1}' localhost:3000/v2/orders | jq .id)Check that echo $ORDER gives a number. If it says null, repeat the second command without -s or | jq .id to see what the shop answers.
The fake gateway (npm run gateway) doesn’t show the headers, and you need X-Request-Id: you are the gateway. Sign the notice with your WEBHOOK_SECRET, as in the challenge of Phase 4, and send it with curl -si:
1. Pay the order
SECRET=$(grep '^WEBHOOK_SECRET=' .env | cut -d= -f2-)BODY=$(printf '{"id":"evt_%s","type":"payment.completed","orderId":%s}' "$(openssl rand -hex 8)" "$ORDER")SIGNATURE=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')curl -si -H "X-Signature: sha256=$SIGNATURE" --json "$BODY" localhost:3000/v2/webhooks/payments | tee payment.txtWhat you will see:
HTTP/1.1 200 OK…x-request-id: a5df8e97-49c9-4355-8bd3-655876ff968d…
{"received":"evt_f459a6fdefbcc708","repeated":false}cut -d= -f2- keeps what goes after the first =; openssl rand -hex 8 gives a new event id; tee writes the response on the screen and in payment.txt. We’ve removed the other headers: look at x-request-id. If you get invalid-signature, the secret isn’t the API’s.
Find its trace in Jaeger
Section titled “Find its trace in Jaeger”In Jaeger’s web page, in Search, choose the service shop-api; in Attributes, type shop.request_id= and your x-request-id, and press Find Traces. One trace comes out, shop-api: POST /v2/webhooks/payments, with two services: shop-api and shop-worker. Open it: it’s a payment like the one in the waterfall from above, with your own times. Look for the API’s short bar, the gap until add (up to a second) and process shop.
If the worker’s part is missing, wait and reload: it sends its spans in batches, every 5 seconds or so. There will also be lots of GET /health traces, Docker’s health check: that’s why you search by the id.
From the log to the trace
Section titled “From the log to the trace”2. The log line, with its trace_id
ID=$(grep -i x-request-id payment.txt | cut -d' ' -f2 | tr -d '\r')echo "X-Request-Id: $ID"docker compose logs api --no-log-prefix | grep "$ID" | jq .What you will see:
X-Request-Id: a5df8e97-49c9-4355-8bd3-655876ff968d{"level": 30,"time": 1792865583704,"pid": 1,"hostname": "0c6a1af0338e","trace_id": "3c359d0e003c75766aac2eb1c507928b","span_id": "3c43199ef117620a","trace_flags": "01","requestId": "a5df8e97-49c9-4355-8bd3-655876ff968d","method": "POST","path": "/v2/webhooks/payments","status": 200,"ms": 8,"msg": "request"}tr -d '\r' removes the header’s carriage return, as in lesson 3. The usual line, with three new fields: trace_id, span_id and trace_flags.
Paste your trace_id in the Lookup by Trace ID box, at the top of Jaeger: it opens the payment’s trace. Ours, with 21 spans: shop-api (13) and shop-worker (8). Two more than the waterfall above: it was the first payment of a freshly started shop, and the API opened its connection to Redis then (two redis-connect spans).
Freeze Redis and sign in
Section titled “Freeze Redis and sign in”Now, the twelve seconds. Freeze the queue’s Redis, the one of the attempt limits, as in Phase 9:
3. Freeze Redis
docker compose pause redisWhat you will see:
Container shop-redis-1 PausedRedis doesn’t answer, but its connections stay open: whoever asks it gets no error, only silence.
Carmen tries to sign in, and curl is left waiting:
4. Sign in
curl -si -o session.txt -w 'curl: HTTP %{http_code} in %{time_total} s\n' --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/sessionWhat you will see:
curl: HTTP 200 in 12.164965 s-o saves the response in session.txt, and -w writes the code and the time at the end. While it waits, in another terminal, in the project’s folder, count about twelve seconds and unfreeze it: docker compose unpause redis (it says Container shop-redis-1 Unpaused). Then curl finishes: 200 in 12.2 seconds. Nothing has failed; it has only taken long.
5. Its id
grep -i -e '^HTTP/' -e '^x-request-id' session.txtWhat you will see:
HTTP/1.1 200 OKx-request-id: 06774669-d9e7-4b15-9210-d913efe04a3aLook it up in Jaeger as before, with shop.request_id=.
Ours, summarized like the payment’s:
POST /v2/session shop-api 12159.62 ms +0 ms redis-ZREMRANGEBYSCORE shop-api 12134.92 ms +0 ms redis-ZRANGE shop-api 12134.90 ms +0 ms redis-ZREMRANGEBYSCORE shop-api 0.88 ms +12135 ms redis-ZRANGE shop-api 0.80 ms +12135 ms pg-pool.connect shop-api 0.08 ms +12136 ms pg.query:SELECT shop shop-api 1.35 ms +12136 ms pg-pool.connect shop-api 0.08 ms +12157 ms pg.query:INSERT shop shop-api 1.25 ms +12157 ms- The first two Redis commands, 12,135 ms: the limit by email, waiting for a frozen Redis. Almost the whole request.
- The next two, the limit by IP, with Redis back: under a millisecond.
- Then, PostgreSQL: finding Carmen and, after about 20 ms with no spans (probably checking her password with argon2, which isn’t instrumented), saving the session.
We looked: no span had an error status. Redis didn’t fail, it took long. The log said how long; the trace says where. And it shows a flaw in step 44: the shop waits for Redis with no limit; in lesson 6, each limit will wait 200 ms at most.
What tracing everything costs
Section titled “What tracing everything costs”Phase 9’s Load testAn experiment in which a program sends many requests in a row to your server to measure how many it can take and how long it takes to answer. It tells you where the limit is before your users find it.Go to definition, with every trace on its way to Jaeger:
6. With traces
npm run load -- -c 10 -d 10 http://localhost:3000/v2/productsWhat you will see:
…┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬──────────┬─────────┐│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┤│ Req/Sec │ 3,397 │ 3,397 │ 7,231 │ 7,871 │ 6,807.9 │ 1,262.04 │ 3,397 │├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┤│ Bytes/Sec │ 3.17 MB │ 3.17 MB │ 6.75 MB │ 7.35 MB │ 6.36 MB │ 1.18 MB │ 3.17 MB │└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴──────────┴─────────┘
Req/Bytes counts sampled once per second.# of samples: 10
68k requests in 10.01s, 63.6 MB readWe’ve removed the beginning and the latency table. Req/Sec, Avg: 6,807.9. Two other runs of ours, from a container inside Compose’s network instead of through the published port, gave 7,035.9 and 7,712.6.
Now, without Jaeger’s URL. -f compose.yaml overrides your COMPOSE_FILE: the API is recreated without OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, and the SDK doesn’t start:
docker compose -f compose.yaml up -d apiCompose warns that shop-jaeger-1 is an orphan container: that’s expected. Recreating the API can change its port (ours went from 3001 to 3000): check docker compose port api 3000 again.
7. Without traces
npm run load -- -c 10 -d 10 http://localhost:3000/v2/productsWhat you will see:
…┌───────────┬─────────┬─────────┬─────────┬─────────┬─────────┬──────────┬─────────┐│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┤│ Req/Sec │ 6,551 │ 6,551 │ 9,367 │ 11,391 │ 9,770.6 │ 1,433.27 │ 6,549 │├───────────┼─────────┼─────────┼─────────┼─────────┼─────────┼──────────┼─────────┤│ Bytes/Sec │ 6.12 MB │ 6.12 MB │ 8.75 MB │ 10.6 MB │ 9.13 MB │ 1.34 MB │ 6.12 MB │└───────────┴─────────┴─────────┴─────────┴─────────┴─────────┴──────────┴─────────┘
Req/Bytes counts sampled once per second.# of samples: 10
98k requests in 10.02s, 91.3 MB read9,770.6, and in the two runs inside Compose’s network, 10,268.6 and 10,901.46. On average, about 7,190 with traces and about 10,310 without: 30% less.
The two ways of measuring gave the same: on our MacBook, tracing every request cost 30% of the requests per second, more than validating the contract in lesson 3. We didn’t measure which part weighs most: creating the spans, the instrumentations or sending them. Measure it on your machine.
Jaeger keeps every trace in memory: in our run with traces, it went from 65 to 304 MB. If your Docker has little memory and Jaeger stops, docker compose up -d --wait starts it again, empty.
When you finish, docker compose up -d --wait api gives the API its URL back. And delete carmen.txt, session.txt and payment.txt: they carry Carmen’s session, and they don’t go into Git.
On your server
Section titled “On your server”Your server’s .env doesn’t have OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: nothing starts there, and the timer from Phase 8 deploys the step as always, with migration 012. If one day you have somewhere to send the traces, .env.production.example says where their URL goes; measure what it costs first.
You have already seen it
Section titled “You have already seen it”- The “Waterfall” column of the Network tab in DevToolsThe developer tools that come with browsers such as Chrome or Firefox, opened with F12. Their Network tab shows every request the page makes, with its response and headers; the Console, the page’s errors; and Application (Storage, in Firefox), what the site stores in your browser, such as cookies.Go to definition: every request of the page, a bar in time. Hovering over it you see where the time went: DNS, connecting, waiting for the server, downloading.
- Sentry, if you use it on the frontend: it also draws traces, and joins them with the backend’s with its
sentry-traceheader.
Common mistakes
Section titled “Common mistakes”- Loading the instrumentation late, with an
importinserver.tsafter others, instead of--import. It starts with no errors, and without the spans of the libraries already loaded. - Putting in a span what you wouldn’t put in a log: a URL’s query, a key with an email, a request’s body.
- Breaking the chain. A queue without
telemetryor an outbox without the saved trace split the trip into two traces. - Believing tracing is free. Here it cost 30%: in production, sampling.
Summary
Section titled “Summary”- Observability answers new questions with what the system emits: logs (what happened), metrics (how much) and traces (where the time went).
- A trace is a tree of spans with the same id; in the waterfall, the indentation says which one is inside which.
- OpenTelemetry: instrumentations, API, SDK and exporter. It’s loaded with
--import, before the shop, and withoutOTEL_EXPORTER_OTLP_TRACES_ENDPOINTit exports nothing. - The context travels in the
traceparentheader, in BullMQ’s jobs and, in the shop, saved with each outbox event: a payment is a single trace. - A trace doesn’t carry what the log doesn’t. Tracing everything cost 30%: in production, sampling.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Traces, from OpenTelemetry: traces, spans and context.
- Trace Context, from the W3C: the standard for the
traceparentheader. - Sampling, from OpenTelemetry: the ways to sample.
- Jaeger: its documentation, with the search and the waterfall.
- OpenTelemetry for JavaScript: Node’s SDK and its instrumentations.