Node.js Production Failure Lab · part 1
How One Report Can Slow Down an Entire Site: Event Loop Blocking in Node.js
Product pages are slow, the database is innocent, and the culprit is a CSV report. A step-by-step walk through Node.js's single-threaded event loop, told through a production incident.
Node.js Production Failure Lab · Part 1 · Difficulty ★☆☆ · Reading time ~20 min · Lab ~30–60 min
On July 2, 2019, Cloudflare’s global network served 502 errors to visitors for about 27 minutes. It wasn’t a network failure or an attack: a single regular expression inside a newly deployed security rule consumed every CPU core that handled HTTP traffic (Cloudflare’s postmortem). A few innocent-looking lines of CPU work brought the whole system to a halt.
Node.js teaches an even harsher version of this lesson: your JavaScript runs on a single thread. If one request does a few seconds of synchronous work, every request that arrives in the meantime waits. In this article we’ll live through exactly that in a realistic incident: product pages are slow, customers are complaining, and the database looks guilty but isn’t. The real culprit is a CSV report the finance team is downloading.
What you’ll learn
- How the Node.js event loop works, and why one request’s CPU work becomes everyone’s latency
- The difference between measuring latency at the edge and inside the service, and what that gap tells you
- How to read event loop delay, and why you want
max, notp99 - How to rule out red herrings: why “the database pool is full” is a symptom, not a cause
- How to pin down the guilty function, line by line, with a flame graph
- Your fix options: doing less work, moving work into SQL,
worker_threads, partitioning, background jobs
Prerequisites
You can read this article without running the lab. These will help:
| Topic | Why | Resource |
|---|---|---|
| Event loop phases | To understand the order in which callbacks run | The Node.js Event Loop (official guide) |
| Blocking the event loop | The theory behind this article; a must-read | Don’t Block the Event Loop (or the Worker Pool) (official guide) |
| Percentiles (p50, p95, p99) | To read latency graphs | The Google SRE book, chapter Monitoring Distributed Systems |
| Big-O | To see why Array.find inside a loop is expensive | Any algorithms resource |
1. The concept: one thread, one queue
Node.js runs a process’s JavaScript on a single thread. The mechanism that drives that thread is called the event loop. Roughly, the loop does this:
- Pick up the next callback that’s ready (a request arrived, a query returned, a timer fired).
- Run it to completion.
- Move on to the next one.
However long you stay in step 2, everyone behind you waits that long. await doesn’t change the picture: await releases the loop while it waits, but the synchronous code after the await still holds the loop.
time ───────────────────────────────────────────────────────────►
event loop: [product 5ms][report: 2000 ms of sync work ·····················][product][product][product]
request A (product) ──┐ arrives ...waiting... └─► response after 2 s
request B (checkout) ──┐ arrives ...waiting... └─► after 1.8 sOn its own, a product page request is 5 ms of work. But because it’s stuck in line behind the report, the customer waits 2 seconds. The product page is the victim; the report is the culprit.
See it for yourself: a 20-line experiment
Before you open the lab, it takes two minutes to see this on your own machine:
// block.mjs
import http from 'node:http';
import { monitorEventLoopDelay } from 'node:perf_hooks';
const delay = monitorEventLoopDelay({ resolution: 10 });
delay.enable();
http.createServer((req, res) => {
if (req.url === '/block') {
const end = Date.now() + 2000;
while (Date.now() < end) {} // a 2-second synchronous "report"
}
res.end(`ok ${req.url}\n`);
}).listen(3001);
setInterval(() => {
// histogram values are in nanoseconds
console.log(`event loop delay p99: ${(delay.percentile(99) / 1e6).toFixed(0)} ms max: ${(delay.max / 1e6).toFixed(0)} ms`);
delay.reset();
}, 5000).unref();node block.mjs
# in a second terminal:
curl -s localhost:3001/block > /dev/null & sleep 0.2; time curl -s localhost:3001/fastOn my machine (Node.js 22), the result looks like this:
ok /fast
real 1.82
event loop delay p99: 12 ms max: 2012 msNotice two things:
/fastdoes no work at all, yet it took 1.82 seconds: it was waiting behind/block.- Event loop delay has a p99 of 12 ms and a max of 2012 ms. The histogram samples every 10 ms. Out of ~500 samples in 5 seconds, only a handful land on the blocked stretch, so p99 writes it off as “rare” and hides it.
maxdoesn’t. This is the most important measurement lesson in this article: for the event loop, look at max.
monitorEventLoopDelay and event loop utilization (eventLoopUtilization) are built into Node.js: see the perf_hooks documentation.
2. The incident: a Tuesday afternoon at quarter-end
🔥 [FIRING] ApiHighLatencyP95:
shopflow-apip95 latency at the edge is above 500 ms (currently ~2 s)
You’re on call for the API of an online store (ShopFlow). A message comes in from the support team: “Some customers say product pages sometimes hang for a second or two, then load normally. Checkout feels sluggish too.” Here’s what you know:
- Traffic is normal (~38 requests/s), and so is the error rate.
- p95 is normally ~20 ms; right now it’s ~2 s.
- Nobody touched the infrastructure. Recent deploys:
| Version | When | Change |
|---|---|---|
| 2.15.1 | today 11:40 | reject orders with more than 10 line items |
| 2.15.0 | yesterday 18:10 | add SKU, product name, category, and formatted prices to the sales report |
| 2.14.3 | yesterday 18:10 | pg version upgrade |
If you’ve set up the lab, start the incident:
git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 001💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), and investigate on your own for 30 minutes. The results of each step below are tucked into collapsible sections; open them when you get stuck. For the lab’s built-in hints:
./lab hint 001.
3. Investigation, step by step
A good investigation doesn’t start with the code. You build a hypothesis from telemetry, and open the code only for final confirmation.
Step 1: Follow the time from where the customer sees it
The dashboard has two latency graphs: one at the edge (the proxy between the customer and the API, Traefik) and one measured by the API itself. Compare the two for the same requests.
What do we see?
At the edge, p95 ≈ 2 s. In the API’s own measurement, p95 for /api/products/:id ≈ 50 ms.
Where did the other ~1.95 seconds go? They were lost before the API even started the clock: requests are waiting to be processed. Open the trace of a slow product request in Jaeger and you’ll see the same thing for a single request: the proxy’s span starts at 0, and the API’s span starts ~2.2 s later.

Left: the latency the customer sees. Right: what the API measures for itself. Every route except the report takes a few tens of milliseconds inside the API; the difference is spent in the queue.

A single product request: the proxy’s span lasts 2.3 s, while the API’s actual work comes at the very end and takes 55 ms. The empty stretch before it is the time the request spent waiting for the event loop.
Lesson: Measuring latency in one place isn’t enough. A gap between the edge and the service is the signature of “waiting in a queue.”
Step 2: Question the usual suspects
Some signals on the dashboard jump out: up to 64 requests waiting on the database connection pool, 1-second pg-pool.connect spans in Jaeger, and on top of that, the pg library was upgraded yesterday. Is it the database?
Is the database to blame?
No. Cross-check the evidence:
pg_stat_statements(./lab psql, or the table at the bottom of the dashboard): queries average a few milliseconds. Nothing in the slow query log.- Back-of-the-envelope math: 10 connections × a few ms per query = capacity for thousands of queries per second. The API sends about a hundred.
So why does the pool look full? The pool hands out a connection in microseconds, but the callback that would take the connection can’t run, because the event loop is busy. Requests pile up while the loop is blocked, and the moment it’s free they all rush the pool at once. Pool congestion is a consequence, not a cause.
The key observation at this point: everything inside the API is delayed at the same moments: queries, pool callbacks, even Prometheus’s /metrics scrapes. In Node.js, what has to be free for any callback to run?

Waiting requests (blue) arrive in sharp spikes: when the block ends, the backlog rushes the pool all at once. Open connections (green) stay flat at 10; a bigger pool won’t fix these spikes.
Lesson: When a metric says “full,” ask whether the resource itself is what’s filling it, or whether it’s the side that consumes it.
Step 3: Look at the event loop
Go to the Node.js runtime row on the dashboard. In the Event loop delay panel, compare p99 with max.
What does the event loop say?
- Event loop delay: max 2–3 s, p99 ~25 ms. Exactly the picture from the demo: the loop is blocked for seconds at a time, several times a minute, and p99 hides it.
- Event loop utilization (ELU) ~55%, CPU ~0.5 cores. That’s far too much for 38 requests per second; these endpoints need only a small fraction of it.

The green max line lives in the seconds range, while the yellow p99 hugs the floor. An alert that only watches p99 would never see this incident.
Hypothesis: Something is running synchronous JavaScript for a long time, and every other request is waiting behind it.
Step 4: Find the request that’s slow on its own
We’re looking for the culprit, not the victims: the request that’s slow because of its own work, not because it was waiting. In Jaeger, select the shopflow-api service and look at the longest traces.
The guilty request
GET /api/reports/sales: 2–3 s all by itself. Its trace shows two short database spans (sales ~40 ms, catalog ~10 ms), followed by a long gap with no child spans at all. Uninstrumented synchronous code.
Go back to the change history: 2.15.0 added “product details and formatted prices” to this report last night. So why did the problem start this afternoon and not last night? Because today is quarter-end: the finance team started pulling reports in bulk today. The trigger and the root cause are different things.

The report request takes 3.2 s. Both database queries finish within the first 250 ms; for the rest of the request there are no child spans at all. The time is going into uninstrumented synchronous code.
Step 5: Fill the gap with a profile
What’s inside the gap in the trace? A profiler will tell you. The lab has continuous profiling turned on: Grafana → Drilldown → Profiles, service shopflow-api, profile type wall/cpu.
What does the flame graph show?
- ~51% of CPU is in the
formatMoneyfunction (shared/money.ts) - ~16% is in the report’s
catalog.findcallback (reports/sales-report.ts)

First place in the Top Table is formatMoney; second is the anonymous callback in sales-report.ts (catalog.find). The flame graph on the right shows the same stack: buildSalesReport → callback → formatMoney.
Alternative route: stop the traffic (./lab traffic off), connect to 127.0.0.1:9229 from Chrome via chrome://inspect, and call the report yourself while recording in the Performance panel.
If flame graphs are new to you: the x-axis isn’t time, it’s the sum of samples. A wide bar = lots of CPU. The call stack gets deeper as you go up. Source: Brendan Gregg, Flame Graphs.
Step 6: The code, last
Now you know exactly where to look:
// reports/sales-report.ts (2.15.0)
const sales = await query(/* one month of sales rows: ~51,000 */);
const catalog = await listProductCatalog(); // 20,000 products
const rows = sales.map((sale) => {
const product = catalog.find((entry) => entry.id === sale.productId); // linear scan on every row
return [
/* ... */
formatMoney(sale.unitPriceCents),
formatMoney(sale.unitPriceCents * sale.quantity),
];
});
// shared/money.ts
export function formatMoney(cents: number, currency = 'USD'): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100); // a new object on every call
}There are two problems:
- O(n·m) lookup: 51,000 rows × 10,000 comparisons on average ≈ 500 million comparisons.
- An expensive object inside a loop: two
formatMoneycalls per row means a brand-newIntl.NumberFormat100,000 times. Building a formatter (loading locale data, resolving options) costs many times more than formatting a number with one.
Measure it yourself:
const opts = { style: 'currency', currency: 'USD' };
console.time('new formatter every time');
for (let i = 0; i < 100_000; i++) new Intl.NumberFormat('en-US', opts).format(i / 100);
console.timeEnd('new formatter every time');
const f = new Intl.NumberFormat('en-US', opts);
console.time('single formatter');
for (let i = 0; i < 100_000; i++) f.format(i / 100);
console.timeEnd('single formatter');On my machine: 1,760 ms versus 25 ms, roughly 70×. In the same run, 51,000 Array.find calls (on a 20,000-element array) took 420 ms; the same lookups with Map.get took 2 ms.
The report holds the only thread for 2 seconds, and at quarter-end the finance team pulls a report roughly every 4 seconds. The event loop is blocked half the time.
The lab’s diagnosis questions and answers (./lab submit 001)
| Question | Answer |
|---|---|
| Which endpoint triggers the incident? | GET /api/reports/sales |
| Which resource is saturated? | The Node.js event loop (main thread) |
| What’s the root cause? | CPU-heavy synchronous JavaScript on the request path |
4. Mitigation: stop the bleeding first
A proper fix needs a code change and a review. To rescue customers in the meantime:
- Pause or throttle the report: a feature flag, or a temporary 503 on
/api/reports/salesplus a heads-up to the finance team. The catalog and checkout recover within seconds. - Or roll back 2.15.0: the report loses its new columns, and the blocking stops.
- Don’t: grow the connection pool, add a database replica, or restart instances. The database isn’t the bottleneck, and every fresh instance blocks the same way on its first report.
5. The fix: remove the wasted work
The cheapest work is the work you never do.
Let the database do the join. The database joins on primary keys using indexes; the API no longer has to scan the catalog for every row:
const sales = await query<Sale>(
'reports.sales',
`SELECT o.id AS "orderId", o.created_at AS "orderedAt", c.email AS "customerEmail",
p.sku, p.name AS product, cat.name AS category,
i.quantity, i.unit_price_cents AS "unitPriceCents"
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
JOIN categories cat ON cat.id = p.category_id
WHERE o.created_at >= $1 AND o.created_at < $2
ORDER BY o.created_at, o.id, i.id`,
[range.from, range.to],
);Reuse the formatter, one per currency:
const formatters = new Map<string, Intl.NumberFormat>();
export function formatMoney(cents: number, currency = 'USD'): string {
let formatter = formatters.get(currency);
if (!formatter) {
formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency });
formatters.set(currency, formatter);
}
return formatter.format(cents / 100);
}The CSV stays byte-for-byte identical; the lab’s functional checks verify this. Removing the feature doesn’t count as a fix.
Which change bought what?
One month of report data (~51,000 rows):
| Variant | Report time |
|---|---|
| Original | ~2.2 s |
Map instead of Array.find, formatter still created on every call | ~1.8 s |
Formatter cached, Array.find still there | ~0.75 s |
| SQL join + cached formatter (the fix) | ~0.27 s |
Here’s the interesting part: reading the code, your eye goes straight to Array.find, but the real cost is in the one-line formatMoney helper. A profiler shows you that in seconds; measure instead of guessing.
6. Verification
./lab deploy
./lab verify 001verify runs the standard traffic (open model, ~38 requests/s) for 60 seconds and measures from the client side:
| Metric | Target | Before | After |
|---|---|---|---|
| Catalog p95 | < 250 ms | 1.84 s | 12 ms |
| Checkout p95 | < 400 ms | 1.83 s | 16 ms |
| Account p95 | < 300 ms | 1.70 s | 12 ms |
| Report p95 | < 3 s | 2.56 s | 294 ms |
| CPU | 0.53 cores | 0.15 cores | |
| Event loop utilization | 55% | 19% | |
| Event loop delay (max) | 2.87 s | 159 ms | |
| Waiting on the pool (max) | 64 | 0 |
Requests waiting on the pool went from 64 to 0, and we never touched the pool. That’s the proof of Step 2’s diagnosis: “a consequence, not a cause.”
The graphs tell the same story. The dashed orange line marks the deploy:



Look at the pool graph: after the deploy, the blue “waiting” line is flat at zero. Nobody touched the pool settings; the event loop was simply set free.
7. Fixes that look right but aren’t
| Attempt | Why it falls short |
|---|---|
| Growing the pool, scaling the database | The database isn’t the bottleneck. More connections just means a bigger stampede when the block ends. |
| Restarts, more instances | Every instance blocks the same way on its first report. You spread the load, but each instance builds the same queue. |
Moving it to worker_threads (e.g. Piscina) | The right tool for heavy but legitimate work. Here the work is wasted: it still burns ~2 s of CPU per report. Under a 1-CPU limit the worker competes with the main thread and reports get even slower. Shipping 51,000 rows to a worker also means paying the copy cost on the main thread. |
| Caching the report by date range | Hides the problem: every new range still blocks for seconds. |
Only Array.find → Map | A step in the right direction, but on its own it only gets you from ~2.2 s to ~1.8 s. The real cost is in the formatter. |
8. In production: alternatives and prevention
When the work really is heavy:
- Partitioning: split the work into small chunks and let the loop breathe in between with
setImmediate. Streaming large CSVs chunk by chunk also keeps memory usage flat. - Offloading: move it to a separate thread with
worker_threads. The official docs say workers are useful for CPU-intensive JavaScript, not for I/O, and recommend a pool rather than spawning a new worker per task (Worker threads). - Background jobs: the most robust design for bulk reports. A queue, a separate worker service, and a download link when it’s ready; ideally against a read replica.
The official guide compares these options in detail in its “Complex calculations without blocking the Event Loop” section: Don’t Block the Event Loop.
Alert on the cause, not the symptom:
- alert: EventLoopBlocked
expr: max_over_time(nodejs_eventloop_lag_max_seconds{job="api"}[1m]) > 0.5
for: 2m
labels:
severity: pageCode review checklist:
- Are expensive objects being built inside a loop? (
Intl.*,RegExp, clients, schemas) - Inside loops, are
Map/Setused instead ofArray.find/includes? - Does work that grows with the data, like “all orders × all products”, go to SQL or a background job?
- Are regexes that run on user input vulnerable to catastrophic backtracking? (The Cloudflare lesson; see the ReDoS section of the official guide.)
- Any large
JSON.parse/JSON.stringifycalls? Those block the event loop too.
Test with production-sized data. The feature was tested with a handful of orders: 50 rows × 20 products is instant; 51,000 × 20,000 is not. A CI benchmark of a one-month report would have caught the problem before merge.
Keep continuous profiling on. It turns a long investigation into a two-minute one. The lab uses Grafana Pyroscope. For a one-off profile, use the Chrome DevTools Performance panel: Profile Node.js performance.
Key takeaways
- In Node, one request’s CPU work is everyone’s latency. Asking “which request is slow on its own?” finds the culprit.
- Measure latency in two places: at the edge and inside the service. The difference is time spent in the queue.
- For the event loop, look at
max; p99 hides rare but long stalls. - A resource that looks full (the pool) is sometimes full not because of itself, but because of the side consuming it.
- The trigger (quarter-end reports) and the root cause (inefficient synchronous work on the request path) are different things. A deploy that looked fine for 20 hours can still be the culprit.
- Don’t guess. Profile.
Test yourself
1. p95 is ~2 s but p50 is low. What does that tell you?
Most requests land between two blocks and are fast. The ones that land on a block wait for seconds. The slowness is intermittent, not constant: the classic signature of event loop blocking.
2. Why are customers complaining about product pages and not the report?
The report is an internal tool for the finance team, and it’s expected to be slow anyway. The product pages are the victims: their own work takes 5 ms, but they’re stuck waiting behind the report. Where people complain is often not where the problem is.
3. Why isn’t moving this work to worker_threads the first choice?
The work is wasted: removing it first cut CPU by 70%. A worker would do the same wasted work on another thread, compete with the main thread under the CPU limit, and leave the main thread paying for copying the data between threads. Workers are the right tool when the work itself is genuinely heavy.
4. Which metric would you alert on for event loop blocking?
A short-window threshold on nodejs_eventloop_lag_max_seconds (or the max from monitorEventLoopDelay): for example, 1-minute max > 0.5 s, sustained for 2 minutes. Event loop utilization (ELU) as a supporting signal.
Further reading
Basics
- Don’t Block the Event Loop (or the Worker Pool): the official guide. Its sections on ReDoS, JSON DoS, partitioning, and offloading read like a sequel to this article.
- The Node.js Event Loop: the phases of the event loop.
- perf_hooks:
monitorEventLoopDelayandeventLoopUtilization.
Deep dives
- Brendan Gregg, Flame Graphs: a guide to reading flame graphs, from their inventor.
- Google SRE book, Monitoring Distributed Systems: the four golden signals, and why percentiles/histograms beat averages.
- Gil Tene’s talk “How NOT to Measure Latency”: how load tests can hide slowness (coordinated omission). This is why the lab’s
verifystep uses an open-model load. - Node.js Worker threads and Piscina: for when you really do need to move work to another thread.
Real-world incidents
- Cloudflare, Details of the Cloudflare outage on July 2, 2019: a single regex eating every CPU; the postmortem’s appendix on regex backtracking is worth reading on its own.
Next up: Random restarts. The service restarts itself every few minutes, and there are no errors in the logs. We’ll learn to tell a memory leak apart from plain load, and to find the leak’s owner with heap snapshots.
The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 001 to generate a postmortem template and compare it with your own write-up.