Debug labs: fake one layer, keep a control arm

Some bugs only happen in production, because the layer that causes them only exists there. When that happens I don't try to rebuild production. I rebuild one layer, fake what's around it, and run a second copy that should behave normally. Twice this year that turned a vague complaint into a number.

A bug that only shows up in production is usually a bug in something you don’t run locally. A CDN in front of the app. A proxy between the browser and the API. Ten tabs that have been open since the morning. Dev has none of these, so dev is fine, and the bug report reads like a mood: “it’s slow after a while”, “I still see the old version”.

The obvious move is to make dev more like production. That’s slow, and when it works you still don’t know which of the hundred differences mattered. The other move is to guess the layer, build only that layer, small enough to read in one sitting, and see whether it alone makes the bug happen.

I built two of these labs this year. Each was one or two small Node servers, a script that drove a real browser, and a log. Agents wrote much of the code, with me directing. My part was deciding what to fake, what the control would be, and what would count as proof. Neither lab outlived its bug.

The scenarios below are made up. The two labs and their numbers are real.

Three rules

  1. Rebuild only the suspect layer. If you suspect the cache, the lab is a cache. Nothing else gets rebuilt.
  2. Fake the rest honestly, or pass it through. A fake CDN serves the real build. A fake proxy forwards to the real API. Only the behaviour you suspect is changed, so the only odd thing in the experiment is the thing you put there.
  3. Keep a control arm. Run a second path that is the same in every way but one. If both arms show the problem, the lab is wrong, not the app. If neither does, the guess is wrong.

One habit sits under all three: read the result from the browser’s own records, not from the UI. A spinner is not a measurement. A version stamp in the page, the service worker’s own state and the browser’s timing entries are.

Here are both labs side by side. Tap a row.

The same path with one thing changed. Without it, a bad number has nothing to be bad next to.

A release that doesn’t arrive

The first lab started from a scenario like this. A web app ships with a service worker, so it loads fast and works offline. After a release, some people keep seeing the old version for much longer than they should. Separately, people who keep several tabs open notice their laptop downloading the whole app again and again.

The suspect layer is the service worker and whatever caches sit in front of it. So the lab is a fake CDN, and a way to release to it quickly and often.

The fake CDN serves a built copy of the app. Every response says Cache-Control: no-store, so the browser’s HTTP cache stays out of the way and the only thing caching anything is the worker. One cache in the experiment, not two.

It reads a delay from a small config file on every request and holds each JS and CSS file for that long. I can edit the file in the middle of an install and the next request is slower, with no restart. A slow install is where races live, so I needed to stretch one out whenever I wanted.

Every request is logged with a millisecond timestamp. In the end that log is the only thing I trust about who fetched what, and when.

// Sketch: the fake CDN. Only the service worker may cache.
const cdn = http.createServer(async (req, res) => {
  const path = new URL(req.url, 'http://lab').pathname;
  log(Date.now(), req.method, path);

  // Re-read on every request, so I can slow down
  // an install while it is running.
  const { delayMs } = await readJson('delay.json');
  if (path.endsWith('.js') || path.endsWith('.css')) {
    await sleep(delayMs);
  }

  res.setHeader('Cache-Control', 'no-store');
  serveFile(res, BUILD_DIR + path);
});

Stamping every release

A deploy script builds the app from a git worktree, stamps index.html with a label and the time, and syncs the result into the fake CDN’s folder. The stamp makes every deploy a new version even when no code changed, so I could release ten times in a row and watch the worker see ten versions.

The stamp has a cost. The worker’s manifest lists a hash for every file it caches and refuses a file that doesn’t match. Stamping index.html after the build breaks its hash, so the script recomputes that one hash in the manifest afterwards. I learned that step by watching the worker quietly ignore my first deploy.

A check script compares three things: the stamp on disk, the stamp being served, and what the browser actually runs. The last one comes from a meta tag in the page and from the worker’s debug state page, not from looking at the screen. When the three disagree, the request log says when they stopped agreeing.

Two installs at once

The lab showed two things. The worker has no guard against starting an install while another one is running. That’s a known upstream issue, not something I discovered. And the app ran its own update check in every tab. On a slow network, each tab’s check found the new version and kicked off a full install of its own, on top of the others.

The A/B used the same lab twice: 3 tabs, 400 ms per file, 135 files. The unfixed build made 479 fetches, 3.55 times the work, and one file was fetched 15 times. The fixed build made exactly 135.

In the figure, only 3 tabs was measured. The slider’s other positions are a model and say so. The total and the worst file are the lab’s numbers; how the extra fetches spread over the grid is drawn.

Tab 10fetches
Tab 20fetches
Tab 30fetches
fetches 0files 135work 0.00×worst file 0×measured
3

Each of the 3 tabs found the new version and started its own install.

One poller for all tabs

The fix has three small parts. One update poller across all tabs, using Web Locks: every tab asks for the same named lock, one gets it, and the rest wait in line. When the holding tab closes, the browser releases the lock and the next tab takes over, with no heartbeat to write. A gate, so a second install can’t start while one is running. And within a tab, update steps run one at a time.

// Every tab runs this. Only the tab holding the lock
// gets inside; the others wait in line for it.
navigator.locks.request('update-poller', async () => {
  while (true) {
    await updateOnce();
    await sleep(POLL_INTERVAL);
  }
});

// The gate: if an update is already running,
// join it instead of starting a second one.
let current = null;

function updateOnce() {
  if (!current) {
    current = checkAndInstall().finally(() => {
      current = null;
    });
  }
  return current;
}

The control arm here is the fixed build in the same lab: same tabs, same delay, same files. Without it, 479 is just a big number. Next to 135 it’s a ratio, and a ratio is something you can argue about in a pull request.

Slow by the afternoon

The second lab started from this. A web app is fine in the morning and slow by the afternoon. Nothing in the server logs is slow. Requests seem to wait a long time before they even start.

My guess was the browser’s connection pool. Over HTTP/1.1 a browser opens about 6 connections per host. If WebSockets fail somewhere between the browser and the server, a typical real-time library falls back to long-polling: a request the server holds open until it has something to say. Every open tab keeps one of those going. With six tabs, every connection to that host is sitting on a long-poll, and the next request from any tab waits for one to come back.

The server can’t see any of this. From its side every request is fast once it arrives. The wait happens inside the browser, before the request leaves.

A proxy that breaks things on purpose

The suspect layer is the network path: something that downgrades to HTTP/1.1 and breaks WebSockets. So the lab is a small proxy that does exactly that, on purpose, in front of the real API.

  • It speaks plain HTTP/1.1.
  • It destroys every WebSocket upgrade, so the app falls back to long-polling the way it would behind a bad middlebox.
  • It adds Timing-Allow-Origin, so the page may read detailed timings for requests to it.
  • It counts requests in flight and exposes the counters.
  • It logs paths and never query strings. Query strings carry things that don’t belong in a log file.

The control arm is a second copy of the same proxy on another port. Same code, same upstream. A different port gets its own pool in the browser, and nothing holds that pool open.

// Sketch: the hostile proxy. Start it twice: once under
// test, and once on another port as the control.
const proxy = http.createServer((req, res) => {
  const path = new URL(req.url, 'http://lab').pathname;

  // Let the page read detailed timings for this host.
  res.setHeader('Timing-Allow-Origin', '*');

  // Probes are answered here, in about 1 ms.
  if (path === '/probe') {
    res.end('ok');
    return;
  }

  // Everything else goes to the real API.
  forward(req, res, REAL_API);
});

// Refuse every WebSocket upgrade.
// The app falls back to long-polling.
proxy.on('upgrade', (req, socket) => socket.destroy());

Measuring the wait

A Playwright script opens a headed Chromium with HTTP/2 and QUIC turned off, so the browser can’t route around the problem. It uses a persistent profile and waits for me to log in by hand, so no credentials go anywhere near the script. Then it opens N tabs through the hostile proxy, and every 5 seconds each tab sends one probe through each proxy.

The number I read is the stall: how long a request waited between the page asking for it and the browser actually sending it. The browser records both moments in its Resource Timing entries, so the stall is one minus the other. Server time isn’t in it. It’s the queue and nothing else.

// Sketch: runs in every tab, every 5 seconds.
performance.clearResourceTimings();

const t = Date.now();
await Promise.all([
  fetch(`${UNDER_TEST}/probe?t=${t}`),
  fetch(`${CONTROL}/probe?t=${t}`),
]);

const probes = performance
  .getEntriesByType('resource')
  .filter((e) => e.name.includes('/probe?'));

for (const e of probes) {
  // Time spent waiting for a free connection.
  const stall = e.requestStart - e.fetchStart;
  report(e.name, stall);
}

With 8 tabs the mean stall was 0.8 s and the worst was 6.1 s. With 14 tabs the mean was 4.9 s and the worst 13.7 s, and 28 of 31 probes waited more than a second. The proxy answered each probe in 1 ms. The control proxy, in the same browser at the same moment, never waited more than 19 ms.

That last number is the reason the control arm exists. Without it, 13.7 s could be the laptop, the VPN or the API. With it, the two arms differ only in the pool, so the pool is the answer.

waitingproxy under test, HTTP/1.1: 6 connections per hostconn 1conn 2conn 3conn 4conn 5conn 6control proxy, same upstream, its own pool
2

2 long-polls hold 2 of 6 connections. A request always finds a free one.

8 tabs
mean 0.8 s, max 6.1 s
14 tabs
mean 4.9 s, max 13.7 s, 28 of 31 probes over 1 s
Control proxy
never over 19 ms
Server time
1 ms per probe

Measured stall in the lab, from Resource Timing. The drawing above is a picture of the queue, not a timer.

The fix is on the network side, not in the app. With HTTP/2, requests to one host share a single connection as separate streams instead of queueing for six. WebSockets that actually connect stop tabs from holding long-polls at all. Turn on HTTP/2 in the figure and the queue goes away.

Where the lab lies to you

Both labs read their results from the browser, and the browser’s records have blind spots. Four of them cost me time.

  • No entry for some responses. Chrome records no Resource Timing entry for a 404, or for a response marked no-store. My first probe hit a path that didn’t exist and produced no data at all, which reads like “no stall” if you’re careless. The probe now gets a 200 from the proxy itself, and a cache-busting query keeps it fresh without no-store.
  • A full buffer. The timing buffer holds 250 entries. A tab that has been open for an hour has filled it, and new entries are dropped without a word. The probe clears it first.
  • Two names, two pools. The pool is keyed by host name. localhost and 127.0.0.1 are the same machine and two different pools. Load the app through one and probe through the other, and you’re measuring a pool nothing is using.
  • localhost isn’t always 127.0.0.1. Node 18 resolves localhost to ::1, the IPv6 address. A proxy listening only on 127.0.0.1 can’t be reached as localhost there. The same trap showed up in parallel checkouts.

None of these is exotic. Each one makes a lab report a clean result for the wrong reason, which is worse than reporting nothing. The control arm catches some of them, because a broken probe is broken in both arms. The rest you catch by checking that the “good” arm really is producing data.

What to copy

  • Name the layer you suspect before you write anything.
  • Build only that layer. Fake or pass through everything else.
  • Add a control arm that differs in exactly one way.
  • Make every version and every request identifiable: stamps on deploys, timestamps on requests.
  • Read the answer from the browser’s own records, and know where those records go quiet.
  • Throw the lab away when the bug is fixed. Keep the notes.

Both labs were small, and an agent wrote most of each one. That changed what a lab is for. A lab used to be something I’d build only when I was sure of the cause. Now it’s cheap enough to build when I’m not sure yet, and let it tell me. Deciding what counts as proof when an agent writes the code is its own subject: the gates I put around an agent.