Part 03 · Web এর ভাষা
Keep-Alive and Connection Reuse
প্রতিটা request এ নতুন connection খোলা কেন costly, আর reuse কীভাবে বাঁচায়।
⏱ 1 ঘণ্টা · Station 34 / 153
The payment API that was "slow"
তোমার checkout service প্রতিটা order এ একটা payment provider এর API call করে। Provider বলে response আসবে 20 ms এ। কিন্তু তোমার log বলছে প্রতিটা call এ লাগছে 120 ms। তুমি ticket খুললে। Provider উত্তর দিলো: "আমাদের server time 18 ms। আপনারা কি connection reuse করছেন?"
করছিলে না। তোমার code প্রতিটা call এ নতুন একটা HTTP client বানাতো। ফলে প্রতিটা call এ আগে DNS, তারপর TCP handshake, তারপর TLS handshake হতো। এরপর গিয়ে প্রথম byte যেত। কাজ শেষে connection টা ফেলে দেওয়া হতো। মানে প্রতিটা request এর 100 ms যাচ্ছিল শুধু setup এ, আসল কাজে না।
HTTP client যা যা করে, তার মধ্যে সবচেয়ে expensive হলো connection খোলা (Module 2 মনে করো: TCP তে একটা round trip, TLS এ আরেকটা)। Keep-alive মানে response এর পর connection বন্ধ না করা, যাতে পরের request সরাসরি চলে যেতে পারে। Backend এ এটা সবচেয়ে সস্তা আর সবচেয়ে বড় performance win গুলোর একটা। আবার idle connection চুপচাপ মরে গেলে অদ্ভুত কিছু bug ও এখান থেকেই আসে।
The problem: setup costs more than the work
| Step | Cost | প্রতিটা নতুন connection এ লাগে? |
|---|---|---|
| DNS lookup | 0-50 ms (প্রায়ই cache থাকে) | মাঝে মাঝে |
| TCP handshake | 1 round trip | হ্যাঁ |
| TLS 1.3 handshake | 1 round trip + দুই পাশেই crypto এর CPU | হ্যাঁ |
| TCP slow start | প্রথম কয়েকটা round trip এ data যায় কম | হ্যাঁ |
| আসল request আর response | 1 round trip | এটাই কাজের অংশ |
ধরো round trip 50 ms। তাহলে নতুন একটা HTTPS connection এ request বের হওয়ার আগেই প্রায় 100 ms চলে যায়। ছোট একটা API call এ লাগে আরো 50 ms। মানে সময়ের দুই ভাগই overhead। আর server এমন TLS handshake এ CPU খরচ করছে, যেটার দরকারই ছিল না।
Think of a phone call
তোমার বন্ধুকে পাঁচটা প্রশ্ন করতে হবে।
- Keep-alive ছাড়া: call দিলে, ধরার জন্য অপেক্ষা করলে, hello বললে, একটা প্রশ্ন করলে, রেখে দিলে। দ্বিতীয় প্রশ্নের জন্য আবার call। এভাবে পাঁচবার।
- Keep-alive সহ: একবার call, একবার hello, পাঁচটা প্রশ্নই করে ফেললে। কাজ শেষ হলে (বা এক মিনিট কেউ কিছু না বললে) রেখে দিলে।
প্রশ্নগুলোতে দুই ক্ষেত্রেই একই সময় লাগে। Call দেওয়া আর hello বলাটা পুরোটাই waste। আর line খুলে রেখে এক ঘণ্টা চুপ থাকলে phone company হয়তো না জানিয়েই line কেটে দেবে। পরে কথা বলতে গেলে দেখবে ওপাশে কেউ নেই।
Analogy টা কোথায় খাটে না। Phone line এ একটাই conversation। কিন্তু HTTP client সাধারণত প্রতিটা host এর জন্য খোলা connection এর একটা pool রাখে। Request আসলে pool থেকে একটা connection দেয়, কাজ শেষে ফেরত নেয়। আরেকটা পার্থক্য: call কেটে গেলে তুমি টের পাও, কিন্তু মরা TCP connection অনেক সময় use করতে না যাওয়া পর্যন্ত বোঝাই যায় না।
The building blocks
- HTTP/1.1 এ connection default ভাবেই খোলা থাকে। Response এর পর connection পরের request এর জন্য খোলা থাকে, যদি না কোনো পাশ
Connection: closeপাঠায়। (HTTP/1.0 এ default ছিল বন্ধ করা; খোলা রাখতে চাইলেConnection: keep-aliveপাঠাতে হতো।) - Framing এর কারণেই এটা সম্ভব। একটা response কোথায় শেষ, client বোঝে
Content-Lengthবা chunked encoding দেখে (lesson 1)। তাই একই byte stream এ পরের request পাঠাতে পারে। - একটা HTTP/1.1 connection এ request গুলো পালা করে যায়। একটা request, একটা response, তারপর পরের request। একসাথে কয়েকটা request চালাতে চাইলে client কয়েকটা connection খোলে (lesson 9)। HTTP/2 একটা connection এর ভেতরেই multiplex করে।
- Connection pool। HTTP client প্রতিটা host (scheme + host + port) এর জন্য idle connection রেখে দেয় আর reuse করে। সাধারণ setting গুলো: প্রতি host এ maximum connection, maximum idle connection, আর একটা idle connection কতক্ষণ রাখা হবে।
- দুই পাশেই idle timeout। কিছুক্ষণ idle থাকলে server connection বন্ধ করে দেয় (nginx এর default keep-alive timeout 75 s; অনেক load balancer এ 60 s)। NAT device আর firewall ও idle entry ফেলে দেয় (Module 2, lesson 12)। তাই client এর উচিত server এর আগেই idle connection বন্ধ করা।
- Stale connection। ধরো server একটা idle connection বন্ধ করছে, আর ঠিক সেই মুহূর্তে client ওই connection এ request পাঠালো। Request fail করবে (
connection reset,EOF)। ভালো client এমন হলে idempotent request একবার নতুন connection এ retry করে। - Server এর দিকের limit। প্রতিটা খোলা connection memory আর একটা file descriptor নেয়। তাই server একসাথে কতগুলো connection, আর প্রতি connection এ কতগুলো request, সেটার limit রাখে। Load balance করার জন্য অনেকদিনের পুরনো connection বন্ধও করে দিতে পারে।
- Reuse করতে হলে একটাই long-lived client লাগবে। বেশিরভাগ language এ pool টা থাকে HTTP client object এর ভেতরে। প্রতি request এ নতুন client বানানো মানে নতুন pool বানানো। মানে কোনো reuse ই হচ্ছে না।
একটা service একই data centre এর আরেকটা service কে HTTPS এ প্রতি second এ 1,000টা call করে (RTT 0.5 ms)। প্রতিটা call এ নতুন HTTP client বানায়। Pool সহ একটা shared client এ গেলে কী হবে?
Behind the scenes: a pooled client, from first call to idle timeout
একটা host, একটা pool, অনেক request
ধাপ 1/5 প্রথম request
Pool এ এখনো api.pay.com এর কোনো connection নেই। তাই dial করে: DNS, TCP handshake, TLS handshake। Request বের হওয়ার আগে প্রায় 2টা round trip।
- pool
- 0 idle
- round_trips
- 3
The picture to keep in your head
একটা connection হলো একটা দামি pipe: বানাতে খরচ বেশি (handshake), use করতে সস্তা (প্রতি request এ শুধু একটা round trip)।
- একবার বানাও, বারবার use করো: প্রতিটা service এর জন্য একটা long-lived client, প্রতি host এ একটা pool।
- Use শেষে pipe ফেরত দাও: পুরো response পড়ে ফেলো, যাতে connection pool এ ফিরতে পারে।
- ওপাশের আগেই idle pipe অবসরে পাঠাও: client এর idle timeout < server আর NAT এর timeout।
- মাঝে মাঝে একটা মরা pipe পাবে, ধরে রাখো: idempotent request একবার নতুন connection এ retry করো।
Try it: does this reuse connections?
Reuse হচ্ছে, নাকি নতুন করে বানানো?
def handler(): client = HttpClient(); client.get(...)
Code from first principles
ছোট্ট একটা HTTP/1.1 server, যেটা গুনে রাখে কতগুলো connection accept করলো আর প্রতিটা connection এ কয়টা request আসলো। একটা client পাঁচটা request দুইবার পাঠায়। প্রথমবার প্রতিটার জন্য নতুন connection (Connection: close সহ)। দ্বিতীয়বার একটাই kept-alive connection এ, আর প্রতিটা response কোথায় শেষ সেটা বোঝে Content-Length দেখে। শেষ লাইনে connection এর সংখ্যাকে 50 ms এর network এ সময়ে বদলে দেখানো হয়েছে।
package main
import (
"bufio"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
)
// The server counts how many TCP connections it accepted and how many requests came on each.
var (
mu sync.Mutex
perConn []int
)
func serve(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
perConn = append(perConn, 0)
id := len(perConn) - 1
mu.Unlock()
r := bufio.NewReader(conn)
for { // keep-alive: keep reading requests on this connection until the client closes it
head := ""
for !strings.HasSuffix(head, "\r\n\r\n") {
line, err := r.ReadString('\n')
if err != nil {
break
}
head += line
}
if head == "" {
break // the client closed the connection
}
mu.Lock()
perConn[id]++
mu.Unlock()
body := "ok"
fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s", len(body), body)
if strings.Contains(head, "Connection: close") {
break
}
}
conn.Close()
}
}
// readResponse reads one response, using Content-Length to know where it ends.
func readResponse(r *bufio.Reader) string {
length := 0
for {
line, _ := r.ReadString('\n')
if line == "\r\n" {
break
}
if v, ok := strings.CutPrefix(line, "Content-Length: "); ok {
length, _ = strconv.Atoi(strings.TrimSpace(v))
}
}
body := make([]byte, length)
io.ReadFull(r, body)
return string(body)
}
func report(label string, requests int) {
mu.Lock()
defer mu.Unlock()
fmt.Printf("%s: %d requests, server accepted %d connection(s), requests per connection %v\n", label, requests, len(perConn), perConn)
perConn = nil
}
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:8096")
go serve(ln)
const n = 5
// A: a new connection for every request.
for i := 0; i < n; i++ {
conn, _ := net.Dial("tcp", "127.0.0.1:8096")
fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n", i)
readResponse(bufio.NewReader(conn))
conn.Close()
}
report("new connection each time", n)
// B: one connection, reused for every request.
conn, _ := net.Dial("tcp", "127.0.0.1:8096")
r := bufio.NewReader(conn)
for i := 0; i < n; i++ {
fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\n\r\n", i)
readResponse(r)
}
report("one kept-alive connection", n)
conn.Close()
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
rtt := 50
fmt.Printf("at %d ms RTT: new each time = %d x (2 + 1) round trips = %d ms, reused = (2 + %d) round trips = %d ms\n",
rtt, n, n*3*rtt, n, (2+n)*rtt)
}const net = require("node:net");
// The server counts how many TCP connections it accepted and how many requests came on each.
let perConn = [];
const server = net.createServer((conn) => {
perConn.push(0);
const id = perConn.length - 1;
let buf = "";
conn.on("data", (chunk) => {
buf += chunk;
let end;
// keep-alive: keep handling requests on this connection until the client closes it
while ((end = buf.indexOf("\r\n\r\n")) >= 0) {
const head = buf.slice(0, end + 4);
buf = buf.slice(end + 4);
perConn[id]++;
const body = "ok";
conn.write(`HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\n\r\n${body}`);
if (head.includes("Connection: close")) conn.end();
}
});
});
// request sends one request on conn and resolves with the body, using Content-Length to know where it ends.
function request(conn, text) {
return new Promise((resolve) => {
let buf = "";
const onData = (chunk) => {
buf += chunk;
const end = buf.indexOf("\r\n\r\n");
if (end < 0) return;
const length = Number(/Content-Length: (\d+)/.exec(buf.slice(0, end))[1]);
if (buf.length < end + 4 + length) return;
conn.off("data", onData);
resolve(buf.slice(end + 4, end + 4 + length));
};
conn.on("data", onData);
conn.write(text);
});
}
const connect = () => new Promise((resolve) => { const c = net.connect(8096, "127.0.0.1", () => resolve(c)); });
function report(label, requests) {
console.log(`${label}: ${requests} requests, server accepted ${perConn.length} connection(s), requests per connection [${perConn.join(" ")}]`);
perConn = [];
}
server.listen(8096, "127.0.0.1", async () => {
const n = 5;
// A: a new connection for every request.
for (let i = 0; i < n; i++) {
const conn = await connect();
await request(conn, `GET /item/${i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`);
conn.destroy();
}
report("new connection each time", n);
// B: one connection, reused for every request.
const conn = await connect();
for (let i = 0; i < n; i++) await request(conn, `GET /item/${i} HTTP/1.1\r\nHost: localhost\r\n\r\n`);
report("one kept-alive connection", n);
conn.destroy();
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
const rtt = 50;
console.log(`at ${rtt} ms RTT: new each time = ${n} x (2 + 1) round trips = ${n * 3 * rtt} ms, reused = (2 + ${n}) round trips = ${(2 + n) * rtt} ms`);
server.close();
});use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
// The server counts how many TCP connections it accepted and how many requests came on each.
fn serve(listener: TcpListener, per_conn: Arc<Mutex<Vec<u32>>>) {
for conn in listener.incoming() {
let mut conn = conn.unwrap();
let id = {
let mut p = per_conn.lock().unwrap();
p.push(0);
p.len() - 1
};
let mut reader = BufReader::new(conn.try_clone().unwrap());
loop {
// keep-alive: keep reading requests on this connection until the client closes it
let mut head = String::new();
while !head.ends_with("\r\n\r\n") {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
head += &line;
}
if head.is_empty() {
break; // the client closed the connection
}
per_conn.lock().unwrap()[id] += 1;
let body = "ok";
write!(conn, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", body.len(), body).unwrap();
if head.contains("Connection: close") {
break;
}
}
}
}
// read_response reads one response, using Content-Length to know where it ends.
fn read_response(reader: &mut BufReader<TcpStream>) -> String {
let mut length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if line == "\r\n" {
break;
}
if let Some(v) = line.strip_prefix("Content-Length: ") {
length = v.trim().parse().unwrap();
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
String::from_utf8(body).unwrap()
}
fn report(per_conn: &Arc<Mutex<Vec<u32>>>, label: &str, requests: u32) {
let mut p = per_conn.lock().unwrap();
let counts: Vec<String> = p.iter().map(|c| c.to_string()).collect();
println!("{label}: {requests} requests, server accepted {} connection(s), requests per connection [{}]", p.len(), counts.join(" "));
p.clear();
}
fn main() {
let per_conn = Arc::new(Mutex::new(Vec::new()));
let listener = TcpListener::bind("127.0.0.1:8096").unwrap();
let shared = Arc::clone(&per_conn);
thread::spawn(move || serve(listener, shared));
let n = 5;
// A: a new connection for every request.
for i in 0..n {
let mut conn = TcpStream::connect("127.0.0.1:8096").unwrap();
write!(conn, "GET /item/{i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
read_response(&mut BufReader::new(conn));
}
report(&per_conn, "new connection each time", n);
// B: one connection, reused for every request.
let mut conn = TcpStream::connect("127.0.0.1:8096").unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
for i in 0..n {
write!(conn, "GET /item/{i} HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
read_response(&mut reader);
}
report(&per_conn, "one kept-alive connection", n);
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
let rtt = 50;
println!(
"at {rtt} ms RTT: new each time = {n} x (2 + 1) round trips = {} ms, reused = (2 + {n}) round trips = {} ms",
n * 3 * rtt,
(2 + n) * rtt
);
}import socket
import threading
# The server counts how many TCP connections it accepted and how many requests came on each.
lock = threading.Lock()
per_conn = []
def serve(listener):
while True:
conn, _ = listener.accept()
with lock:
per_conn.append(0)
cid = len(per_conn) - 1
reader = conn.makefile("rb")
while True: # keep-alive: keep reading requests on this connection until the client closes it
head = b""
while not head.endswith(b"\r\n\r\n"):
line = reader.readline()
if not line:
break
head += line
if not head:
break # the client closed the connection
with lock:
per_conn[cid] += 1
body = b"ok"
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body))
if b"Connection: close" in head:
break
conn.close()
def read_response(reader):
"""Read one response, using Content-Length to know where it ends."""
length = 0
while (line := reader.readline()) != b"\r\n":
if line.startswith(b"Content-Length: "):
length = int(line.split(b": ")[1])
return reader.read(length)
def report(label, requests):
global per_conn
with lock:
counts = " ".join(str(c) for c in per_conn)
print(f"{label}: {requests} requests, server accepted {len(per_conn)} connection(s), requests per connection [{counts}]")
per_conn = []
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 8096))
listener.listen()
threading.Thread(target=serve, args=(listener,), daemon=True).start()
N = 5
# A: a new connection for every request.
for i in range(N):
conn = socket.create_connection(("127.0.0.1", 8096))
conn.sendall(f"GET /item/{i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".encode())
read_response(conn.makefile("rb"))
conn.close()
report("new connection each time", N)
# B: one connection, reused for every request.
conn = socket.create_connection(("127.0.0.1", 8096))
reader = conn.makefile("rb")
for i in range(N):
conn.sendall(f"GET /item/{i} HTTP/1.1\r\nHost: localhost\r\n\r\n".encode())
read_response(reader)
report("one kept-alive connection", N)
conn.close()
# What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
rtt = 50
print(f"at {rtt} ms RTT: new each time = {N} x (2 + 1) round trips = {N * 3 * rtt} ms, reused = (2 + {N}) round trips = {(2 + N) * rtt} ms")import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
// The server counts how many TCP connections it accepted and how many requests came on each.
static final List<Integer> perConn = new ArrayList<>();
static void serve(ServerSocket listener) {
while (true) {
try (Socket conn = listener.accept()) {
int id;
synchronized (perConn) { perConn.add(0); id = perConn.size() - 1; }
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
OutputStream out = conn.getOutputStream();
while (true) { // keep-alive: keep reading requests on this connection until the client closes it
StringBuilder head = new StringBuilder();
String line;
while ((line = reader.readLine()) != null && !line.isEmpty()) head.append(line).append("\r\n");
if (line == null) break; // the client closed the connection
synchronized (perConn) { perConn.set(id, perConn.get(id) + 1); }
String body = "ok";
out.write(("HTTP/1.1 200 OK\r\nContent-Length: " + body.length() + "\r\n\r\n" + body).getBytes(StandardCharsets.UTF_8));
out.flush();
if (head.toString().contains("Connection: close")) break;
}
} catch (IOException e) {
return;
}
}
}
// readResponse reads one response, using Content-Length to know where it ends.
static String readResponse(InputStream in) throws IOException {
int length = 0;
while (true) {
StringBuilder line = new StringBuilder();
int c;
while ((c = in.read()) != '\n') line.append((char) c);
String l = line.toString().trim();
if (l.isEmpty()) break;
if (l.startsWith("Content-Length: ")) length = Integer.parseInt(l.substring(16));
}
return new String(in.readNBytes(length), StandardCharsets.UTF_8);
}
static void report(String label, int requests) {
synchronized (perConn) {
StringJoiner counts = new StringJoiner(" ");
for (int c : perConn) counts.add(String.valueOf(c));
System.out.println(label + ": " + requests + " requests, server accepted " + perConn.size() + " connection(s), requests per connection [" + counts + "]");
perConn.clear();
}
}
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(8096, 50, InetAddress.getByName("127.0.0.1"));
Thread server = new Thread(() -> serve(listener));
server.setDaemon(true);
server.start();
int n = 5;
// A: a new connection for every request.
for (int i = 0; i < n; i++) {
try (Socket conn = new Socket("127.0.0.1", 8096)) {
conn.getOutputStream().write(("GET /item/" + i + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));
readResponse(conn.getInputStream());
}
}
report("new connection each time", n);
// B: one connection, reused for every request.
try (Socket conn = new Socket("127.0.0.1", 8096)) {
InputStream in = new BufferedInputStream(conn.getInputStream());
for (int i = 0; i < n; i++) {
conn.getOutputStream().write(("GET /item/" + i + " HTTP/1.1\r\nHost: localhost\r\n\r\n").getBytes(StandardCharsets.UTF_8));
readResponse(in);
}
report("one kept-alive connection", n);
}
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
int rtt = 50;
System.out.printf("at %d ms RTT: new each time = %d x (2 + 1) round trips = %d ms, reused = (2 + %d) round trips = %d ms%n",
rtt, n, n * 3 * rtt, n, (2 + n) * rtt);
}
}Output (পাঁচটা language এই একই):
new connection each time: 5 requests, server accepted 5 connection(s), requests per connection [1 1 1 1 1]
one kept-alive connection: 5 requests, server accepted 1 connection(s), requests per connection [5]
at 50 ms RTT: new each time = 5 x (2 + 1) round trips = 750 ms, reused = (2 + 5) round trips = 350 ms
Output টা পড়ি:
- প্রতিবার নতুন connection: 5টা connection, প্রতিটায় 1টা request। পাঁচটা TCP handshake। আসল internet এ হলে সাথে পাঁচটা TLS handshake ও।
- Kept alive: 1টা connection, 5টা request। Client connection বন্ধ না করা পর্যন্ত server এর loop একই connection এ request পড়েই গেছে।
- Client connection reuse করতে পেরেছে শুধু
Content-Lengthএর কারণে। সে জানতো response ঠিক 2 byte। তাই এর পরের byte গুলো পরের response এর। - 50 ms RTT তে একই পাঁচটা request এ 750 ms বনাম 350 ms। কাজ একদম একই। বদলেছে শুধু setup।
এবার একটা আসল server এ একই জিনিস, curl এর num_connects দিয়ে মাপা (ওই transfer এর জন্য কয়টা নতুন connection খুলেছে):
$ curl -s -o /dev/null -o /dev/null -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/ https://example.com/ https://example.com/
new connections 1, tls done at 0.099458s, total 0.107765s
new connections 0, tls done at 0.000000s, total 0.006453s
new connections 0, tls done at 0.000000s, total 0.008123s
$ for i in 1 2 3; do curl -s -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/; done
new connections 1, tls done at 0.023686s, total 0.031295s
new connections 1, tls done at 0.019792s, total 0.029106s
new connections 1, tls done at 0.021939s, total 0.031011s
- একটা curl process, তিনটা URL: প্রথম transfer একটা connection খুলেছে (এই cold run এ DNS, TCP, TLS এ লেগেছে 99 ms)। পরের দুইটা সেটাই reuse করেছে: 0টা নতুন connection, প্রতিটায় মোটামুটি 6-8 ms।
- তিনটা আলাদা curl process: প্রতিটা খালি pool সহ নতুন client। তাই প্রতিটা request এ নতুন connection খুলেছে, আর লেগেছে প্রায় 30 ms। Reuse করা একটার চেয়ে চারগুণ বেশি।
Real engineering
- প্রতিটা downstream service এর জন্য একটা HTTP client, startup এ বানানো। Go এর
http.Client, Python এরrequests.Sessionবাhttpx.Client, Node এরundiciagent বাkeepAlive: trueagent, Java এরHttpClient। এটা সব request আর thread এর মধ্যে share করো। - Response এর কাজ সবসময় শেষ করো। Body শেষ পর্যন্ত পড়ো (বা close করো)। না পড়া body connection কে pool এর বাইরে আটকে রাখে।
- Pool tune করো: প্রতি host এ max connection (peak concurrency এর জন্য যথেষ্ট, কিন্তু unlimited না), কয়টা idle connection রাখবে, আর idle timeout server আর load balancer এর চেয়ে কম।
- Connection error এ idempotent request একবার retry করো। Pool এ stale connection থাকা normal। নতুন connection এ একবার retry করলেই এটা ঢাকা পড়ে যায়। POST auto-retry করবে না (lesson 4)।
- Database আর Redis এও একই idea। Connection pool use করো। Size ঠিক করো তোমার concurrency আর database এর limit দেখে (Postgres শত শত connection সামলায়, হাজার হাজার না; PgBouncer এর মতো pooler কাজে লাগে)।
- Deploy এর সময় draining। Server বন্ধ করার সময় নতুন request নেওয়া বন্ধ করো, আর keep-alive connection গুলো gracefully বন্ধ করো (শেষ response গুলোতে
Connection: closeপাঠাও)। তাহলে client গুলো error ছাড়াই অন্য server এ চলে যাবে।
When it breaks
একটা failure বেছে নাও
read tcp: connection reset by peer (first request after idle)
Think before you read on
Keep-alive সময় বাঁচায় connection খোলা রেখে। তাহলে একটা server ইচ্ছা করে একদম ঠিকঠাক একটা connection কেন বন্ধ করবে, ধরো 1,000টা request বা 10 মিনিট পর?
Reveal
Load ছড়িয়ে দেওয়ার জন্য। Load balancer server বাছে connection খোলার সময়, প্রতিটা request এ না। একটা client যদি একটাই long-lived connection রাখে, তার সব request চিরকাল একই server এ যাবে। ফলে scale up এর পর নতুন server গুলো বসে থাকে, আর পুরনোগুলো গরম হয়েই থাকে। মাঝে মাঝে connection বন্ধ করলে client কে আবার connect করতে হয়, আর প্রতিবার connect এর সময় আবার balance হয়। এতে server leak হওয়া memory ফেরত পায়, TLS certificate rotate করতে পারে, আর deploy এর আগে পরিষ্কারভাবে drain করতে পারে। খরচ হলো প্রতি 1,000টা request এ একটা handshake, যেটা খুবই সামান্য।
Check yourself
1. HTTP keep-alive কী, আর এটা কী বাঁচায়?
Answer
Response এর পর TCP (আর TLS) connection খোলা রাখা, যাতে পরের request সেটা reuse করতে পারে। প্রথমটার পরের প্রতিটা request এ TCP আর TLS handshake (round trip আর CPU) আর TCP slow start বাঁচে।
2. Kept-alive connection এ client কীভাবে বোঝে একটা response কোথায় শেষ?
Answer
Response এর framing দেখে। Content-Length বলে দেয় body তে ঠিক কত byte পড়তে হবে, অথবা chunked encoding শেষটা চিহ্নিত করে। এগুলো না থাকলে শেষ বোঝার একমাত্র উপায় হতো connection বন্ধ হওয়া।
3. Client এর idle timeout server এর চেয়ে কম রাখা উচিত কেন?
Answer
যাতে server বন্ধ করার আগেই client idle connection অবসরে পাঠায়। নাহলে client এমন connection এ request পাঠাতে পারে যেটা server এইমাত্র বন্ধ করেছে, আর request টা reset খেয়ে fail করবে।
4. প্রতি request এ নতুন HTTP client বানালে keep-alive কেন কাজ করে না?
Answer
Connection pool থাকে client এর ভেতরে। নতুন client এর pool খালি। তাই প্রতিটা request নতুন connection খোলে, আর পুরনোটা ফেলে দেওয়া হয়।
Your challenge: build a tiny pool
Code টাকে একটা connection pool দিয়ে বাড়াও:
get()লেখো: idle connection থাকলে সেটা দেবে, না থাকলে নতুন dial করবে। আরput(conn)লেখো, যেটা connection pool এ ফেরত রাখে।- প্রতিটা pooled connection এ একটা "last used" time রাখো, আর idle timeout দাও 3 second (আগের lesson গুলোর মতো একটা fake clock use করো, যেটা হাতে এগিয়ে দেবে)।
get()কে expired connection ফেলে দিতে হবে। - 3টা request পাঠাও, clock 5 second এগিয়ে দাও, তারপর আরো 2টা পাঠাও।
Run করার আগে predict করো: server বলবে কয়টা connection accept করেছে, আর প্রতিটায় কয়টা request?
তুমি সফল যখন server বলবে 2টা connection, request [3 2], তোমার pool কখনো expired connection দেবে না, আর idle timeout 10 second করলে report বদলে হবে 1টা connection, [5]।
The mental model
একটা connection বানাতে খরচ বেশি (DNS, TCP, TLS, slow start), use করতে সস্তা। তাই HTTP connection খোলা রাখে, আর client প্রতি host এ একটা pool রাখে। Framing (Content-Length বা chunked) এর কারণেই কয়েকটা request একটা connection share করতে পারে। একটা long-lived client use করো, response সবসময় পুরো পড়ো, client এর idle timeout server আর network এর চেয়ে কম রাখো, stale connection এ idempotent request একবার retry করো, আর load balanced রাখতে server কে মাঝে মাঝে connection recycle করতে দাও।
Station stamp
Chapter শেষ করো
পড়া শেষ হলে Complete চাপো, progress save হবে। XP শুধু Pro তে — Pro থাকলে এই chapter এ +10 XP পেতে।
Pro নিয়ে XP পাও →