Adaptive Load Shedding in Node.js: Protecting Systems Under Sudden Spikes
When incoming request volume spikes 10x, standard autoscaling is too slow to prevent node saturation. How we implemented latency-based admission control and event-loop lag monitoring to keep p99 stable without cascading crashes.
Horizontal Pod Autoscaling (HPA) works well for predictable, gradual traffic growth. When traffic multiplies by ten in two seconds — a breaking news push, a flash sale, or a retry storm — autoscaling is useless. New containers take 30 to 90 seconds to pull, bootstrap, and pass health checks. By that time, the existing instances have already exhausted memory, locked their event loops, and failed health probes, triggering a catastrophic cascading failure across the cluster.
The only reliable defense against sudden spikes is admission control at the process edge: load shedding.
The Failure Mode of Node.js Under Saturation
In Node.js, asynchronous I/O runs on a single event loop. When inbound connections saturate the process, incoming requests sit in the OS socket backlog and V8 heap queue. As concurrency grows:
- Garbage collection (GC) triggers more frequently to reclaim short-lived request contexts.
- GC pauses block the event loop.
- Event loop lag skyrockets from 2ms to 1,500ms.
- Client requests time out at the gateway (e.g., 5 seconds), but Node.js continues processing the orphaned work anyway, burning CPU cycles on responses that nobody will ever receive.
This is the death spiral. To survive, a service must reject requests immediately as soon as internal capacity degrades, returning HTTP 503 with a Retry-After header before any CPU or memory is allocated.
Measuring What Matters: Event Loop Delay
CPU percentage reported by the OS is a lagging indicator. By the time os.loadavg() or process.cpuUsage() spikes, the process is already compromised.
The true ground truth in Node.js is event-loop delay, measured with perf_hooks.monitorEventLoopDelay:
import { monitorEventLoopDelay } from 'node:perf_hooks';
// Sample event-loop lag with 10ms resolution
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
export function getEventLoopLagP99(): number {
// Convert nanoseconds to milliseconds
return histogram.percentile(99) / 1e6;
}
Under normal load, p99 lag stays below 15ms. If p99 exceeds 70ms, the process is falling behind. If it exceeds 150ms, any further queued work will breach consumer SLAs.
Implementing the Admission Controller
Rather than a static concurrency cap (which fails to account for varying query weights), we implement an adaptive controller based on CoDel (Controlled Delay):
import type { IncomingMessage, ServerResponse } from 'node:http';
interface ShedderOptions {
maxLagMs: number;
minConcurrency: number;
}
export class AdaptiveLoadShedder {
private activeRequests = 0;
constructor(private readonly options: ShedderOptions = { maxLagMs: 80, minConcurrency: 10 }) {}
public shouldShed(): boolean {
// Always permit minimal baseline concurrency for healthchecks and admin
if (this.activeRequests < this.options.minConcurrency) {
return false;
}
const p99Lag = getEventLoopLagP99();
return p99Lag > this.options.maxLagMs;
}
public wrap(handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>) {
return async (req: IncomingMessage, res: ServerResponse) => {
if (this.shouldShed()) {
res.statusCode = 503;
res.setHeader('Retry-After', '2');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
error: 'Overloaded',
message: 'Server is shedding load to protect availability. Please retry shortly.',
}));
return;
}
this.activeRequests++;
try {
await handler(req, res);
} finally {
this.activeRequests--;
}
};
}
}
The Architectural Rules That Make It Work
- Reject before parsing the body. Dropping a request after reading a 2 MB multipart payload has already consumed network and memory bandwidth. Drop it in the first middleware layer.
- Exempt health probes. If your
/api/healthprobe gets shed, Kubernetes will mark the container dead and restart it, accelerating the cascade. Liveness checks must bypass the shedder. - Set
Retry-Afterwith jitter. If 5,000 clients receive HTTP 503 simultaneously and all retry at second 3.0, you create a synchronized resonance spike. Upstream proxies and clients must randomize their retry intervals. - Fast failure is a feature, not a bug. Delivering 80% of transactions with 45ms latency while shedding 20% with immediate 503s is infinitely superior to dropping 100% of transactions through connection timeouts.
A resilient system does not promise unlimited throughput; it guarantees bounded latency and graceful degradation under extreme stress.
- nodejs
- performance
- distributed-systems
- architecture
Get the next one by email
Occasional, and only when there is something worth sending.
Keep reading
Algorithmic Deception and Islamic Jurisprudence: Building Software with Amanah
Dark patterns, coercive renewal loops, unearned fees, and deceptive telemetry. How classical Fiqh principles of Gharar, Riba, and Amanah directly govern honest software engineering and digital business ethics.
সফটওয়্যার ইঞ্জিনিয়ারিংয়ে আমানত ও ইসলামিক নীতিশাস্ত্র: অ্যালগরিদমিক প্রতারণা পরিহারের বিধান
ডার্ক প্যাটার্ন, জোরপূর্বক সাবস্ক্রিপশন নবায়ন, লুক্কায়িত ফি এবং অনিচ্ছাকৃত ডেটা ট্র্যাকিং—ইসলামিক ফিকাহর মূলনীতি (গারার, রিবাহ, আমানত) কীভাবে ডিজিটাল প্রোডাক্ট ও কোডিং নীতিকে সংজ্ঞায়িত করে।