Summary#
TCP sets up a connection, then delivers a reliable, ordered byte stream, slowing down when the receiver or network is overloaded. UDP just sends independent packets with no setup, no retries and no ordering: faster and simpler, but the application must handle loss. QUIC runs over UDP and adds reliability, encryption and independent streams, avoiding TCP's head-of-line blocking; HTTP/3 uses it. Whatever you use, reuse connections, because each new one costs round trips.
Why It Exists#
IP only moves packets between machines, on a best-effort basis: packets can be lost, duplicated or reordered. Applications need something on top. Most want every byte delivered in order (web pages, database queries, file transfers). Others care more about freshness than completeness (a live video frame that arrives late is useless). TCP and UDP serve these two needs. This page builds on Networking Fundamentals.
How It Works#
TCP connection setup and teardown#
Before sending data, TCP performs a three-way handshake. This costs one full round trip before the first request can be sent; with TLS on top, more round trips follow (see HTTP and HTTPS).
To close, each side sends FIN and the other acknowledges it. The side that closes first waits in TIME_WAIT (often 60 seconds on Linux) so late packets do not confuse a new connection. Servers that open and close huge numbers of short connections can run out of ports because of this.
What the handshake actually sets up#
The three packets of the handshake do more than say hello. Each side picks a random initial sequence number (ISN) and learns the other's, so every later byte can be numbered and acknowledged. Random ISNs matter for security as well as correctness: if they were predictable, an attacker who is not on the path could forge packets that fit into someone else's connection. The SYN and SYN-ACK also carry options that both sides must agree on at the start, because they cannot be added later:
| Option | What it does | Why you care |
|---|---|---|
| MSS (maximum segment size) | Largest payload per segment, typically 1,460 bytes on Ethernet | Too large means fragmentation or black holes on tunnels |
| Window scale | Multiplies the 16-bit window field by up to 2^14 | Without it a receiver can advertise only 64 KB, which caps throughput on long links |
| SACK permitted | Lets the receiver report exactly which blocks arrived | Recovers from several losses in one round trip instead of one at a time |
| Timestamps | Adds a timestamp to each segment | Accurate RTT measurement and protection against wrapped sequence numbers on fast links |
The connection is state that both machines hold: sequence numbers, windows, buffers, timers and the negotiated options. That is the real cost of a connection. It is why an idle connection still uses memory, why a server can hold only so many, and why a crash on one side leaves the other holding a "half-open" connection until a timeout or keep-alive notices.
Two queues on the server. When a SYN arrives on a listening socket, the kernel puts a half-finished entry in the SYN queue and replies with a SYN-ACK. When the final ACK arrives, the connection moves to the accept queue, where it waits for the application to call accept(). Two different failures live here:
- A SYN flood sends huge numbers of SYNs from spoofed addresses and never completes them, filling the SYN queue so real users cannot connect. Linux defends with SYN cookies: when the queue is full, the server stores nothing and instead encodes the connection details into its own ISN. A genuine client's ACK carries that number back, and the server rebuilds the state from it.
- An application that is too slow to accept lets the accept queue overflow. New connections are then dropped or reset even though CPU and memory look idle. Raising the
listen()backlog and thesomaxconnlimit, or fixing the slow accept loop, solves it.
Faster setup. TCP Fast Open lets a returning client put data in the SYN itself, using a cookie from an earlier connection, which saves one round trip. It was never widely deployed on the open internet because middleboxes interfered with it. Most of its benefit is now delivered instead by TLS 1.3 session resumption and by QUIC, which are covered below.
The life of a connection, state by state#
A TCP connection moves through a fixed set of states. Most of them are invisible, but a few show up in production dashboards and ss output and tell you exactly what is wrong.
- ESTABLISHED: data flows both ways. The number of these is your real concurrent connection count.
- TIME_WAIT: the side that closed first waits for twice the maximum segment lifetime (MSL) so that stray delayed packets from this connection die out before the same address and port pair is reused, and so its final ACK can be resent if lost. Linux holds it for 60 seconds. Tens of thousands of TIME_WAIT entries on a client or proxy mean it is opening and closing connections instead of reusing them.
- CLOSE_WAIT: the peer has closed, but our application has not closed its socket. A growing CLOSE_WAIT count is almost always a bug in the application, such as a code path that forgets to close a connection after an error. These sockets never time out on their own and eventually exhaust file descriptors.
- SYN_RECEIVED piling up suggests a SYN flood or a client network that drops the final ACK.
FIN versus RST. FIN is a polite close: "I have no more data, but I will still read yours" (this one-directional close is called a half-close). RST is an abort: "this connection no longer exists, drop everything". A server sends RST when a packet arrives for a port with no listener, or when an application closes a socket with unread data. Load balancers and proxies also send RSTs when they time out idle connections, which is why clients see "connection reset by peer" on connections that sat idle too long.
Reliability, ordering, flow and congestion control#
- Reliability: every segment has a sequence number. The receiver acknowledges what it got; the sender retransmits anything not acknowledged in time.
- Ordering: the receiver reorders segments by sequence number before handing bytes to the application.
- Flow control: the receiver advertises a window (how much it can buffer), so a fast sender cannot overwhelm a slow receiver.
- Congestion control: the sender limits how much it has in flight based on signs of network overload (loss, rising delay). New connections start small (slow start) and grow, which is why brand-new connections are slow for the first few round trips. Algorithms include CUBIC (Linux default) and BBR.
Reliability in more depth: acknowledgements and timers#
TCP numbers every byte, not every packet. An acknowledgement says "I have received everything up to byte N", a cumulative ACK. If segments 1, 2, 4 and 5 arrive but 3 is lost, the receiver keeps acknowledging the end of segment 2. With SACK it also reports "and I hold 4-5", so the sender resends only segment 3.
The sender detects loss in two ways:
- Fast retransmit. Three duplicate ACKs for the same byte strongly suggest a lost segment followed by later ones that did arrive. The sender resends at once, without waiting for a timer. This recovers in about one RTT.
- Retransmission timeout (RTO). If no ACKs come back at all (for example, the last segments of a response were lost, so there is nothing after them to trigger duplicate ACKs), the sender waits for a timer. The timer is computed from measured RTTs: a smoothed average (SRTT) and its variation (RTTVAR), with
RTO = SRTT + 4 x RTTVAR. This method comes from Van Jacobson's 1988 paper "Congestion Avoidance and Control", and is specified in RFC 6298. Linux enforces a minimum RTO of 200 ms, and each successive timeout doubles the wait (exponential backoff).
That 200 ms floor matters inside data centres, where the RTT is 0.1-0.5 ms. A request that loses its last packet suddenly takes 200 ms instead of 1 ms, which is a classic source of unexplained p99 latency. Modern Linux reduces this with tail loss probes and RACK (time-based loss detection), which resend the last segment early instead of waiting for the full timer.
Retransmission is not free for the application. From the application's view, a lost packet is not an error: the read call just takes longer. That is the comfort of TCP and also its trap. A connection to a dead server can look "slow" for minutes, because the default number of retries for data is high (on Linux, about 15 retries, which can add up to around 15 minutes). This is why every network call needs an application-level timeout. TCP alone will keep trying far longer than your users will wait.
Flow control in more depth#
Each ACK carries the receiver's advertised window (rwnd): how many more bytes it can buffer. The sender never has more unacknowledged data in flight than this. If the application on the receiving side stops reading, the buffer fills, the window falls to zero, and the sender stops and probes periodically until space opens. This is backpressure built into the transport: a slow consumer slows the producer automatically, with no data lost.
The window limits throughput: one connection can move at most one window per round trip.
- Without window scaling, the window field is 16 bits, so at most 65,535 bytes. At 100 ms RTT that caps one connection at about 5.2 Mbps, no matter how fast the link.
- To fill a 1 Gbps path at 100 ms RTT, you need the bandwidth-delay product in flight: 1 Gbps x 0.1 s = 100 Mbit = 12.5 MB. Window scaling makes that possible, as long as the operating system's socket buffers are allowed to grow that large. Linux auto-tunes receive buffers up to a configurable maximum (
tcp_rmem), and a too-small maximum is a common reason why cross-region transfers are slow on otherwise idle links.
Congestion control in more depth#
Flow control protects the receiver. Congestion control protects the network between them, which no single sender can see. In October 1986 the early internet suffered congestion collapse: links were full, but useful throughput between two sites fell by roughly a factor of a thousand, because senders retransmitted into queues that were already overflowing. Jacobson's fixes, the basis of every TCP since, rest on one idea: treat packet loss as a sign of congestion, and back off.
The sender keeps a congestion window (cwnd) alongside the receiver's window, and sends at most the smaller of the two per round trip.
- Slow start. A new connection starts with a small
cwnd(10 segments, about 14.6 KB, since RFC 6928 in 2013) and doubles it every RTT while ACKs arrive. "Slow" is a historical name. Growth is exponential, but it still costs several round trips to reach a large window. - Congestion avoidance. Past a threshold (
ssthresh), growth becomes roughly linear: about one segment per RTT. - On loss, the classic algorithm (Reno) halves
cwnd. This pattern is AIMD, additive increase and multiplicative decrease. Chiu and Jain showed in 1989 that AIMD makes competing flows converge to a fair share of a link, which is why the internet stays usable when millions of flows share it.
A worked example of why slow start matters for APIs: to send a 100 KB response over a fresh connection, the server can send 14.6 KB in the first RTT, then 29.2 KB, then 58.4 KB. That is 102 KB after three round trips. At 80 ms RTT, the transfer alone takes about 240 ms, before even counting the handshakes. On a warm, reused connection whose window has already grown, the same response goes in a single RTT. This is one of the strongest arguments for connection reuse: it saves the handshakes and keeps the window large.
| Algorithm | Signal it reacts to | Behaviour | Where you meet it |
|---|---|---|---|
| Reno / NewReno | Packet loss | Halves the window on loss, grows by one segment per RTT | Older stacks, the textbook model |
| CUBIC (Ha, Rhee and Xu, 2008) | Packet loss | Grows along a cubic curve, recovering quickly to the window it had before the loss | Default on Linux, Windows and macOS |
| BBR (Cardwell et al., Google, 2016) | Measured bandwidth and minimum RTT | Paces sending to the estimated bottleneck rate instead of filling queues until loss | Google services, many CDNs, long and lossy paths |
| DCTCP | ECN marks from switches | Slows down in proportion to how many packets were marked | Inside data centres with ECN-capable switches |
ECN (explicit congestion notification) lets a router mark a packet "I am getting congested" instead of dropping it, so senders slow down before any loss. It needs support from the endpoints and the routers, which is common inside data centres and increasingly available on the internet.
Head-of-line blocking#
Because TCP delivers one ordered stream, a single lost packet blocks everything behind it until it is retransmitted, even data that arrived fine. This is head-of-line (HOL) blocking. HTTP/2 multiplexes many requests over one TCP connection, so one lost packet stalls all of them. QUIC fixes this by giving each stream its own ordering.
Head-of-line blocking in more depth#
Head-of-line blocking happens at two different layers, and it helps to keep them apart:
- Application-level HOL (HTTP/1.1). One connection carries one request at a time. A slow response blocks every request queued behind it on that connection. Browsers worked around this by opening about six connections per host, and sites by spreading assets over several hostnames ("domain sharding").
- Transport-level HOL (TCP). HTTP/2 solved the application problem by multiplexing many requests as interleaved streams on one connection. But TCP still delivers one ordered byte stream underneath, and it does not know the streams exist. If one packet carrying a piece of stream 3 is lost, the kernel holds back all later bytes, including complete responses for streams 5 and 7, until the retransmission arrives.
On a clean network, transport-level HOL hardly matters. On a lossy mobile network, it can make HTTP/2's single connection perform worse than HTTP/1.1's six parallel connections, because one loss stalls everything instead of one-sixth of the traffic, and a single connection's congestion window is also halved instead of one of six. That observation was a large part of the motivation for QUIC.
The same pattern appears far from networking. In a message queue partition, a message that a consumer cannot process stops every message behind it in the same partition. Ordered delivery always has this cost: if B must be seen after A, a stuck A delays B. The cures are also the same everywhere: make the ordered units smaller (per-stream ordering in QUIC, per-key ordering in a partitioned log), or move stuck items aside (a dead-letter queue). See Message Queues.
UDP characteristics#
UDP adds only ports, a length and a checksum to IP:
- No connection setup: the first packet carries data.
- No retransmission, ordering or flow control: lost packets stay lost.
- Message-based: each datagram is delivered whole or not at all, not as a byte stream.
- Small header (8 bytes vs TCP's 20+), and easy multicast and broadcast.
Applications that use UDP add only what they need: sequence numbers to drop stale data, forward error correction, or selective retries.
UDP in more depth#
The UDP header is four 16-bit fields: source port, destination port, length and checksum. That is everything. An application receiving a datagram learns where it came from and where it was going, and the rest is an opaque blob of bytes. Everything TCP gives you, and UDP does not, falls into a short list, and an application on UDP has to decide case by case which of these it needs:
| Need | TCP provides | On UDP the application must |
|---|---|---|
| Know a packet was lost | ACKs and timers | Add sequence numbers and detect gaps |
| Recover lost data | Retransmission | Resend selectively (NACKs), add redundancy (FEC), or just skip |
| Put data in order | Reordering buffer | Reorder, or discard anything older than the newest |
| Not overwhelm the receiver | Flow control | Rate-limit or apply its own feedback |
| Not overwhelm the network | Congestion control | Adapt its sending rate to loss and delay |
| Know the peer is there | Connection state | Send heartbeats, handle timeouts |
Size matters. A datagram is delivered whole or not at all. The protocol allows up to about 64 KB, but a datagram larger than the path MTU is fragmented at the IP layer, and losing any fragment loses the whole datagram. Real protocols keep datagrams under about 1,200-1,400 bytes. Classic DNS limited UDP answers to 512 bytes. EDNS0 raised that, and answers that are still too big set a "truncated" flag so the client retries over TCP.
How real-time applications use UDP.
- Voice and video (RTP, WebRTC). Each packet carries a sequence number and timestamp. The receiver keeps a small jitter buffer (tens of milliseconds) to smooth out variable delay, conceals a lost audio packet by stretching its neighbours, and asks for retransmission only when it is likely to arrive in time to be useful. Video codecs request a fresh key frame when too much is lost. The congestion control is delay-based: the sender lowers its bitrate when queues start to build, which is why a video call's picture gets blurry instead of freezing.
- Games. The server sends frequent snapshots of world state, perhaps 20-60 per second. Each snapshot supersedes the previous one, so a lost one is simply skipped. Clients predict their own movement immediately and reconcile when the authoritative snapshot arrives, and they interpolate other players between snapshots. Important one-off events (a purchase, a chat message) go over a reliable channel, either a separate TCP connection or a small reliability layer on top of UDP.
- Metrics (StatsD). The app fires a datagram such as
api.latency:42|msand never waits. If the collector is down or slow, metrics are lost but the application is never slowed. That is exactly the right trade-off for telemetry, and wrong for billing events.
UDP must still be polite. Because UDP has no congestion control, a careless UDP application can flood a link and starve every TCP flow sharing it. IETF guidance (RFC 8085) asks UDP applications that send a lot to implement their own congestion control. WebRTC and QUIC both do.
UDP and abuse. With no handshake, the source address of a UDP packet is easy to forge. Attackers send small requests to public UDP services with the victim's address as the source, and the services send much larger replies to the victim. This is a reflection and amplification attack. In February 2018, GitHub was hit by a 1.35 Tbps attack that abused exposed memcached servers, which could turn a tiny request into a reply tens of thousands of times larger. If you run a UDP service on the internet, keep replies no larger than requests until the client has proved its address (QUIC does exactly this during its handshake), and never expose internal UDP services publicly.
UDP and browsers. Web pages cannot open raw UDP sockets. A browser gets UDP-based transport only through WebRTC (peer-to-peer media and data channels), HTTP/3, and WebTransport. For a feature such as live reactions on a stream, a mobile app could receive a fast UDP feed while browser users receive the same events batched over HTTP or WebSockets, with the UI spreading them out over time so they still look live. Designs that rely on UDP need an answer for browser clients.
UDP and NAT. NAT devices track UDP "connections" too, but since UDP has no close, they guess, using idle timeouts that can be as short as 30 seconds. Long-lived UDP sessions send keep-alives every 15-25 seconds to hold their mapping open.
When to use each#
| Use case | Protocol | Why |
|---|---|---|
| Web pages, APIs, databases, file transfer | TCP (or QUIC) | Every byte must arrive in order |
| DNS lookups | UDP (TCP for large answers) | One small question and answer; a retry is cheaper than a handshake |
| Live video calls, VoIP | UDP (RTP, WebRTC) | A late frame is useless; skip it |
| Online games | UDP | Latest position matters, old updates do not |
| Live streaming to many viewers | TCP (HLS/DASH over HTTP) or QUIC | Seconds of buffering are acceptable; CDNs speak HTTP |
| Metrics (StatsD) | UDP | Losing a sample is fine; never block the app |
Choosing in practice#
In a design interview and in most real systems, TCP is the default and usually does not even need to be said aloud. The real question is whether some part of the system is a better fit for UDP. Four questions settle it:
Most real products use both. A video-conferencing app uses HTTPS over TCP for sign-in, scheduling and signalling (who joins, which codecs to use), WebSockets for chat and presence, and UDP via WebRTC for the audio and video itself. A multiplayer game uses HTTPS for the store and matchmaking, and UDP for live movement. A ride-hailing app uses HTTPS for bookings, and might stream driver locations over a long-lived connection where a dropped update is fine because a newer one is two seconds away. Splitting by data type, not by product, is the mature answer.
When UDP is tempting but wrong.
- Bulk transfer to "go faster". UDP is not faster at moving a file. TCP already fills the link. Without congestion control, UDP just causes loss. Tools that move huge files over long, lossy links on UDP (some commercial transfer products, and QUIC itself) work because they add careful congestion control, not because they skip it.
- Anything with money or state changes. A lost "debit this account" message is a bug, not a glitch.
- Behind restrictive networks. Many corporate and hotel networks block or throttle UDP. Anything UDP-based needs a TCP fallback (WebRTC falls back to TURN over TCP or TLS on port 443).
QUIC#
QUIC is a transport protocol built on UDP, standardised by the IETF in 2021, and the basis of HTTP/3. It provides:
- Reliable, ordered streams, but each stream is independent, so a loss blocks only its own stream.
- Built-in TLS 1.3: connection and encryption setup together in one round trip, or zero (0-RTT) when resuming.
- Connection migration: a connection is identified by an ID, not by IP and port, so a phone switching from Wi-Fi to mobile data keeps its connection.
Because it runs in user space over UDP, QUIC can evolve faster than TCP, which is built into operating system kernels. Some corporate networks block UDP, so clients fall back to TCP.
QUIC in more depth#
Why build a new transport on UDP instead of fixing TCP? TCP lives in operating system kernels and is inspected and modified by countless middleboxes (firewalls, NATs, load balancers) that assume they know what a TCP header looks like. Changing TCP's wire format, or even its behaviour, takes a decade of kernel upgrades and still breaks on old middleboxes. This problem is called ossification. QUIC sidesteps it in two ways: it runs over UDP, which middleboxes pass through without looking inside, and it encrypts almost all of its own headers, so middleboxes cannot come to depend on them. The protocol can then evolve by shipping a new library in a browser or server, not a new kernel.
Google started QUIC around 2012 and deployed it in Chrome and its own services. The design and deployment experience are described in "The QUIC Transport Protocol: Design and Internet-Scale Deployment" (Langley et al., SIGCOMM 2017), which reported measurable reductions in search latency and video rebuffering, largest on the slowest networks. The IETF version, a substantial redesign, was published as RFC 9000 in May 2021, with HTTP/3 following as RFC 9114 in 2022.
Handshakes compared. With TCP plus TLS 1.3, the client must finish the TCP handshake (one RTT) before starting TLS (another RTT), so the request goes out after two RTTs. QUIC merges transport and cryptographic setup into one exchange.
At 100 ms RTT, a new HTTPS connection over TCP spends about 200 ms before the request leaves, and QUIC about 100 ms. A resumed QUIC connection can send the request in its very first packet.
0-RTT has a catch: replay. Early data is sent before the server has proved the connection is fresh, so an attacker who records it can send it again. Servers should accept 0-RTT only for requests that are safe to repeat (idempotent reads such as GET) and reject or delay anything that changes state. CDNs that enable 0-RTT typically apply exactly this rule.
Other improvements over TCP.
- Independent streams, so loss on one stream does not block the others (see head-of-line blocking above).
- Connection IDs instead of the 4-tuple. When a phone moves from Wi-Fi to mobile data, its IP changes and every TCP connection dies. A QUIC connection continues, because the server recognises the connection ID. This is connection migration. It also means QUIC load balancers must route by connection ID, not by client IP and port, or a migrated connection lands on the wrong server.
- Better loss detection. Every QUIC packet has a new, never-reused packet number, even for retransmitted data. TCP reuses the sequence number when it retransmits, so when an ACK arrives it cannot tell whether the original or the retransmission was acknowledged, which muddles its RTT samples (the "retransmission ambiguity" that Karn's algorithm works around). QUIC has no such ambiguity.
- Address validation. A server can require a client to prove it owns its source address before sending large responses, which prevents QUIC from becoming a UDP amplifier.
Costs.
- CPU. QUIC runs in user space and encrypts every packet individually, and it lacks the decades of hardware offload that TCP enjoys (segmentation offload, checksum offload). Early deployments reported noticeably higher CPU per byte than TCP plus TLS. The gap has narrowed with UDP segmentation offload and batching system calls, but it is still real for bulk-serving servers.
- Blocked UDP. Some networks block UDP on port 443. Clients therefore start with HTTP/2 over TCP, learn from an
Alt-Svcheader or an HTTPS DNS record that the server supports HTTP/3, and try QUIC on later connections. They fall back silently if it fails. - Visibility. Encrypted headers mean network operators cannot see retransmissions or RTTs the way they can with TCP, so debugging relies on endpoint logs (the qlog format exists for this).
Where QUIC fits. At the edge, between users and a CDN or front-end load balancer, QUIC and HTTP/3 help most: mobile users, lossy networks, long distances, many small resources. Inside a data centre, where RTTs are sub-millisecond and loss is rare, the benefits are small, and most internal traffic stays on TCP (HTTP/2, gRPC). Turning on HTTP/3 is usually a CDN or load-balancer setting, not application work.
Connection reuse and pooling#
A new HTTPS connection over TCP costs about 2-3 round trips (TCP plus TLS) before the first byte of the request. Across a continent at 100 ms RTT, that is 200-300 ms of pure setup. So:
- Keep-alive keeps a connection open for many requests.
- Connection pools keep a set of open connections to a database or service, and requests borrow one.
- HTTP/2 and HTTP/3 multiplex many concurrent requests on one connection.
What a connection really costs#
Reusing connections is not a micro-optimisation. A new connection costs on three fronts:
- Latency. Each new HTTPS connection over TCP costs one RTT for TCP and one for TLS 1.3 (two for TLS 1.2), plus several RTTs of slow start before the window is large. Inside a data centre that is well under a millisecond. Between regions at 70-150 ms it dominates the request.
- CPU. The TLS handshake does public-key cryptography. A server can handle far fewer new handshakes per second per core than it can handle requests on existing connections. A database connection adds authentication and session setup on top.
- Memory. Every open connection holds kernel buffers and application state, even while idle. PostgreSQL runs a separate operating-system process per connection, and each takes several megabytes. That is why its default
max_connectionsis only 100 and why a few thousand direct connections can bring a database server to its knees long before CPU runs out.
Pool sizing, worked#
A pool keeps a set of connections open and lends one to each request. Little's law gives the number needed: connections in use = request rate x time each request holds a connection.
- A service makes 2,000 database queries per second, each holding a connection for 5 ms: 2,000 x 0.005 = 10 connections busy on average. Allow headroom for bursts and slow queries, say 20.
- The trap is multiplication. If that service runs as 200 pods and each pod has its own pool of 20, the database faces 4,000 connections, although only about 10 are busy at any moment. Autoscaling makes it worse: the database's connection count grows with the number of pods, not with real load.
- Bigger pools are not faster. A database with 16 cores can execute only so many queries at once. Beyond roughly a few times the core count, extra connections just contend for locks and CPU and raise latency. Small pools with a short wait queue usually beat large ones.
The fix for the multiplication problem is a pooler that sits between the many clients and the database: PgBouncer or RDS Proxy for PostgreSQL, ProxySQL for MySQL. Thousands of client connections map onto a few dozen real ones. PgBouncer offers three modes, and the choice matters:
| Mode | A server connection is held for | Sharing | What breaks |
|---|---|---|---|
| Session | The whole client session | Least | Nothing, but little gain |
| Transaction | One transaction | High, the usual choice | Session state: SET variables, advisory locks, some prepared-statement uses, LISTEN |
| Statement | One statement | Highest | Multi-statement transactions are not allowed |
Pooling at a million clients: Meta's ZGateway#
Meta's ZippyDB is a key-value store shared by hundreds of internal teams, with more than a million client machines using it. Even with every client pooling its own connections, Meta described typical clients holding tens of thousands of outgoing connections and individual database hosts accepting tens of thousands of incoming ones. A mass restart of clients forced the database to rebuild connections while still serving queries. And identical work was repeated: a thousand callers reading the same popular record each caused their own lookup.
Meta's answer, described in a 2026 Meta engineering post, was to put a shared reverse proxy, ZGateway, in front of the database. Clients connect to a few gateway hosts, and the gateways talk to the database over shared pools. Once all traffic flows through one layer, five techniques become possible:
- Shared connection pooling. A new client reuses the gateway's existing backend connections instead of opening its own to every database host. The database sees connections from a bounded set of gateways rather than from a million machines.
- Batching. Requests for different keys on the same shard (say profiles 73, 81 and 92) travel in one backend request. The database still does three lookups, but they share the fixed costs of serialisation, network transmission and request handling, and the use case spends less of its rate-limit budget. The price is latency: holding the first request to wait for others delays it. ZGateway flushes a batch when a timer fires or a size or count limit is reached, and caps how many batches can be in flight so that a slow database cannot make the gateway's memory grow without bound.
- Request coalescing. If three callers want the same key while a lookup for it is already running, they attach to that lookup and all receive its result. Unlike batching, this removes work: one lookup answers many callers, which is exactly what happens when a record suddenly becomes popular. It only works within one gateway and while the lookup is still in flight. It costs memory to track waiting callers, so it needs limits and cleanup on timeout.
- Read-through caching. The gateway keeps results in memory. To stop a thundering herd when a popular entry expires, a per-key fill lock lets one request refill it while the rest wait for that result, which is coalescing again with the answer kept afterwards. Freshness comes from a change-data-capture stream that invalidates or refreshes entries, within an agreed bound on how stale a cached read may be.
- Admission control. Requests go into separate bounded queues per use case and priority, served in turns. If one team floods its queue, its excess is rejected while other teams keep making progress. CPU and memory pressure also limit what is accepted. The cost is that some callers get fast errors instead of slow successes, so clients must back off before retrying or they recreate the overload.
The lesson generalises: a shared proxy layer turns per-client costs (connections, repeated reads, uncontrolled spikes) into shared, controllable ones. The same reasoning lies behind database proxies, service meshes and API gateways. The price is an extra hop (often well under a millisecond inside a data centre) and another tier to run and scale.
Keeping pooled connections healthy#
Long-lived connections fail in quiet ways. A healthy pool needs:
- An idle timeout shorter than every middlebox's. If a NAT gateway or load balancer drops idle mappings after 350 seconds and the pool keeps idle connections for 10 minutes, the first request after a quiet period hangs and then fails. Either expire idle connections sooner, or enable TCP keep-alives with an interval below the shortest timeout on the path.
- A maximum lifetime. Recycling each connection after, say, 30 minutes (with jitter) spreads load onto newly added servers, picks up DNS changes, and limits the damage of slow leaks.
- Validation and fast failure. Check a connection when borrowing it, or catch the error and retry once on a fresh one. Set a short wait timeout for borrowing: if the pool is exhausted, failing in 100 ms is better than queueing requests for 30 seconds.
- Jittered reconnects. When a database fails over, every client reconnects at once. Spreading reconnect attempts with random backoff avoids a self-inflicted connection storm. This was one of the problems ZGateway was built to absorb.
Multiplexing changes the picture. With HTTP/2 or gRPC, one connection carries many concurrent requests (servers typically allow about 100 concurrent streams per connection), so a client often needs only one or a few connections per backend. The catch is load balancing: an L4 load balancer spreads connections, so a handful of long-lived HTTP/2 connections can pin all of a client's traffic onto one or two servers. The fixes are an L7 load balancer that spreads individual requests, client-side balancing across several connections, or a maximum connection age so that connections are periodically re-established. See Load Balancing.
When to Use It#
- TCP by default for anything that must be complete and ordered.
- UDP when freshness beats completeness, or for tiny request-response exchanges like DNS.
- QUIC / HTTP/3 for mobile and lossy networks, and global users where handshake time matters.
When NOT to Use It#
- Do not build your own reliability on UDP for ordinary data transfer; you will end up re-implementing TCP badly.
- Do not open a new connection per request to a database or busy service; use a pool.
How to Implement It#
- Default to HTTP over TCP for APIs, and enable HTTP/2 between services.
- Enable HTTP/3 at the CDN or edge for mobile clients.
- Pool database connections and size the pool with Little's law (QPS x query time).
- Use UDP-based protocols (WebRTC, RTP) only for real-time media and games.
- Tune timeouts: connect timeout ~1 s inside a data center, request timeouts per call.
# Example connection pool settings (PgBouncer)
[pgbouncer]
pool_mode = transaction ; share connections between transactions
max_client_conn = 5000 ; app-side connections accepted
default_pool_size = 50 ; real connections to PostgreSQL per db/user
server_idle_timeout = 60| Technology | Fits when |
|---|---|
| PgBouncer, ProxySQL, RDS Proxy | Pooling many app connections onto few database connections |
| HTTP clients with keep-alive pools | Calling other services repeatedly |
| WebRTC | Real-time audio and video in browsers (UDP-based) |
| QUIC libraries (quiche, msquic) or a CDN with HTTP/3 | Faster connections on mobile and lossy networks |
Timeouts and keep-alives in code#
Most transport problems in production are configuration problems: a missing timeout, no keep-alive, a pool with defaults nobody chose. A Node.js HTTP client shows the settings worth setting explicitly in any language:
import http from "node:http";
// One shared agent per process: reuses connections across requests.
const agent = new http.Agent({
keepAlive: true, // keep connections open between requests
keepAliveMsecs: 15_000, // TCP keep-alive probes on idle sockets
maxSockets: 50, // cap concurrent connections per host
maxFreeSockets: 10, // idle connections kept warm
timeout: 60_000, // close sockets idle this long (below LB/NAT idle timeouts)
});
function getJson(url: string): Promise<string> {
return new Promise((resolve, reject) => {
const req = http.get(url, { agent, timeout: 2_000 }, (res) => {
let body = "";
res.on("data", (chunk) => (body += chunk));
res.on("end", () => resolve(body));
});
// Without this, a dead peer can hold the request for minutes.
req.on("timeout", () => req.destroy(new Error("request timeout")));
req.on("error", reject);
});
}The same five decisions appear in every client library, whatever their names: reuse connections, cap how many, keep idle ones alive or close them before middleboxes do, bound the time of every request, and destroy sockets that time out instead of leaving them half alive.
Operating-system settings that matter#
You rarely need to tune the kernel, but a handful of Linux settings explain many production incidents:
| Setting | Default (typical) | What it controls | When to change it |
|---|---|---|---|
net.core.somaxconn | 4,096 on recent kernels, 128 on older | Upper bound on a socket's accept queue | Busy servers on older kernels that drop new connections |
net.ipv4.ip_local_port_range | 32768-60999 | Ephemeral ports for outgoing connections | Proxies and clients that open many connections to one backend |
net.ipv4.tcp_tw_reuse | Enabled for loopback only on recent kernels | Reusing TIME_WAIT ports for new outgoing connections | Clients with port exhaustion, when timestamps are on |
net.ipv4.tcp_keepalive_time | 7,200 s | Idle time before keep-alive probes start | Lower it (or set per socket) for connections through NAT or load balancers |
net.ipv4.tcp_rmem / tcp_wmem | Max a few MB | Socket buffer auto-tuning limits | High-bandwidth, long-RTT transfers |
net.ipv4.tcp_congestion_control | cubic | Congestion algorithm | Switch to bbr for long, lossy paths after testing |
Two of these defaults surprise people. The two-hour keep-alive default means TCP keep-alive does nothing useful against a NAT timeout of a few minutes unless the application sets a shorter interval per socket. And the old tcp_tw_recycle option, often suggested in blog posts for TIME_WAIT problems, broke clients behind NAT and was removed from Linux in 4.12. Connection reuse is the real fix for TIME_WAIT pressure.
Trade-offs#
| Protocol | Pros | Cons | Pick when |
|---|---|---|---|
| TCP | Reliable, ordered, universal | Handshake cost, HOL blocking | APIs, databases, files |
| UDP | No setup, low overhead, no blocking | No reliability; app handles loss | Real-time media, games, DNS |
| QUIC | Fast setup, no cross-stream HOL blocking, migration | Higher CPU cost, UDP sometimes blocked | Web and mobile clients via HTTP/3 |
| Connection per request | Simple, no pool state | Handshake and slow-start cost every time, TIME_WAIT and port exhaustion | Very low request rates only |
| Per-instance connection pool | Fast reuse, simple | Connections multiply with instance count | Small fleets, modest databases |
| Central pooler or gateway (PgBouncer, ZGateway-style) | Bounds backend connections, enables batching, coalescing and admission control | Extra hop, extra tier to run, session features restricted | Many clients sharing one database or service |
| HTTP/2 multiplexing | One connection carries many requests | Transport HOL on loss, L4 load balancing gets uneven | Service-to-service calls in a data centre |
| QUIC 0-RTT | Request in the first packet on resumption | Early data can be replayed | Idempotent reads from returning clients |
| BBR instead of CUBIC | High throughput on lossy, long paths, less queueing | Fairness concerns with loss-based flows | CDNs, long-haul transfers, video delivery |
Common Pitfalls#
- A new TCP and TLS connection per request, adding hundreds of milliseconds across regions.
- Too many database connections because every app instance opens a large pool.
- Assuming UDP packets arrive in order or at all.
- Forgetting that a "connection reset" mid-request does not tell you whether the server processed it.
- Leaking sockets in CLOSE_WAIT because an error path never closes the connection.
- Relying on TCP's own retries instead of setting application timeouts, so calls to a dead host hang for minutes.
- Pool idle timeouts longer than the NAT or load balancer idle timeout, so the first request after a quiet spell fails.
- Long-lived HTTP/2 or gRPC connections behind an L4 load balancer, so new servers get no traffic.
- Sending UDP datagrams larger than the path MTU, so a single lost fragment loses the whole message.
- Exposing a UDP service whose replies are larger than its requests, which makes it an amplification weapon.
- Accepting state-changing requests as QUIC or TLS 0-RTT early data.
- Huge database pools "for performance", which adds contention instead of throughput.
Real-World Examples#
Google developed QUIC and deployed it widely in Chrome and its services before the IETF standardised it; HTTP/3 over QUIC is now supported by major browsers and CDNs.
DNS has used UDP port 53 since its early design, falling back to TCP for large responses and zone transfers.
In February 2018 GitHub withstood a 1.35 Tbps reflection attack that abused publicly exposed memcached servers listening on UDP. It is the textbook example of why UDP services must not send large replies to unverified source addresses.
Meta put a shared gateway, ZGateway, in front of its ZippyDB key-value store to cope with more than a million client machines. Pooled backend connections, batching, request coalescing, a read-through cache with per-key fill locks and per-use-case admission control let the database serve far more callers with less repeated work.
Google's BBR congestion control was published in 2016 and deployed on Google's services, including YouTube, where Google reported higher throughput and lower queueing delay on many paths.
The initial congestion window of 10 segments came from Google's measurements, published as "An Argument for Increasing TCP's Initial Congestion Window" (Dukkipati et al., 2010). Their data showed that most web responses were small enough to finish within slow start, so starting with a larger window cut the latency of typical page loads by around a round trip. Linux adopted 10 as its default, and the IETF standardised it in RFC 6928.
In the Interview#
How to talk about transport in an interview#
Interviewers assume TCP unless you say otherwise, and most of them want your time spent on data and scale, not on packet formats. Transport earns points in three moments:
- A real-time component. Name the split explicitly: "Signalling and chat go over WebSockets on TCP. The media goes over WebRTC on UDP, because a late frame is worse than a lost one. Browser users who cannot get UDP fall back to TURN over TCP." Then stop. You have shown you know when UDP fits and that browsers complicate it.
- Latency budgets across regions. "Each new HTTPS connection costs two round trips before the request, about 150 ms between US-East and Europe, so clients keep connections warm and the edge terminates TLS close to users." This links the protocol to a number.
- A database or shared service with many clients. "Two hundred pods with a pool of 20 each is 4,000 connections, far more than PostgreSQL handles well. We put PgBouncer in transaction mode in front of it and keep the real pool near a few times the core count." If the problem has hot keys, add coalescing and a cache with a fill lock, as Meta's ZGateway does.
Level expectations. A junior or mid-level candidate should get the TCP and UDP choice right and know that connections should be reused. A senior candidate should quantify handshake costs and pool sizes, and know why HTTP/2 over a lossy link suffers. A staff candidate might bring up QUIC's connection migration for mobile clients, 0-RTT replay limits, the load-balancing side effects of long-lived connections, or incast on fan-out paths. But only when it changes a decision in the design, never as a recital.
Common mistakes that cost points. Choosing UDP for anything that must not be lost. Saying "UDP is faster" without saying what is lost. Ignoring browser clients in a UDP design. Treating a connection reset as proof that a request failed, when it might have been processed. That last one leads straight to idempotency keys; see Idempotency.
Deep Dive: Tuning, ephemeral ports and long-lived connectionsShow
Ephemeral port exhaustion. Each outgoing connection from one IP to one destination IP and port needs a unique source port, from a range of roughly 28,000 by default on Linux. With TIME_WAIT holding ports for 60 seconds, a proxy opening more than ~470 new connections per second to one backend can exhaust them. Fixes are connection reuse, more source IPs, or widening the port range.
Nagle and delayed ACKs. Nagle's algorithm batches small writes, which can interact badly with delayed acknowledgements and add ~40 ms latency to small request-response traffic. Latency-sensitive services set TCP_NODELAY.
Long-lived connections and load balancing. Connection reuse means a load balancer sees few long connections, so new servers receive little traffic. HTTP/2 and gRPC clients should rebalance (for example, by limiting connection age) or use L7 load balancing that spreads requests, not connections.
Kernel bypass. Very high-throughput systems (trading, telecom) use kernel-bypass stacks or RDMA to cut per-packet overhead, but this is specialist territory.
Deep Dive: The throughput of one TCP flow, in numbersShow
Three limits cap a single TCP connection, and the lowest one wins:
- The receiver's window. Throughput is at most
rwnd / RTT. A 64 KB window at 100 ms gives 5.2 Mbps. A 16 MB auto-tuned window at 100 ms gives about 1.3 Gbps. - The congestion window. On a path with random loss, a loss-based algorithm keeps halving its window. The Mathis formula (Mathis, Semke, Mahdavi and Ott, 1997) estimates the steady state: throughput ≈ (MSS / RTT) x (1.22 / √p), where p is the loss rate. With MSS 1,460 bytes, RTT 100 ms and 0.1% loss: 1,460 x 8 bits / 0.1 s = 117 kbps, times 1.22 / 0.0316 ≈ 38.6, which is about 4.5 Mbps, whatever the link speed. Halve the RTT and throughput doubles. That is why long-distance transfers on lossy paths are slow and why CDNs and regional replicas help bulk delivery, not only first-byte latency.
- The bottleneck link. No algorithm can beat the slowest link on the path.
Bufferbloat is what happens when loss-based algorithms meet large buffers. CUBIC keeps growing its window until a buffer overflows, so on a home router with seconds of buffer, a single upload fills that buffer and every other packet, including a video call's, waits behind it. Latency under load jumps from 20 ms to hundreds of milliseconds. Two fixes exist: smarter queue management in routers (CoDel and fq_codel drop or mark packets early, based on how long they waited) and delay-aware senders like BBR, which aim to keep the pipe full without filling queues.
BBR in one paragraph. BBR keeps two running estimates: the bottleneck bandwidth (the highest delivery rate recently seen) and the round-trip propagation time (the lowest RTT recently seen). Their product is the ideal amount in flight. BBR paces packets at the estimated bandwidth, periodically probes a little higher to see whether more bandwidth is available, and briefly drains its queue to re-measure the minimum RTT. Because it does not treat random loss as congestion, it keeps high throughput on lossy long-distance paths where CUBIC collapses. Its first version was criticised for being unfair to loss-based flows that share a bottleneck with it, which later versions address.
Practical tools. On Linux, ss -ti shows per-connection cwnd, rtt, retrans and delivery rate. A connection with a tiny cwnd and many retransmissions is suffering loss, and one with a large cwnd but low throughput is limited by the application or the receive window. iperf3 measures what the path can actually carry, and comparing one stream with several parallel streams tells you whether you are window-limited or link-limited.
Deep Dive: Building a reliable channel on UDP, and why it is hardShow
Teams sometimes decide to "just add reliability to UDP" for a game, a replication protocol or a file transfer. The work involved is a useful map of what TCP and QUIC already do:
- Sequencing and acknowledgement. Every packet gets a number, and the receiver reports what it has. Acknowledging every packet doubles packet count, so real protocols send compact ranges or bitmaps (for example, "latest received is 1,200, plus a 32-bit mask of the 32 before it").
- Retransmission timing. You need RTT estimates, a timeout that adapts to variance, backoff on repeated loss, and a rule for when data is too old to bother resending. Getting this wrong either floods the network with duplicates or stalls on every loss.
- Congestion control. Without it, your protocol makes congestion worse exactly when the network is struggling, and network operators may throttle it. This is the part teams most often skip and most regret.
- Fragmentation and reassembly. Messages larger than one datagram must be split, numbered, reassembled and resent piece by piece.
- Security. Without a handshake, you need to prevent spoofing, replay and amplification, and to encrypt. That means effectively re-inventing TLS.
- Connection lifecycle. Heartbeats, timeouts, NAT keep-alives and clean shutdown.
By the time all six are done well, you have built a worse QUIC. That is the real argument for QUIC's existence: it packages all of this, tested at internet scale, into a library. Building custom reliability on UDP is justified mainly when you need partial reliability (resend some messages, drop others, as in games and media) or behaviour no standard protocol offers. Even then, libraries such as ENet for games or QUIC's unreliable datagram extension (RFC 9221) are usually a better starting point than raw sockets.
Deep Dive: Failures at the connection level, and graceful shutdownShow
What the application can know. When a write call returns successfully, TCP has only copied your bytes into a kernel buffer. They may not have left the machine yet. Even an ACK only proves the peer's kernel received them, not that its application processed them. So when a connection breaks in the middle of a request, the client cannot know whether the server did the work. This is why retried requests need idempotency keys, and why "exactly once" has to be built at the application layer, never assumed from TCP.
Half-open connections. If a server loses power, it sends no FIN or RST. The client's connection stays ESTABLISHED until it tries to send something and the retransmissions time out, or until a keep-alive probe fails. A client that only listens, such as a subscriber waiting for push messages, may wait indefinitely for data that will never come. Long-lived connections therefore need application heartbeats (a ping every 15-30 seconds, with a deadline for the reply), not just TCP keep-alive with its two-hour default.
Graceful shutdown during deploys. Every deployment kills processes that hold open connections. Done carelessly, each deploy produces a burst of errors. The careful sequence is:
- Mark the instance as draining so the load balancer stops sending it new connections (fail its readiness check, or deregister it).
- Wait for the load balancer to notice, typically a few health-check intervals.
- Tell clients on existing connections to go elsewhere. HTTP/1.1 servers add
Connection: closeto responses. HTTP/2 servers send a GOAWAY frame naming the last stream they will process, so clients open new connections for later requests without losing in-flight ones. WebSocket servers send a close frame, and clients reconnect with jitter. - Let in-flight requests finish, up to a deadline (say 30 seconds), then close.
Cloud load balancers expose this as a "deregistration delay" or "connection draining" setting. Getting it right is the difference between zero-error deploys and a spike of resets every time you ship.
RST storms. When a load balancer or proxy restarts, it may reset thousands of connections at once, and every client reconnects in the same second. Combined with TLS handshakes, the reconnect wave can cost more CPU than the normal traffic. Jittered reconnect delays, TLS session resumption and keeping a little headroom on handshake capacity are the standard defences.
Key Takeaways#
- TCP gives reliable, ordered streams with flow and congestion control, at the cost of a handshake and head-of-line blocking.
- UDP sends independent packets with no setup or retries; use it when freshness beats completeness.
- QUIC runs over UDP, adds TLS and independent streams, and powers HTTP/3.
- New connections cost round trips, so reuse them with keep-alive, pools and multiplexing.
- Pick by data needs: payments and files need TCP; live media and games prefer UDP.
- A connection is shared state: sequence numbers, windows, buffers and timers on both sides. That state is what costs memory and what leaks in CLOSE_WAIT.
- Slow start means a fresh connection needs several round trips to send even 100 KB. Reuse keeps both the handshake and the large window.
- One TCP flow is limited by window ÷ RTT and by loss (Mathis). Distance and loss cut throughput, not only latency.
- On UDP, decide explicitly which of sequencing, retransmission, ordering, flow control and congestion control you need. If you need all of them, use QUIC.
- QUIC gives 1-RTT setup, 0-RTT resumption for safe requests, independent streams and connection migration, at some CPU cost and with a TCP fallback.
- Size pools with Little's law, then watch the multiplication across instances. A central pooler or gateway bounds connections and enables batching, coalescing and admission control.
- A broken connection does not tell you whether the request was processed. Use idempotency keys for retries, heartbeats for long-lived connections, and drain connections gracefully on every deploy.