Intermediate LevelNode JS
How does configuring http.Agent keep-alive connection pooling prevent TCP handshake latency under high load?
❓ Interview Prompt: By default, Node HTTP client opens and closes a new TCP connection for every request! Use new http.Agent({ keepAlive: true, maxSockets: 50 }). Reuses open TCP/TLS sockets across requests, dropping latency by 50%.
By default, Node.js HTTP clients close TCP sockets after every request. Enabling 'keepAlive' reuses open sockets across HTTP requests:
Benefits:
•
Eliminates repetitive TCP 3-way handshake and TLS negotiation latency on outbound HTTP calls!
•
Reduces latency by 50% under microservice load.
Code Implementation Example
javascript
import http from 'node:http';
// Reusable HTTP Keep-Alive Connection Pool
const agent = new http.Agent({
keepAlive: true,
maxSockets: 50,
keepAliveMsecs: 10000
});
http.get('http://api.internal/data', { agent }, (res) => {
// Reuses socket for subsequent requests!
});💡Configuring Keep-Alive connection pooling on http.Agent.
🎯 Interview Key Takeaway
Configure http.Agent with keepAlive: true to reuse open TCP sockets and eliminate request handshake latency.
#http.Agent#keepAlive#Connection Pooling#Networking#Intermediate
Back to all Node JS Questions→