Most Node.js APIs feel fast in development and on launch day. Then traffic grows, p95 latency creeps up, and somebody suggests "just add more servers". Sometimes that helps. Often it doesn't, because the problem is not the number of servers. It is one thing blocking the event loop, or one slow dependency that every request waits on.
Here are the checks and fixes we use first when a Node.js API starts struggling. None of them need a rewrite.
1. Measure event loop delay before you guess
Node runs your JavaScript on one main thread. If one request does heavy synchronous work, every other request waits. CPU charts won't always show this, so measure the event loop directly. Node ships a histogram for exactly this in perf_hooks:
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
// values are in nanoseconds
console.log({
p50ms: h.percentile(50) / 1e6,
p99ms: h.percentile(99) / 1e6,
maxms: h.max / 1e6,
});
h.reset();
}, 10_000);
If p99 delay sits in the tens or hundreds of milliseconds, something synchronous is hogging the thread. Typical culprits are large JSON.parse/JSON.stringify calls, synchronous crypto, big regexes, image work, and loops over thousands of records inside a request handler.
2. Move CPU-heavy work off the main thread
Once you know what blocks, move it. For CPU-bound jobs inside the same process, worker_threads keeps the event loop free:
import { Worker } from 'node:worker_threads';
export function runReport(input) {
return new Promise((resolve, reject) => {
const w = new Worker(new URL('./report-worker.js', import.meta.url), {
workerData: input,
});
w.once('message', resolve);
w.once('error', reject);
});
}
In production, use a small worker pool (for example Piscina) rather than creating a worker per request. If the work doesn't need to finish before you respond, the next fix is usually better.
3. Put slow work in a queue
Sending emails, generating PDFs, calling a slow third-party API, resizing images: none of these need to happen while the user waits. Accept the request, put a job on a queue, return 202 Accepted, and let workers handle it.
With BullMQ and Redis, the producer side is short:
import { Queue } from 'bullmq';
const reports = new Queue('reports', { connection: { host: 'redis', port: 6379 } });
app.post('/reports', async (req, res) => {
const job = await reports.add('build', { userId: req.user.id }, {
attempts: 3,
backoff: { type: 'exponential', delay: 2000 },
});
res.status(202).json({ jobId: job.id });
});
You also get retries and a clear view of what failed, instead of losing work when a request times out.
4. Size your database pool and set timeouts
A very common cause of "random" slowness is requests queueing for a database connection. With pg, the default pool size is 10. Under load, request number 11 waits until a connection frees up. And if a query hangs, it holds that connection indefinitely.
import pg from 'pg';
export const pool = new pg.Pool({
max: 20, // match what your DB can actually handle
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000, // fail fast instead of queueing forever
statement_timeout: 5_000, // kill runaway queries
});
Raise max only after checking the database's own connection limit, and remember it is per process. Four instances with max: 20 means up to 80 connections.
5. Cache the reads that don't change every second
Many APIs answer the same question thousands of times: a product list, a settings object, a user's permissions. A short-lived Redis cache in front of those reads takes load off the database and makes responses predictable (this example uses the ioredis client):
async function getProduct(id) {
const key = `product:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const { rows } = await pool.query('SELECT * FROM products WHERE id = $1', [id]);
await redis.set(key, JSON.stringify(rows[0]), 'EX', 60);
return rows[0];
}
Keep the TTL short at first and add explicit invalidation on writes. A stale cache is a worse bug than a slow endpoint.
6. Put timeouts on every outbound call
If your API calls another service and that service hangs, your requests hang with it. They pile up until memory or connections run out. Node's built-in fetch accepts an abort signal, so there is no excuse not to set a timeout:
const res = await fetch('https://partner.example.com/rates', {
signal: AbortSignal.timeout(3000),
});
Pair that with a sensible fallback (a cached value, a partial response, or a clear error), and one slow partner can no longer take your whole API down.
Then scale out
After the event loop is clear, slow work is queued and the pools are sized, adding instances behind a load balancer, or using the cluster module or your container platform's replicas, actually scales linearly. Before that, you are mostly multiplying the same bottleneck.
A short checklist
- Event loop delay p99 is measured and alerting
- No CPU-heavy work in request handlers
- Anything that can wait goes through a queue with retries
- DB pool sized against the database's real limit, with connection and statement timeouts
- Hot reads cached with a short TTL and invalidated on write
- Every outbound HTTP call has a timeout and a fallback
This is the checklist our team starts with when we pick up a back end that is struggling under load. If you need extra hands for this kind of work, we have Node.js developers available to join your team.
Disclosure: I work at EchoInnovate IT, a software development company with teams in the USA and India.
What is the most surprising Node.js bottleneck you've tracked down? I'd like to hear it in the comments.
Top comments (0)