Why one synchronous CPU loop in Node.js stalls your /healthz endpoint

How one synchronous CPU loop stalls Node.js /healthz probes, triggers SIGTERM-to-SIGKILL restarts, and looks quiet on host CPU — with live OTel proof.

Everything on your host dashboard looks healthy, yet one slow JavaScript loop can quietly knock over a live Node.js service. Inbound requests back up, proxies start serving 504 timeouts and then flip to 502 drops once processes get killed, and /healthz stops answering. Multi-core container CPU sits around 25% or 50%, well below scaling alarms.

That disconnect comes down to Node's threading model: your JavaScript, HTTP parsing, and healthchecks share one main libuv loop. When a synchronous loop locks that stack, /healthz cannot run even while the kernel accepts TCP sockets. Orchestrators reboot those silent containers into a cascade, a blind spot covered in why legacy APM metrics miss event loop stalls.

The table below traces how one blocking handler triggers healthcheck kills and how to resolve it.

Stage Runtime symptom Cause & resolution
Liveness fails 504 then 502; host CPU at 25%–50% SIGTERM stalls behind sync loop until SIGKILL hits
Loop locks /healthz waits in kernel TCP queue OTel trace isolates the 6 s blocking route
Safe fixes Main thread stays free for poll Bounded setImmediate(), worker_threads, async stdlib

Why do orchestrators kill Node.js pods when CPU looks low?

Container schedulers separate traffic draining from process restarts using separate checks. In Kubernetes, a failed readiness probe removes a pod from Service endpoints so requests route elsewhere. A failed liveness probe, much like a Swarm or ECS healthcheck, restarts the container instead.

Even when a liveness probe times out, the scheduler sends SIGTERM before SIGKILL so active sockets can close cleanly. Our Failure Lab Express app (apps/node-express/app.js, lines 406–409) hooks that shutdown path:

process.on('SIGTERM', () => {
  server.close();
  setTimeout(() => process.exit(0), 5000).unref();
});

Here is the trap: Node cannot invoke that SIGTERM callback while a synchronous loop still holds V8. Graceful shutdown never begins. Once the grace period expires, SIGKILL ends the container mid-flight, flipping proxy responses from 504 timeouts to 502 drops as retries hit sibling replicas.

Host averages blur that paralysis. Because Node executes JavaScript on one core at most, saturating that thread shows 100% of one core—only 50% across two vCPUs, or 25% across four. Following how libuv schedules /healthz makes clear why lightweight probes stall right behind heavy routes.

How do libuv phases actually handle /healthz and concurrent I/O?

Under Express, Node runs callbacks across five user-facing libuv phases (timers, pending callbacks, I/O poll, setImmediate check hooks, and close callbacks), with internal idle and prepare steps between turns. Whenever one call frame refuses to return, every phase stalls behind it, as the cascade diagram below traces.

Cascade diagram showing a synchronous loop stalling libuv poll phases, queuing /healthz, and causing SIGKILL cascades

Engineers often assume Promises or process.nextTick() slip through between phases, especially since Node.js 11 (including Node.js 22.23.5 in our lab container) began draining microtasks right after every callback returns. In reality, neither eager microtasks nor incoming poll reads can interrupt a synchronous function until its stack frame unwinds.

That is why /healthz freezes even though apps/node-express/app.js (lines 93–107) does almost nothing:

// Scenario 08: returns 503 when SIMULATE_BAD_HEALTHCHECK=true
app.get('/healthz', (_req, res) => {
  if (process.env.SIMULATE_BAD_HEALTHCHECK === 'true') {
    return res.status(503).json({
      status: 'unhealthy',
      reason: 'SIMULATE_BAD_HEALTHCHECK=true',
      tip: 'Use Formatio Roll back to restore the previous successful deployment.',
    });
  }
  return res.status(200).json({
    status: 'ok',
    service: 'node-express',
    uptime_seconds: Math.floor(process.uptime()),
  });
});

That handler touches zero databases and writes responses during poll in microseconds. Once another handler spins, however, /healthz finishes TCP handshaking inside the Linux accept queue and stalls behind V8. Triggering that lock against a deployed service reveals how telemetry captures it.

How can you reproduce event loop starvation deterministically?

Inside apps/node-express/app.js (lines 363–376), Scenario 04 triggers this stall deterministically with one synchronous loop:

app.all('/api/lab/scenarios/04-event-loop-block', (req, res) => {
  const durationMs = parseInt(String(req.query.ms || '5000'), 10);
  console.log(`[Sabotage] Blocking Node.js event loop synchronously for ${durationMs}ms...`);
  const start = Date.now();
  while (Date.now() - start < durationMs) {
    Math.random() * Math.random();
  }
  res.json({
    status: 'resolved',
    scenario: '04-event-loop-block',
    blocked_ms: durationMs,
    message: `Event loop was blocked synchronously for ${durationMs}ms.`,
  });
});

To expose concurrent queueing, scenarios/04-event-loop-block/trigger.sh backgrounds a POST call to ?ms=5000, adjustable via BLOCK_MS. After 0.5 seconds, it sends a foreground curl -sS --max-time 10 probe to /api/lab/status, which stalls behind the loop just like /healthz.

When I ran that trigger against our deployed container, the observability metrics view below explained why host graphs leave teams guessing:

Live Formatio Metrics view during Scenario 04 showing CPU spike, 37 MB memory blip, zero 5xx errors, and double request peak at 08:27 AM

At 08:27 AM, CPU spikes alongside a double peak in Requests and higher network Bandwidth. Memory rises briefly before settling at 37 MB, while 5xx errors stay at 0. An OOM crash is not what happened. Top summary cards still show idle readings (1.3% CPU, 0 B/s, 0/min, 0 ms) simply because traffic had already drained. Three collection rules explain that view. Formatio samples CPU and memory every 15 seconds, counts HTTP ingress requests when responses finish rather than while blocked, and reports per-core CPU (100% equals one core) instead of host averages.

Resource charts proved the container spiked and recovered, yet could not tell me which endpoint froze it. Roughly a minute earlier, I ran a 6-second trigger (?ms=6000) and checked the OpenTelemetry trace waterfall at 12/1/2026, 8:25:39 AM:

Live OTel trace waterfall for Scenario 04 showing a 6-second span across Express middleware and route handler on Node.js 22.23.5

Because package.json boots Node.js 22.23.5 with node --require @opentelemetry/auto-instrumentations-node/register app.js, OpenTelemetry wraps Express before routes execute. Preloading at boot also avoids exit-race telemetry drops covered in why Node.js drops telemetry on crashes and how supported Railpack OTel preloads compare to sidecars.

Waterfalls turn symptoms into route attribution. From 07:25:39 GMT to 07:25:45 GMT, an outer middleware - patched span finishes in 5.9 ms and jsonParser takes 1.9 ms, before a second router middleware - patched span holds open with request handler - /api/lab/scenarios/04-event-loop-block for 6 seconds. Seeing those spans let me isolate the stalling endpoint directly without hunting through [Sabotage] logs. Once identified, keeping concurrent requests moving comes down to three patterns.

What fixes event loop blocking without rewriting Node.js?

The remediation diagram below contrasts three ways to prevent heavy tasks from monopolizing Node's single loop.

Diagram comparing setImmediate yielding, worker_threads pooling, and async standard library APIs

For long in-process work, yielding between bounded slices with setImmediate() returns control to libuv. In scenarios/04-event-loop-block/solution.patch (app.js, lines 363–376), cooperative turns unblock concurrent health checks:

app.all('/api/lab/scenarios/04-event-loop-block', async (req, res) => {
  const durationMs = parseInt(String(req.query.ms || '5000'), 10);
  const start = Date.now();
  await new Promise((resolve) => {
    const step = () => {
      if (Date.now() - start >= durationMs) return resolve();
      setImmediate(step);
    };
    step();
  });
  res.json({
    status: 'resolved',
    scenario: '04-event-loop-block',
    blocked_ms: durationMs,
    message: `Yielded event loop safely across slices for ${durationMs}ms.`,
  });
});

Each setImmediate(step) lets poll serve /healthz and /api/lab/status between ticks. Note one practical catch: solution.patch spins empty ticks against Date.now() strictly to demonstrate yielding, whereas production code should run a fixed chunk of real work per turn. As the chart below confirms, slicing stops concurrent request starvation even across a 5,000 ms handler.

Comparison chart of Scenario 04 blocking before and after setImmediate yielding

Yielding still shares one core, however, so heavy JSON parsing or transforms belong on a bounded worker_threads pool that scales across cores. Workers carry two caveats of their own. Moving catastrophic backtracking regex (ReDoS) off-thread still hangs that worker unless you enforce linear regexes or worker.terminate() timeouts. Shipping huge payloads like 40 MB parsed objects over postMessage also hits main-thread structuredClone lag, so pair workers with express.json({ limit }), streams, or transferable ArrayBuffer slices.

For built-in operations, replace blocking helpers (fs.readFileSync, zlib.gzipSync, crypto.pbkdf2Sync) with async calls that run on libuv's background threadpool. Watch one default ceiling: UV_THREADPOOL_SIZE starts at four threads, so expand it or route heavy bursts to workers. The comparison table below pairs each pattern with the production guardrail it needs.

Pattern Keeps libuv loop open Guardrail in production
Cooperative setImmediate() slices Yields between chunks so /healthz runs Cap chunk work; avoid idle spinning
Bounded worker_threads pool Runs heavy CPU across multiple cores Timeout ReDoS workers; limit postMessage size
Async stdlib (fs, crypto, zlib) Offloads blocking syscalls off JS stack Monitor default 4-thread UV_THREADPOOL_SIZE limit

Frequently asked questions

Why does container CPU usage sit at 25% or 50% when the Node.js event loop is frozen?

Node.js runs application code on a single thread, consuming at most 100% of one logical core. On multi-vCPU hosts, container averages divide that load across idle cores (reading 50% on two vCPUs or 25% on four) even while Express sits deadlocked.

Why is setImmediate() safe for unblocking /healthz while process.nextTick() freezes the server?

Node drains process.nextTick() right after each callback returns, before libuv reaches poll to accept HTTP traffic. Recursive nextTick chains starve sockets indefinitely, whereas setImmediate() waits until check after poll serves /healthz.

Should you move /healthz onto a separate Node.js HTTP server port to stop timeouts?

No. Another http.createServer inside the same Node process shares the exact same libuv loop, so synchronous blocks freeze both ports. Serving /healthz from a worker_thread creates a worse trap by returning 200 OK while Express stays frozen.


If you want to trigger this stall and verify the patch locally, clone formatio-failure-lab and run scenarios/04-event-loop-block/trigger.sh. To deploy test repositories with OpenTelemetry traces wired up out of the box, you can also start a 14-day free trial in the Formatio dashboard.