惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage
The Practica · 2026-05-16 · via The Practical Developer

Your memory graph is flat. CPU is flat. But ss -s shows TCP connections climbing every Tuesday at 9 a.m., and eventually new clients get ECONNREFUSED while the pod still has plenty of RAM. The trigger is not a memory leak. It is a connection leak, and the root cause is almost always the same: a client that opens an HTTP connection, sends part of a request, and goes silent. Node.js waits. By default, it waits forever.

The Node.js HTTP server is fast, but its defaults are from an era where the internet was smaller and friendlier. server.timeout is 0, meaning a socket can sit idle indefinitely. server.requestTimeout did not exist before Node.js 18, and even now the default is measured in minutes, not seconds. server.headersTimeout is 60 seconds, which is generous to a fault. And server.keepAliveTimeout is 5 seconds, which seems conservative until your load balancer expects 60.

This post is the three server-side timeout values you actually need, what each one guards against, and the production-ready server setup that turns a slow client from a resource-eating ghost into a fast, clean error.

The shape of the failure

You notice it first as connection exhaustion. Under ss -s or netstat the ESTABLISHED counter climbs into the thousands. The Node.js process RSS stays flat because the kernel, not your application, holds the socket state. But the event loop latency spikes because the TCP backlog is full. New healthy clients sit in the SYN queue until they time out on their end, or they connect and get queued behind the zombies.

Or you notice it during a deploy. Kubernetes sends SIGTERM. The old pod enters graceful shutdown. But twenty sockets are still waiting for a request body that will never arrive. The pod stays in Terminating for the full termination grace period. The new pods are ready and serving traffic. The old pods refuse to die because Node.js will not close sockets that still have “active” requests, even when those requests are never going to finish.

The trigger is almost always one of three things. A mobile app on flaky 2G that sends the headers then loses signal. A third-party integration with a broken HTTP client that opens a connection and forgets about it. Or a scraper running a slowloris-style attack that sends one header byte every 59 seconds. Node.js defaults assume every client is well-behaved and fast. Production is not.

1. headersTimeout: how long a client has to finish the request line and headers

Before any body arrives, the client must send the HTTP method, path, protocol version, and all headers. In a healthy system this takes less than a millisecond. A malicious or broken client can send one byte per minute, keeping the socket open and the parser waiting. This is a classic slowloris attack, and it works against a default Node.js server because headersTimeout is set to 60 seconds.

An attacker can keep a socket busy for a full minute by sending data just frequently enough to avoid triggering idle timeouts. With a 1024 connection limit on a small instance, that is a denial of service from a single IP address. The fix is aggressive and simple:

import http from 'node:http';

const server = http.createServer(app);
server.headersTimeout = 10_000; // 10 seconds is generous

Ten seconds is enough for a genuine client on a slow network to send a few kilobytes of headers. It is not enough for an attacker to weaponize header parsing. If you run behind a CDN or load balancer that terminates TLS and injects large headers, measure the p99 header receipt time in your logs before tightening this. But for most API services, 10 seconds is correct and 60 seconds is a liability.

One detail most teams miss: headersTimeout was added in Node.js 11. Before that, there was no built-in protection against slow header sending at all. If you are on an ancient runtime, upgrade for this feature alone.

2. requestTimeout: how long a client has to send the entire request

headersTimeout fires if the headers take too long. What about the body? Before Node.js 18, there was no built-in timeout for the total request duration including body transfer. A client could send headers immediately, then dribble the body one byte per hour, and the server would wait. Node.js 18 added requestTimeout, which covers the entire request from the first byte to the end of the body.

The default in recent Node.js versions is 300 seconds. That is five minutes. For an API that mostly accepts JSON payloads under 100 KB, five minutes is not generous, it is dangerous. A client that drops connection after sending 50% of a file upload will hold a socket and any associated worker thread for five minutes.

Set it tight at the server level and override it only on routes that genuinely need large uploads:

server.requestTimeout = 30_000; // 30 seconds for the whole request

For a file-upload endpoint that accepts 100MB videos, you might bump that specific route:

app.post('/upload', (req, res) => {
  req.socket.server.requestTimeout = 120_000;
  // ... handle upload
});

But the global default should protect the 95% of your API that accepts small JSON. Do not let the exception become the default.

3. keepAliveTimeout: the idle window between requests on a persistent connection

keepAliveTimeout is not about a single request. It is about the silence between two requests on the same TCP connection. When a client finishes a request and keeps the connection open for reuse, Node.js waits keepAliveTimeout milliseconds for the next request before destroying the socket. The default is 5 seconds.

Five seconds sounds reasonable, but it is the single most common source of “random” 502 errors during deploys. Here is why. Your load balancer (AWS ALB, Nginx, HAProxy) also has a keepalive idle timeout. If the load balancer’s timeout is longer than Node.js’s timeout, the following race happens:

  1. Node.js closes the idle socket after 5 seconds.
  2. The load balancer has the same socket in its pool and sends a new request on it a fraction of a second later.
  3. The request hits a closed socket. The load balancer returns 502 to the client.
  4. The client retries and usually succeeds, but your error rate graph now has a baseline of 0.1% mysterious 502s that correlate with low-traffic periods, not high load.

The fix is to make Node.js’s keepAliveTimeout slightly longer than your load balancer’s idle timeout, not shorter. If your ALB is set to 60 seconds, set Node.js to 65 seconds:

server.keepAliveTimeout = 65_000;

This seems backwards. Most teams set the backend timeout shorter than the proxy timeout to “give the proxy a chance to retry.” That logic does not apply to idle keepalive sockets. The proxy cannot retry a request that was already sent on a socket the backend just closed. The proxy only knows the socket is dead after the request fails. Making the backend timeout longer gives the proxy time to reuse the connection safely.

If you do not know your load balancer’s timeout, find it. For AWS ALB it is 60 seconds by default. For Nginx with keepalive_timeout, check your config. Then add 5 seconds and set Node.js accordingly.

4. timeout: the socket inactivity safety net (and its limits)

server.timeout is the oldest of the four, and the most misunderstood. It sets the number of milliseconds of inactivity before a socket is presumed to have timed out. Default is 0, meaning disabled.

The key word is “inactivity.” If a client sends one byte every 5 seconds, the socket is not idle. timeout will not fire. This means timeout alone does not stop a slow body upload or a slowloris attack. It only catches sockets where nothing is sent at all, which headersTimeout and requestTimeout already handle more comprehensively.

Still, it is worth setting as a global safety net for connections that somehow slip past the other timers, or for protocols where the other timers do not apply:

server.timeout = 120_000; // 2 minutes of absolute silence

Do not rely on timeout as your primary defense. Rely on headersTimeout and requestTimeout. Use timeout as the backup plan.

The production-ready server setup

Here is the 40-line module you drop into your service. It wires the three critical timeouts plus keepAliveTimeout tuned for your load balancer:

// lib/server.js
import http from 'node:http';
import { app } from './app.js';

export function createServer() {
  const server = http.createServer(app);

  // Prevent slowloris-style header attacks
  server.headersTimeout = 10_000;

  // Prevent runaway body uploads
  server.requestTimeout = 30_000;

  // Safety net for completely idle sockets
  server.timeout = 120_000;

  // Must exceed load balancer idle timeout to avoid 502 races
  // Adjust this to (loadBalancerTimeout + 5000)
  server.keepAliveTimeout = 65_000;

  return server;
}

Start it with a deliberate graceful shutdown that respects in-flight requests but does not wait for zombies:

// index.js
import { createServer } from './lib/server.js';

const server = createServer();
const PORT = process.env.PORT ?? 3000;

server.listen(PORT, () => {
  console.log(`Listening on ${PORT}`);
});

function shutdown() {
  console.log('SIGTERM received, closing server');
  server.close(() => {
    console.log('Server closed, exiting');
    process.exit(0);
  });

  // Force exit after 30 seconds even if sockets remain
  setTimeout(() => {
    console.error('Forced exit after graceful shutdown timeout');
    process.exit(1);
  }, 30_000);
}

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

The server.close() call stops accepting new connections and waits for existing keepalive sockets to close naturally. The 30-second hard limit ensures that a pod with zombie sockets does not stay in Terminating forever. This combination is what makes Kubernetes rolling updates actually roll.

Testing it with curl

You do not need a load test to verify these settings. You need curl and the ability to send data slowly.

Test headersTimeout by sending one header byte per second:

# Send the request line, then sleep. Node should kill this after 10 seconds.
(echo -n 'GET / HTTP/1.1
'; sleep 20) | curl telnet://localhost:3000

Test requestTimeout by sending headers immediately, then a very slow body:

curl -X POST http://localhost:3000/api/data \
  -H 'Content-Type: application/json' \
  -d '{"slow": true}' \
  --limit-rate 1B/10s

With requestTimeout: 30_000, the server should close the connection after 30 seconds even though data is still trickling in.

Test keepAliveTimeout by making a request, waiting, and making another:

curl -v http://localhost:3000/health && sleep 70 && curl -v http://localhost:3000/health

The second request should open a new TCP connection because the first was closed by keepAliveTimeout at 65 seconds.

If any of these tests surprise you, your production server is currently vulnerable.

The interaction with load balancers and proxies

The timeout values above are for the Node.js server. But your Node.js server probably does not face the internet directly. It faces a load balancer, a sidecar proxy, or a CDN. Those intermediaries have their own timeouts, and they interact with yours in non-obvious ways.

Load balancer idle timeout > backend keepAliveTimeout: Causes 502s on low-traffic connections, as described above. Fix: raise keepAliveTimeout.

Load balancer request timeout < backend requestTimeout: The load balancer returns 504 to the client and may or may not close the backend connection. If it keeps the backend connection open, your Node.js handler may continue processing a request whose result nobody wants. Fix: set the load balancer request timeout slightly longer than your slowest legitimate endpoint, or implement request deadlines as described in the request deadlines post.

Proxy buffering hides backpressure: If your proxy buffers the entire response before sending it to the client, the client sees fast response times while your Node.js process is blocked waiting for the proxy to drain the buffer. This is not a timeout issue, but it makes timeout tuning harder because the metrics lie. Fix: disable proxy buffering for streaming endpoints, or account for it in your latency budgets.

The takeaway

Node.js server defaults are designed for development, not production. A server with no request timeout, a 60-second header window, and a 5-second keepalive window is a server that invites slow clients to consume resources indefinitely.

Set headersTimeout to 10 seconds to stop slowloris attacks. Set requestTimeout to 30 seconds to stop runaway uploads. Set keepAliveTimeout to slightly exceed your load balancer’s idle timeout to stop random 502s. Set timeout to 2 minutes as a last-ditch safety net.

Then test it with curl, verify it with ss -s under load, and make sure your graceful shutdown has a hard ceiling so Kubernetes can actually replace your pods.

The cost is four lines of configuration. The benefit is that the next time a client goes silent mid-request, your server gives up in seconds instead of minutes, and the sockets go back into the pool for requests that actually finish.


A note from Yojji

The difference between a service that handles a Tuesday morning traffic spike and one that melts down is often not the application code, but the boundary configuration that decides how long to wait for misbehaving clients. Tuning server timeouts, matching them to load balancer behavior, and verifying them with deliberate tests is the kind of infrastructure discipline that Yojji’s teams treat as standard practice in every production deployment.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their teams specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and the resilient backend architecture that keeps services running when clients, networks, or upstreams stop cooperating.