A user says a page has started lagging: how do you debug it end to end?
Narrow it down before you open a profiler: who, which page, since when. Then measure one layer at a time (browser, network, server, database, dependencies) until one of them owns the time. Five server-side causes measured with OpenTelemetry traces, and the signature each leaves.
The verdict, which the five cases below will earn: don’t start by guessing a cause. First pin down three things:
- who is affected: one user, one customer, or everyone;
- which page or action;
- since when, and what changed then.
Then follow one slow request through each layer (browser, network, server, database, other services) until one layer owns most of the time. Fix that, and confirm with the same measurement that found it. Most backend causes leave a recognisable shape in a trace: one long query, dozens of short ones, a long wait for a database connection, a long call to another service. Learning those shapes is most of the skill.
It always starts the same way: a message that says “the page has started lagging”, and nothing else. This kind of debugging is a pleasure to do well: a vague complaint, a handful of clues, and a method that narrows the suspects one layer at a time until the culprit has nowhere left to stand.
The server-side numbers below come from latency-debugging-lab. It’s a small multi-tenant API traced with OpenTelemetry, made slow in five ways, and measured before and after each fix. make demo reruns everything, and Jaeger shows the traces at localhost:16686.
Case file
The case “The page has started lagging”, and nothing else Suspects Browser, network, server, database, other services Culprit Whichever layer owns most of the time, each with its own trace shape The fix Narrow who, which and since when, then measure one layer at a time Evidence latency-debugging-lab: OpenTelemetry traces, five causes, make demo
Step 1: secure the scene before you touch anything #
The complaint tells you almost nothing yet, and that’s fine; the first few questions do a remarkable amount of work. These narrow it down fastest:
| Question | If the answer is… | Suspect first |
|---|---|---|
| One user, or many? | One user | Their device, network, browser extensions, or their data (a huge account) |
| One customer (tenant), or all? | One big customer | A query whose cost grows with their data (case 1) |
| One page, or every page? | Every page | Something shared: the database, the connection pool, a dependency every page calls, a CDN or DNS change |
| Always, or at certain times? | At peak, or at 2 a.m. every night | Capacity, pool exhaustion (case 3), a batch job holding locks (case 5) |
| Since when? | Since Tuesday’s deploy | The diff in that deploy, and data that crossed a size threshold |
| Every request, or some? | Some, unpredictably | A dependency’s tail latency (case 4), lock waits, garbage collection |
Two things make this step fast. One is real-user monitoring (RUM): timing data from actual browsers, split by page, browser, country and customer. The other is a deploy marker on your latency graphs. Without them, you’re asking the user to describe the problem; with them, you can see it for yourself, like having a camera at the scene.
Step 2: find which layer owns the time #
A slow page is the sum of several layers. Measure each one, so you’re comparing numbers rather than hunches:
| Layer | What can be slow | How to see it |
|---|---|---|
| Browser | Big JavaScript bundles, long tasks blocking input, layout shifts, render-blocking CSS and fonts | DevTools Performance panel; Core Web Vitals from real users |
| Network | DNS, TCP and TLS setup, a CDN cache miss, no HTTP/2 or HTTP/3, a far-away region | DevTools Network → Timing; curl -w (below) |
| Edge / load balancer | Queueing, TLS termination, a WAF rule, a cold instance | Load balancer logs (request vs target processing time) |
| Server | Your code, its queries, its calls to other services, waiting for connections | Distributed traces; the Server-Timing header |
| Database | Plans that changed, missing indexes, locks, bloat, a saturated disk | pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS), pg_stat_activity |
| Other services | Their latency, retries, missing timeouts | The client spans in your traces |
The quickest split is server time vs everything else. If the server answered in 40 ms but the user waited 4 s, look at the browser and the network. If the server took 3.9 s, look at the server. Half the suspects are cleared with one number.
Two cheap ways to see the split:
curl -s -o /dev/null -w 'dns %{time_namelookup}s connect %{time_connect}s tls %{time_appconnect}s first byte %{time_starttransfer}s total %{time_total}s\n' https://example.com/page
And a Server-Timing response header, which DevTools shows in the request’s Timing tab:
Server-Timing: db;dur=12.3, db-wait;dur=0.1, dep;dur=20.4, total;dur=35.0
The demo app sets this header on every response. It’s a few lines of code, and it lets anyone with a browser tell “the server is slow” apart from “the page is slow”. I’m very fond of this header: tiny, standard, and it settles arguments in seconds.
Diagram source
flowchart TD
A{"Does the server own most of the time?"} -->|no| B["Browser and network: Core Web Vitals, DevTools"]
A -->|yes| C{"What shape is the trace?"}
C -->|one long query| D["Query cost grows with the tenant: fix the index"]
C -->|a ladder of short queries| E["N+1: one JOIN"]
C -->|long db.acquire, fast query| F["Pool starvation: separate pools"]
C -->|one long http.client span| G["Slow dependency: add a timeout"]
C -->|trivial UPDATE waits| H["Row locks: commit the job in chunks"]
Step 3a: the browser and the network (when the server is fast) #
Core Web Vitals are the shared vocabulary here. Google rates a page “good” when, at the 75th percentile of real visits:
- Largest Contentful Paint (LCP), how long the main content takes to appear, is 2.5 s or less;
- Interaction to Next Paint (INP), how long the page takes to react to a click or keypress, is 200 ms or less (INP replaced First Input Delay as a Core Web Vital in March 2024);
- Cumulative Layout Shift (CLS), how much the page jumps around while loading, is 0.1 or less.
Their usual suspects:
- LCP got worse: a bigger hero image, a font or CSS file that now blocks rendering, the main content moving behind a client-side fetch, or a CDN that stopped caching (check the
cache/ageresponse headers). - INP got worse (“the page lags when I click”): a long JavaScript task on the main thread, often a re-render of a big list or a new third-party script. The Performance panel shows long tasks as red-cornered blocks. Split the work, virtualise the list, or move it off the main thread.
- CLS got worse: images or ads without reserved space, or late-loading fonts.
Beware a classic false lead here. Lab tools (Lighthouse, DevTools on your fast laptop) tell you what can be slow. Field data from real users tells you whether it’s slow for them. A page can score 100 in Lighthouse and still be slow on a mid-range phone on 4G. Throttle the CPU and network in DevTools before deciding.
Not measured in the demo: these numbers depend on devices and networks, and are best taken from your own users.
Step 3b: the server and the database (when the server is slow) #
This is where traces earn their keep, because each culprit leaves a different fingerprint. Each request is a tree of spans: the request itself, every database query, every wait for a pooled connection, every call to another service. Here are five common causes, measured at 8-22 concurrent clients on one laptop:
| # | Cause | p50 / p99 before | p50 / p99 after the fix | Signature in the trace |
|---|---|---|---|---|
| 1 | Query cost grows with the tenant (big tenant) | 829 ms / 1,644 ms | 1.1 ms / 2.9 ms | One db.query that is nearly the whole request, long only for big tenants |
| 2 | N+1 queries | 11 ms / 21 ms (51 queries) | 1.1 ms / 3.3 ms (1 query) | Dozens of short db.query spans in a row |
| 3 | Pool starvation (reports hold the connections) | 291 ms / 306 ms | 2.3 ms / 4.5 ms | db.acquire (waiting for a connection) 166 ms; the query itself 0.5 ms |
| 4 | Slow dependency, no timeout | 22 ms / 2,002 ms | 21 ms / 101 ms | One long http.client span; database fine |
| 5 | Row locks held by a batch job | 5 ms / 558 ms | 4.6 ms / 7.5 ms | A trivial UPDATE taking hundreds of ms; pg_stat_activity shows lock waits |
Diagram source
xychart-beta
title "p50 before the fix (ms)"
x-axis ["Big tenant", "N+1", "Pool starvation", "Slow dependency", "Row locks"]
y-axis "ms" 0 --> 829
bar [829 , 11 , 291 , 22 , 5]
Let’s take each one as its own case.
Case 1: “it’s slow for us”, from your biggest customer #
The orders page filtered by tenant_id and sorted by date, with an index on tenant_id only. For a tenant with 2,000 orders, PostgreSQL fetches 2,000 rows and sorts them in about a millisecond. For one with a million orders, it fetches and sorts a million rows to return 50: 829 ms at the median.
The trace shows one query taking nearly all the time. To confirm, run EXPLAIN (ANALYZE, BUFFERS) with the big tenant’s ID, because the small tenant’s plan looks fine and makes a convincing alibi. The fix is an index that matches both the filter and the order, (tenant_id, created_at DESC): 1.1 ms for both tenants.
One side effect surprised me, and it’s the finding from the lab I’d most want you to remember. While the big tenant’s queries were running, the small tenant’s page was also 10× slower (11 ms instead of 1.1 ms). The big queries were using the CPU and disk the small tenant’s queries needed. One customer’s slow query is everyone’s problem. The slow-query post covers the other ways a query slows down as a table grows.
Case 2: slow everywhere, and worse in production than locally #
The page loaded 50 orders, then each order’s customer with its own query: 51 queries. Locally that cost only 11 ms, because each round trip to the database took about 0.2 ms. On a network with a 1 ms round trip, the same page spends at least 50 ms waiting on round trips. That’s why N+1 “works on my machine”. In a trace it’s unmistakable: a ladder of identical short spans. Once you’ve seen that ladder, you’ll spot it from across the room. One JOIN: 1 query, 1.1 ms.
Case 3: slow at peak, but every query is fast #
Pages and a reporting endpoint shared one pool of 5 connections. Six people running a 300 ms report held all five. The page’s own query took 0.5 ms, but the request took 291 ms, nearly all of it waiting for a connection (db.acquire: 166 ms on average, more at the tail).
This is the sneaky one, the culprit with the best alibi. If you only trace queries, this cause is invisible: every query looks fast and the database looks idle. Instrument the pool’s acquire, or graph its wait count and wait time; most pool libraries expose them.
Giving reports their own pool of 2 brought the page back to 2.3 ms. The cost didn’t disappear, it moved: reports now queued for their own 2 connections and took 902 ms instead of ~300 ms. That’s usually the right trade, because a report can wait and a page can’t. Longer term, the report belongs on a read replica (the replicas post).
Case 4: slow sometimes, for some requests #
Every page called a recommendations service that answered in 20 ms, except 5% of the time, when it took 2 s. Without a timeout, the median stayed at 22 ms, so averages and dashboards looked fine, but the p99 was 2,002 ms. That’s how “it’s sometimes slow” arrives: a tail problem invisible in the median.
The trace shows one long client span, with the database doing nothing. With a 100 ms timeout and a page that renders without recommendations, the p99 was 101 ms. Every outgoing call needs a timeout. Many HTTP clients have none by default, Go’s http.DefaultClient included.
Case 5: slow while a job runs, and the CPU is idle #
A nightly-style job updated every customer’s score in one transaction, with 500 ms of work inside it. Meanwhile, the page did a trivial UPDATE customers SET last_seen = now() WHERE id = $1, and it waited for the job’s row locks: p99 558 ms. That’s for a single-row update that normally takes under a millisecond.
The trace shows a long query; the database explains why. During the slow run, pg_stat_activity had sessions with wait_event_type = 'Lock' in 153 of 158 samples taken every 20 ms:
SELECT pid, wait_event_type, wait_event, now() - query_start AS waiting, query
FROM pg_stat_activity WHERE wait_event_type = 'Lock';
-- and who holds it:
SELECT pid, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
Rewriting the job to commit every 100 rows, with its work done outside the transaction, brought the page’s p99 to 7.5 ms. Lock waits dropped to 6 of 149 samples. Set lock_timeout on interactive requests too, so a page fails fast instead of hanging behind a job. The locking post covers this in more depth.
Step 4: fix, then prove it with the same measurement #
The last step is the one that turns a fix into knowledge, and a hunch into a closed case.
- Measure the fix with the number that found the problem. If the complaint was the p99 for one customer, the evidence is that p99 for that customer, not the overall average.
- Make it hard to come back. A test that counts queries per request (case 2), an index added in a migration with a note on why (case 1), timeouts as a lint rule or a wrapper (case 4), pool wait time on a dashboard with an alert (case 3), and a rule that batch jobs commit in chunks (case 5).
- Write down what it was. The next “it’s slow” usually starts at the same layer.
Remember this
- Pin down who, which page and since when before guessing a cause.
- Split server time from everything else first: one number clears half the suspects.
- Each backend culprit leaves a shape in the trace: learn the shapes.
What to set up on Monday, before anyone complains #
- Traces on every request, with spans for queries, pool waits and outgoing calls. OpenTelemetry’s contrib instrumentation covers most frameworks and drivers. Sample, but keep the slow and failed ones.
Server-Timingon responses, so browser-side and server-side measurements meet in DevTools.- Real-user monitoring of Core Web Vitals, split by page and customer, with deploy markers.
pg_stat_statementsenabled, and graphs of the connection pool’s wait time and of lock waits.- Timeouts everywhere, and
lock_timeout/statement_timeoutfor interactive requests.
With these in place, “it’s slow” stops being a dreaded message and becomes a puzzle you already have the tools to solve: you stop guessing and start seeing.
Server-side numbers: latency-debugging-lab on PostgreSQL 17.11, Go 1.27, OpenTelemetry Go 1.47, one laptop (i7-8550U), load generator on the same machine, Nov 2026. Core Web Vitals thresholds as published by Google (web.dev), checked Nov 2026. Code and full results: latency-debugging-lab.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.