Data and monitoring · Advanced · 30 min
Find a slow request across two services with distributed tracing
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 LTS · Python 3.14 · opentelemetry-sdk 1.45.2 · Jaeger 2.23.0
You will trace an order API and the stock service it calls with OpenTelemetry 1.45, follow one slow order through Jaeger 2.23 to the database query that causes it, match the request's logs by trace id and prove the fix with a second trace.
On this page
A customer says checkout is slow. Your order API's metrics agree: the 95th percentile has crept up to a few hundred milliseconds. But the order API does little work of its own. It calls a stock service, which reads a database, and the time could be going anywhere along that chain. Logs from each service show what each one did, not how the pieces fit together.
Distributed tracing joins them. Every service records its part of the request as timed spans, and passes a trace id to the next service in a traceparent HTTP header. A tracing back end collects the spans from all services and lays out one request as a waterfall, so the slow step is visible at a glance.
In this tutorial you build that chain on one machine: an order API on port 8001 that calls a stock service on port 8002, which queries a SQLite database with a slow query planted in it. Both services send spans with the OpenTelemetry Python SDK to Jaeger, an open-source tracing back end. You then work the problem the way you would in production: check the header crosses the hop, find the slow trace, read it down to the slow span, pull the matching log lines by trace id, fix the cause and compare a new trace with the old one.
The services use Python's standard-library HTTP server and add tracing by hand, so every step of propagation is in code you can read. With a framework you would use OpenTelemetry's ready-made instrumentation instead, as in tracing a Python web app with OpenTelemetry; the spans, headers and search work the same way.
Step 1 · Install Python, SQLite and the OpenTelemetry packages
Install the Python virtual environment module, the sqlite3 command-line tool and curl. Then create a project folder with its own environment and install the OpenTelemetry API, SDK and OTLP exporter at exact versions:
sudo apt update
sudo apt install -y python3-venv sqlite3 curl
mkdir -p ~/tracing-demo
cd ~/tracing-demo
python3 -m venv .venv
.venv/bin/pip install --quiet "opentelemetry-api==1.45.2" "opentelemetry-sdk==1.45.2" \
"opentelemetry-exporter-otlp-proto-http==1.45.2"The exporter sends spans as OTLP over HTTP, the OpenTelemetry protocol that Jaeger, the OpenTelemetry Collector and most commercial back ends accept. Pinning all three packages to one release matters: the API, SDK and exporter are released together and expect each other's exact versions.
Check it worked
cd ~/tracing-demo
.venv/bin/python --version
.venv/bin/pip list 2>/dev/null | grep '^opentelemetry'The first line is Python 3.14 followed by a patch number. The list includes opentelemetry-api, opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http, all at 1.45.2, plus the supporting opentelemetry-proto and opentelemetry-semantic-conventions packages.
Step 2 · Download and start Jaeger
Jaeger 2 is a single program. Started without a configuration file, it runs in all-in-one mode: it receives spans, stores them in memory and serves a web interface and a query API. That is right for learning and debugging on one machine. Memory storage loses every trace when Jaeger stops, so production setups point it at Elasticsearch, OpenSearch or Cassandra instead.
Download the release for your CPU, unpack it and check the two programs inside against the published checksums:
cd ~/tracing-demo
JAEGER_VERSION=2.23.0
ARCH="$(dpkg --print-architecture)"
BASE="https://github.com/jaegertracing/jaeger/releases/download/v${JAEGER_VERSION}"
curl -fsSLO "${BASE}/jaeger-${JAEGER_VERSION}-linux-${ARCH}.tar.gz"
curl -fsSLO "${BASE}/jaeger-${JAEGER_VERSION}-linux-${ARCH}.sha256sum.txt"
tar -xzf "jaeger-${JAEGER_VERSION}-linux-${ARCH}.tar.gz"
sha256sum -c "jaeger-${JAEGER_VERSION}-linux-${ARCH}.sha256sum.txt"The check prints two lines ending in OK, one for jaeger and one for example-hotrod, a demo application you will not use. ARCH is amd64 on most machines and arm64 on ARM servers. This copy of Jaeger gets no updates from apt; check the releases page at https://github.com/jaegertracing/jaeger/releases and repeat these commands with a newer version to upgrade.
Start Jaeger in the background, with its output in jaeger.log and its process id saved so you can stop it later:
cd ~/tracing-demo
nohup "./jaeger-${JAEGER_VERSION}-linux-${ARCH}/jaeger" > jaeger.log 2>&1 &
echo $! > jaeger.pidThe span receiver listens on localhost only. The web interface on port 16686 listens on every network interface and has no login, so on a server, block port 16686 in your firewall and reach the interface through an SSH tunnel from your laptop instead (ssh -L 16686:localhost:16686 you@your-server, then open http://localhost:16686 there).
Check it worked
Give Jaeger a few seconds to start, then ask for the web interface and list the two ports this tutorial uses:
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:16686/
ss -tln | grep -E ':(4318|16686) 'The first command prints 200. The ss lines show 127.0.0.1:4318 and *:16686. If nothing answers, tail -n 20 ~/tracing-demo/jaeger.log shows why; a port already in use is the usual cause.
Step 3 · Write the tracing setup both services share
Both services need the same three things: a tracer provider that names the service and sends spans to Jaeger, a log format that stamps every line with the current trace id and span id, and a clean shutdown. Put them in one module:
cd ~/tracing-demo
cat > tracing.py <<'PY'
import logging
import signal
import sys
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
class TraceIds(logging.Filter):
"""Copy the current trace id and span id onto every log record."""
def filter(self, record):
ctx = trace.get_current_span().get_span_context()
record.trace_id = trace.format_trace_id(ctx.trace_id) if ctx.is_valid else "-"
record.span_id = trace.format_span_id(ctx.span_id) if ctx.is_valid else "-"
return True
def setup(service_name):
resource = Resource.create({"service.name": service_name})
provider = TracerProvider(resource=resource)
# Sends to http://localhost:4318/v1/traces unless OTEL_EXPORTER_OTLP_ENDPOINT says otherwise.
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
handler = logging.StreamHandler(sys.stdout)
handler.addFilter(TraceIds())
handler.setFormatter(logging.Formatter(
f"%(asctime)s %(levelname)s service={service_name} "
"trace_id=%(trace_id)s span_id=%(span_id)s %(message)s"
))
logging.basicConfig(level=logging.INFO, handlers=[handler])
# Turn SIGTERM into a normal exit, so the SDK sends its last batch of spans.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
return trace.get_tracer(service_name)
PYThree details are worth knowing:
service.nameis how Jaeger groups spans. Every service needs its own, and it should stay the same across restarts and versions.BatchSpanProcessorqueues finished spans and sends them in batches, by default every five seconds. That keeps export off the request path, but it means a span reaches Jaeger a few seconds after the request ends.- By default Python does not run its exit handlers when
killsends SIGTERM, so the last batch would be lost. The signal handler turns SIGTERM into an ordinary exit, which lets the SDK flush.
Check it worked
cd ~/tracing-demo
.venv/bin/python -c "import tracing; print(tracing.setup('smoke-test'))"It prints a line such as <opentelemetry.sdk.trace.Tracer object at 0x7f...>. An ImportError means a package is missing from step 1.
Step 4 · Build the stock service and its database
The stock service answers GET /stock/<sku> with the quantity in stock, worked out by adding up every stock movement for that product. First create the database: one table of a million movements across 2,000 products. It has no index on sku, which is the problem planted for you to find:
cd ~/tracing-demo
cat > make_db.py <<'PY'
import sqlite3
con = sqlite3.connect("stock.db")
con.execute("DROP TABLE IF EXISTS movements")
con.execute(
"CREATE TABLE movements (id INTEGER PRIMARY KEY, sku TEXT NOT NULL, qty INTEGER NOT NULL)"
)
rows = ((f"SKU-{i % 2000:04d}", (i * 7) % 11 - 4) for i in range(1_000_000))
con.executemany("INSERT INTO movements (sku, qty) VALUES (?, ?)", rows)
con.commit()
print(con.execute("SELECT COUNT(*) FROM movements").fetchone()[0], "movements")
con.close()
PY
.venv/bin/python make_db.pyIt takes a few seconds and prints 1000000 movements.
Now the service. Look for two things in it. propagate.extract(self.headers) reads the caller's traceparent header, and passing that context to the server span makes the span part of the caller's trace instead of starting a new one. And the database call gets its own span, named and labelled the way OpenTelemetry's conventions for database spans describe, with the query text as an attribute:
cd ~/tracing-demo
cat > stock_service.py <<'PY'
import json
import logging
import sqlite3
from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from opentelemetry import propagate
from opentelemetry.trace import SpanKind
import tracing
tracer = tracing.setup("stock-service")
log = logging.getLogger("stock")
DB = Path(__file__).with_name("stock.db")
QUERY = "SELECT COALESCE(SUM(qty), 0) FROM movements WHERE sku = ?"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# Join the caller's trace, if it sent a traceparent header.
ctx = propagate.extract(self.headers)
with tracer.start_as_current_span(
"GET /stock/{sku}", context=ctx, kind=SpanKind.SERVER
) as span:
span.set_attribute("http.request.method", "GET")
span.set_attribute("url.path", self.path)
log.info("request path=%s traceparent=%s", self.path, self.headers.get("traceparent"))
if not self.path.startswith("/stock/"):
return self.reply(404, {"error": "not found"}, span)
sku = self.path.removeprefix("/stock/")
with tracer.start_as_current_span("SELECT movements", kind=SpanKind.CLIENT) as db_span:
db_span.set_attribute("db.system.name", "sqlite")
db_span.set_attribute("db.operation.name", "SELECT")
db_span.set_attribute("db.collection.name", "movements")
db_span.set_attribute("db.query.text", QUERY)
with closing(sqlite3.connect(DB)) as con:
available = con.execute(QUERY, (sku,)).fetchone()[0]
log.info("stock checked sku=%s available=%s", sku, available)
self.reply(200, {"sku": sku, "available": available}, span)
def reply(self, status, payload, span):
span.set_attribute("http.response.status_code", status)
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass # the log lines above replace the default access log
ThreadingHTTPServer(("127.0.0.1", 8002), Handler).serve_forever()
PYThe span records the query with its ? placeholder, never the values. Keep it that way in your own code: query values can hold customer data that does not belong in a tracing back end.
Start the service in the background, logging to stock.log:
cd ~/tracing-demo
nohup .venv/bin/python stock_service.py > stock.log 2>&1 &
echo $! > stock.pidCheck it worked
Ask it for one product directly and read its last log line:
cd ~/tracing-demo
curl -s http://127.0.0.1:8002/stock/SKU-0042; echo
tail -n 1 stock.logThe reply is {"sku": "SKU-0042", "available": 507}. The log line looks like 2026-11-26 10:14:51,201 INFO service=stock-service trace_id=8a3f... span_id=1c2d... stock checked sku=SKU-0042 available=507. Because curl sent no traceparent, the stock service started a new trace of its own; the line before it shows traceparent=None.
Step 5 · Build the order API and follow the traceparent header
The order API takes POST /orders with a list of products and checks each one with the stock service. Each call to the stock service runs inside a client span, and propagate.inject(headers) writes that span's identity into a traceparent header on the outgoing request. That one line is what links the two services:
cd ~/tracing-demo
cat > order_api.py <<'PY'
import json
import logging
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from opentelemetry import propagate
from opentelemetry.trace import SpanKind
import tracing
tracer = tracing.setup("order-api")
log = logging.getLogger("orders")
STOCK_URL = "http://127.0.0.1:8002/stock/"
def check_stock(sku):
with tracer.start_as_current_span("GET /stock/{sku}", kind=SpanKind.CLIENT) as span:
span.set_attribute("http.request.method", "GET")
span.set_attribute("url.full", STOCK_URL + sku)
headers = {}
propagate.inject(headers) # adds traceparent for this client span
log.info("calling stock service sku=%s", sku)
request = urllib.request.Request(STOCK_URL + sku, headers=headers)
with urllib.request.urlopen(request, timeout=5) as response:
span.set_attribute("http.response.status_code", response.status)
return json.load(response)["available"]
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
ctx = propagate.extract(self.headers)
with tracer.start_as_current_span("POST /orders", context=ctx, kind=SpanKind.SERVER) as span:
span.set_attribute("http.request.method", "POST")
span.set_attribute("url.path", self.path)
if self.path != "/orders":
return self.reply(404, {"error": "not found"}, span)
length = int(self.headers.get("Content-Length", 0))
items = json.loads(self.rfile.read(length))["items"]
span.set_attribute("order.item_count", len(items))
log.info("order received items=%s", ",".join(items))
stock = {sku: check_stock(sku) for sku in items}
accepted = all(n > 0 for n in stock.values())
log.info("order %s", "accepted" if accepted else "short of stock")
self.reply(201 if accepted else 409,
{"status": "accepted" if accepted else "short of stock", "stock": stock},
span)
def reply(self, status, payload, span):
span.set_attribute("http.response.status_code", status)
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
ThreadingHTTPServer(("127.0.0.1", 8001), Handler).serve_forever()
PY
nohup .venv/bin/python order_api.py > orders.log 2>&1 &
echo $! > orders.pidThe order API also extracts a traceparent from its own callers. In production that header would come from a gateway or a front end. Here you send one yourself, with a trace id you choose, so you can follow it. The trace id is the second field, 32 hex characters, and the final 01 means "sampled: record this trace":
cd ~/tracing-demo
curl -s -X POST http://127.0.0.1:8001/orders \
-H 'Content-Type: application/json' \
-H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' \
-d '{"items": ["SKU-0042", "SKU-0007", "SKU-1999"]}'
echoThe reply is {"status": "accepted", "stock": {"SKU-0042": 507, "SKU-0007": 503, "SKU-1999": 494}}, and it takes a noticeable fraction of a second.
Check it worked
Search both log files for the trace id you sent:
cd ~/tracing-demo
grep 4bf92f3577b34da6a3ce929d0e0e4736 orders.log stock.logEvery line from both services carries trace_id=4bf92f3577b34da6a3ce929d0e0e4736. Now compare two lines. In orders.log, each calling stock service line has a span_id. In stock.log, the matching request line shows the header the stock service received, something like traceparent=00-4bf92f3577b34da6a3ce929d0e0e4736-a1b2c3d4e5f60718-01. Its third field is that same span id: the trace id stays the same for the whole request, while the parent id changes at every hop to point at the span that made the call. If the stock service logged traceparent=None here, the header was not injected and the two services would show up in Jaeger as unrelated traces.
Step 6 · Find the slow trace in Jaeger
Send five more orders, the way real traffic would arrive, without a traceparent of your own. The order API starts a new trace for each:
cd ~/tracing-demo
for i in 1 2 3 4 5; do
curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' -X POST http://127.0.0.1:8001/orders \
-H 'Content-Type: application/json' \
-d '{"items": ["SKU-0100", "SKU-0200", "SKU-0300"]}'
doneEach line shows 201 and a time, something like 0.142s. Wait about five seconds for the last batch of spans to reach Jaeger.
In the Jaeger web interface at http://localhost:16686, open the Search page, choose order-api under Service, leave Lookback at the last hour, type 50ms into Min Duration and select Find Traces. The results list every order trace slower than 50 ms, with its duration and span count. Select one to open its waterfall.
The same search is available from Jaeger's query API, which is handy over SSH and in scripts. Version 3 of the API, under /api/v3, is the stable one; it returns traces in OTLP's JSON format. Save this small client, which uses only the standard library:
cd ~/tracing-demo
cat > jaeger_query.py <<'PY'
"""Ask Jaeger's v3 query API for slow traces, or print one trace as a waterfall."""
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
API = "http://localhost:16686/api/v3"
def fetch(path, params=None):
url = f"{API}{path}?{urllib.parse.urlencode(params or {})}"
try:
with urllib.request.urlopen(url, timeout=10) as response:
return json.load(response)["result"]["resourceSpans"]
except urllib.error.HTTPError as err:
if err.code == 404: # Jaeger answers 404 when nothing matches
return []
raise
def spans(resource_spans):
"""Yield (service name, span) for every span in an OTLP JSON response."""
for rs in resource_spans:
attrs = {a["key"]: a["value"].get("stringValue") for a in rs["resource"]["attributes"]}
for scope in rs["scopeSpans"]:
for span in scope["spans"]:
yield attrs.get("service.name"), span
def millis(span):
return (int(span["endTimeUnixNano"]) - int(span["startTimeUnixNano"])) / 1e6
def root_of(items):
ids = {span["spanId"] for _, span in items}
return next((svc, span) for svc, span in items if span.get("parentSpanId") not in ids)
def find(service, min_duration):
now = datetime.now(timezone.utc)
found = fetch("/traces", {
"query.serviceName": service,
"query.startTimeMin": (now - timedelta(minutes=15)).isoformat(),
"query.startTimeMax": now.isoformat(),
"query.durationMin": min_duration,
"query.searchDepth": 20,
})
traces = {}
for svc, span in spans(found):
traces.setdefault(span["traceId"], []).append((svc, span))
rows = []
for trace_id, items in traces.items():
svc, root = root_of(items)
rows.append((millis(root), trace_id, svc, root["name"]))
if not rows:
print("no traces found", file=sys.stderr)
for ms, trace_id, svc, name in sorted(rows, reverse=True):
print(f"{trace_id} {ms:8.1f} ms {name} [{svc}]")
def show(trace_id):
items = list(spans(fetch(f"/traces/{trace_id}")))
if not items:
sys.exit(f"trace {trace_id} not found")
ids = {span["spanId"] for _, span in items}
children = {}
for svc, span in items:
parent = span.get("parentSpanId") if span.get("parentSpanId") in ids else None
children.setdefault(parent, []).append((svc, span))
start = min(int(span["startTimeUnixNano"]) for _, span in items)
def walk(parent, depth):
for svc, span in sorted(children.get(parent, []),
key=lambda item: int(item[1]["startTimeUnixNano"])):
offset = (int(span["startTimeUnixNano"]) - start) / 1e6
print(f"{offset:8.1f} ms {millis(span):8.1f} ms {' ' * depth}{span['name']} [{svc}]")
walk(span["spanId"], depth + 1)
print(" start duration span")
walk(None, 0)
queries = {a["value"]["stringValue"] for _, span in items
for a in span.get("attributes", []) if a["key"] == "db.query.text"}
for query in sorted(queries):
print(f"db.query.text: {query}")
if __name__ == "__main__":
if len(sys.argv) == 4 and sys.argv[1] == "find":
find(sys.argv[2], sys.argv[3])
elif len(sys.argv) == 3 and sys.argv[1] == "show":
show(sys.argv[2])
else:
sys.exit("usage: jaeger_query.py find <service> <min duration, e.g. 50ms> | show <trace id>")
PYSearch for order traces slower than 50 ms in the last 15 minutes:
cd ~/tracing-demo
.venv/bin/python jaeger_query.py find order-api 50msCheck it worked
You get one line per slow order, slowest first, something like:
1f0c9a6e2b7d4c118e5a3f9b0d2c4e61 143.9 ms POST /orders [order-api]
4bf92f3577b34da6a3ce929d0e0e4736 141.2 ms POST /orders [order-api]
...Your trace from the previous step, 4bf92f3577b34da6a3ce929d0e0e4736, is in the list, along with the five new ones. The exact times depend on your machine. If the command prints no traces found, wait a few more seconds for the batch to arrive and run it again.
Step 7 · Read the waterfall down to the slow span
Take the slowest trace id from the search and print the whole trace. Save the id in a variable; the next step uses it too, so stay in this terminal:
cd ~/tracing-demo
TRACE="$(.venv/bin/python jaeger_query.py find order-api 50ms | awk 'NR == 1 {print $1}')"
.venv/bin/python jaeger_query.py show "$TRACE"The output is the same tree the web interface draws as bars, with each span's start time, measured from the beginning of the trace, and its duration. Something like:
start duration span
0.0 ms 143.9 ms POST /orders [order-api]
0.4 ms 47.6 ms GET /stock/{sku} [order-api]
1.3 ms 46.4 ms GET /stock/{sku} [stock-service]
1.5 ms 45.9 ms SELECT movements [stock-service]
48.2 ms 47.9 ms GET /stock/{sku} [order-api]
49.0 ms 46.8 ms GET /stock/{sku} [stock-service]
49.1 ms 46.5 ms SELECT movements [stock-service]
96.3 ms 47.3 ms GET /stock/{sku} [order-api]
97.1 ms 46.2 ms GET /stock/{sku} [stock-service]
97.2 ms 45.8 ms SELECT movements [stock-service]
db.query.text: SELECT COALESCE(SUM(qty), 0) FROM movements WHERE sku = ?Read it from the top, the way you would read the bars in the web interface:
- The root span is the whole request as the order API saw it.
- Its children are back to back. The second stock call starts only when the first ends, so the order API checks products one at a time. Order time grows with the number of products. That is worth fixing later, but it is not the main cost.
- The network is cheap. The gap between each client span and the stock service's server span is under a millisecond.
- One span fills its parent. Inside every stock call,
SELECT movementstakes nearly all the time. That is the slow step, and thedb.query.textattribute tells you which query it is.
Ask SQLite how it runs that query:
cd ~/tracing-demo
sqlite3 stock.db "EXPLAIN QUERY PLAN SELECT COALESCE(SUM(qty), 0) FROM movements WHERE sku = 'SKU-0100';"It prints QUERY PLAN and ` `--SCAN movements ``. `SCAN means SQLite reads all one million rows to add up the 500 that belong to one product, on every request.
Check it worked
You can point to the span that takes most of the trace (SELECT movements), say which service it belongs to (stock-service), and the query plan says SCAN movements.
Step 8 · Pull every log line for that request
The trace tells you where the time went. The logs tell you what the code was doing at the time: which product, which values, which warning. Because both services stamp each line with the trace id, one search pulls the story of one request out of both files:
cd ~/tracing-demo
grep "trace_id=$TRACE" orders.log stock.logOn a real system the logs would sit in a log store such as Loki rather than in files, and the search becomes a query on the trace_id field. Many set-ups add a link from each span in the tracing interface to that query, so you can jump from a slow span to its log lines in one click.
Check it worked
You see 11 lines: five from orders.log (order received, three calling stock service lines and order accepted) and six from stock.log (a request and a stock checked line for each product). All carry the same trace_id. Lines from other orders do not appear.
Step 9 · Fix the slow query and prove it with a new trace
The query filters on sku and reads qty. An index on both columns, in that order, lets SQLite jump to one product's rows and add them up from the index alone, without touching the table:
cd ~/tracing-demo
sqlite3 stock.db "CREATE INDEX movements_sku_qty ON movements (sku, qty);"
sqlite3 stock.db "EXPLAIN QUERY PLAN SELECT COALESCE(SUM(qty), 0) FROM movements WHERE sku = 'SKU-0100';"The plan now reads `` `--SEARCH movements USING COVERING INDEX movements_sku_qty (sku=?) ``. The stock service opens a new connection for every request, so it uses the index straight away, with no restart.
Send the same order as before with a second trace id of your own, give the spans five seconds to arrive, and print the new trace:
cd ~/tracing-demo
curl -s -X POST http://127.0.0.1:8001/orders \
-H 'Content-Type: application/json' \
-H 'traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01' \
-d '{"items": ["SKU-0042", "SKU-0007", "SKU-1999"]}'
echo
sleep 6cd ~/tracing-demo
.venv/bin/python jaeger_query.py show 0af7651916cd43dd8448eb211c80319cThe reply is the same as before, with the same stock numbers: the index changes how SQLite finds the rows, not the answer. The trace has the same shape, ten spans, but each SELECT movements now takes a fraction of a millisecond and the whole order a few milliseconds.
Check it worked
Compare the two traces for the same order, before and after the fix:
cd ~/tracing-demo
.venv/bin/python jaeger_query.py show 4bf92f3577b34da6a3ce929d0e0e4736 | sed -n 2p
.venv/bin/python jaeger_query.py show 0af7651916cd43dd8448eb211c80319c | sed -n 2pThe first line shows the root span before the fix, well over 100 ms on most machines. The second shows it after, typically under 10 ms. That pair of traces is your evidence: same request, same answer, and the time that went on the database is gone.
A trace measures time spent on your servers. When users on slow or prepaid mobile connections report a slow checkout, comparing the root span with what the phone experienced tells you quickly whether to fix the back end or reduce what you send over the network.
Next steps
When you are finished, stop the three processes and delete the demo folder. The last command removes ~/tracing-demo and everything in it, including the database and logs; Jaeger's traces go when it stops, because they were only in memory:
cd ~/tracing-demo
kill "$(cat orders.pid)" "$(cat stock.pid)" "$(cat jaeger.pid)"
cd ~
rm -rf ~/tracing-demo- Let ready-made instrumentation create the HTTP spans for you in FastAPI and httpx: trace a Python web app with OpenTelemetry.
- Put a Collector between your services and Jaeger to batch, filter and sample spans: run the OpenTelemetry Collector as a pipeline.
- Write the trace id into JSON log lines a log store can index: write structured JSON logs in Python.
- Decide when to reach for traces, metrics or logs: understand metrics, logs and traces.
Related tutorials
- Trace a Python web app with OpenTelemetryYou will add OpenTelemetry tracing to a FastAPI app that calls a second service with httpx, with named resources, your own spans, events and recorded errors, exported first to the terminal and then to a Collector, with sampling set from environment variables.
- Run the OpenTelemetry Collector as a telemetry pipelineYou will run OpenTelemetry Collector contrib 0.166 on Ubuntu as one pipeline for traces, metrics and logs that deletes email and authorisation attributes, keeps every error trace and 10% of the rest, and reports on its own health through internal metrics.
- Understand metrics, logs and traces and when to use eachYou will have followed one failing checkout request through a metric, a log line and a trace, and written a one-page plan for which signal your own system should reach for first.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials