Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Performance engineering · Lesson 18 of 44

Network performance for system designers

Why distance sets a latency floor, how round trips and handshakes dominate short requests, what the bandwidth-delay product, TCP windows and loss do to throughput, and how Nagle, MTU and buffers add surprises, with tested C# arithmetic.

ConceptApplied18 min readUpdated

  • 6 code samples
  • 7 interviewer follow-ups
  • 3 self-checks

Read first: Latency, throughput and queues

By the end you will be able to
  • Compute the latency floor from distance, and count the round trips a request needs before the first byte.
  • Calculate the bandwidth-delay product and explain why a window-limited transfer cannot fill a fast, long link.
  • Estimate TCP throughput under loss and the cost of slow start for short transfers.
  • Explain Nagle and delayed acknowledgements, MTU and MSS problems, and bufferbloat.
  • Diagnose a transfer that is slower than the link with the right tools and in the right order.

3 code samples (61 lines), collapsed so the explanation stays in focus.

Most services are built from calls over a network, so the network's physics shows up in every latency budget. Three facts explain most surprises. Distance sets a floor you cannot optimize away. Short requests are limited by the number of round trips, not by bandwidth. And a single TCP connection can only use a link if its window and its loss rate allow it. This lesson turns those into arithmetic you can do in an interview.

HLD

Latency has a floor: distance

Light in optical fiber travels at about two thirds of its speed in a vacuum, roughly 200,000 km per second, or 5 microseconds per kilometer each way. Routes are longer than the straight line and devices add delay, so real round trips are larger, but this is the minimum.

PathDistanceBest-case round trip in fiber
Same datacenterunder 1 kmtens of microseconds, plus device and software delay (about 0.5 ms in practice)
Across a metropolitan area100 km1 ms
New York to Londonabout 5,570 kmabout 56 ms
Across an ocean and a continent15,000 km150 ms

You can buy bandwidth. You cannot buy latency: only moving the work closer to the user (a CDN, an edge location, a regional deployment) lowers it. Two other delays add to propagation. Serialization is the time to put the bits on the wire, size ÷ bandwidth: a 1,500-byte packet takes 12 µs at 1 Gbps and 1.2 ms at 10 Mbps. Queueing is the time spent waiting behind other traffic, which, as the first lesson in this section showed, is where most variation comes from.

HLD

Round trips are the currency

Before the first byte of a response can arrive, a new connection has to be set up. Each setup step costs a round trip:

ConnectionRound trips before the request can be sentRound trips to the first response byte
New TCP connection with TLS 1.23 (TCP handshake 1, TLS 1.2 handshake 2)4
New TCP connection with TLS 1.32 (TCP 1, TLS 1.3 handshake 1)3
New QUIC connection (HTTP/3)1 (transport and TLS 1.3 together)2
Resumed QUIC connection with 0-RTT data0 (the request travels with the first flight)1
Existing connection reused01

At an 80 ms round trip those rows are 320 ms, 240 ms, 160 ms, 80 ms and 80 ms, before the server does any work and before any data beyond the first flight arrives. This is why modern designs keep connections alive and pool them, resume TLS sessions, and prefer protocols with fewer handshake round trips.

It also explains why terminating the connection near the user speeds up a global application even when the origin is far away. If the user is 20 ms from an edge location and the edge holds a warm, long-lived connection to an origin that is 140 ms from the edge, the user pays the handshake round trips against 20 ms, not 160 ms: roughly 200 ms to the first byte instead of 480 ms for a new TLS 1.3 connection straight to the origin.

C# · Setup, Rtts21 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public enum Setup { TcpTls12, TcpTls13, Quic, QuicResumed, Reused }

public static class Rtts
{
    /// <summary>Round trips spent before the client can send its request.</summary>
    public static int BeforeRequest(Setup setup) => setup switch
    {
        Setup.TcpTls12 => 3,        // TCP handshake (1) + TLS 1.2 full handshake (2)
        Setup.TcpTls13 => 2,        // TCP handshake (1) + TLS 1.3 handshake (1)
        Setup.Quic => 1,            // QUIC combines the transport and TLS 1.3 handshakes
        _ => 0,                     // 0-RTT resumption, or a connection that already exists
    };

    /// <summary>Time to the first response byte: setup, plus one round trip for the request and response, plus server time.</summary>
    public static double TimeToFirstByteMs(Setup setup, double rttMs, double serverMs = 0) => (BeforeRequest(setup) + 1) * rttMs + serverMs;
}
C#
Debug.Assert(Rtts.TimeToFirstByteMs(Setup.TcpTls12, 80) == 320);
Debug.Assert(Rtts.TimeToFirstByteMs(Setup.TcpTls13, 80) == 240);
Debug.Assert(Rtts.TimeToFirstByteMs(Setup.Quic, 80) == 160);
Debug.Assert(Rtts.TimeToFirstByteMs(Setup.QuicResumed, 80) == 80);
Debug.Assert(Rtts.TimeToFirstByteMs(Setup.Reused, 80) == 80);

// A user 20 ms from an edge; the edge holds a warm connection to an origin 140 ms further on (160 ms from the user).
double direct = Rtts.TimeToFirstByteMs(Setup.TcpTls13, rttMs: 160);                          // the handshakes cross the whole distance
double viaEdge = Rtts.BeforeRequest(Setup.TcpTls13) * 20 + (20 + 140);                       // handshakes with the edge, then one request through it
Debug.Assert(direct == 480 && viaEdge == 200);

HLD

The bandwidth-delay product

A sender can only keep as much data in flight as its window allows, and a link of bandwidth B and round-trip time R holds B × R bytes while the first data is still travelling and nothing is acknowledged yet. That is the bandwidth-delay product, and a single connection must have a window at least that large to fill the link.

Example · formula
BDP = bandwidth × round-trip time
throughput of one connection <= window ÷ round-trip time

A 1 Gbps path with an 80 ms round trip has a BDP of 125,000,000 bytes per second × 0.08 s = 10 MB. The classic TCP window field is 16 bits, 65,535 bytes. Without the window scaling option that gives 65,535 ÷ 0.08 = 819 KB/s, 6.6 Mbps on a gigabit link. With window scaling and large enough buffers, a 4 MiB window gives about 420 Mbps, and 10 MB fills the pipe. Modern operating systems negotiate window scaling and auto-tune buffers, but limits on buffer size, a middlebox that strips the option, or an application that sets a small socket buffer still reproduce this exactly. A single stream that is stuck at a suspiciously low, constant rate is usually window-limited, and its rate divided by the window gives the round-trip time it is seeing.

Two ways around it: raise the window (and buffer limits) on both ends, or use several parallel connections, since each has its own window. Tools like iperf3 can show the difference between one stream and many.

HLD

Slow start: why short transfers never see the bandwidth

A new TCP connection starts with a small congestion window, typically 10 segments (about 14.6 KB), and roughly doubles it each round trip while there is no loss. So a transfer that fits in a few windows is limited by the number of rounds, not the link. To send S segments from an initial window of 10 takes the smallest n for which 10 × (2^n − 1) ≥ S rounds:

TransferSegments of 1,460 bytesRoundsAt 80 ms
15 KB112160 ms
100 KB693240 ms
1 MB6857560 ms
10 MB6,85010800 ms

A 1 MB response over a gigabit link, which the link could carry in 8 ms, takes more than half a second for this reason. Implications: send fewer bytes (compression, smaller payloads), keep connections warm so the window has already grown, serve from nearby, and in some systems raise the initial window. This is also why a load test that opens a new connection per request measures something different from one that reuses connections.

HLD

Loss and congestion control

When a packet is lost, loss-based congestion control shrinks the window (classic Reno halves it; CUBIC backs off less sharply) and grows it again slowly. Under steady random loss p, a well-known approximation (Mathis and co-authors) bounds a connection's throughput:

Example · formula
throughput <= (MSS ÷ RTT) × (C ÷ √p)
C is about 1.2 and depends on acknowledgement behavior

With a 1,460-byte MSS and an 80 ms round trip, a loss rate of 0.01% (p = 0.0001) caps a Reno-style connection near 18 Mbps, however fast the link. At 0.0001% loss it is about 180 Mbps. The approximation breaks down at high loss and for newer algorithms (CUBIC does better on long paths, and BBR estimates bandwidth and round-trip time instead of reacting to loss), but the shape is right: throughput falls with round-trip time and with the square root of the loss rate. So a long, slightly lossy path is far worse than a short, clean one, and a fraction of a percent of loss on a transcontinental link is a serious problem.

C# · TcpMath27 lines
public static class TcpMath
{
    public static double BandwidthDelayProductBytes(double bitsPerSecond, double rttSeconds) => bitsPerSecond / 8 * rttSeconds;

    /// <summary>The most one connection can move per second with `windowBytes` outstanding: window / RTT, in bits per second.</summary>
    public static double WindowLimitedBitsPerSecond(double windowBytes, double rttSeconds) => windowBytes * 8 / rttSeconds;

    /// <summary>The Mathis approximation for loss-limited throughput of a Reno-style connection, in bits per second.</summary>
    public static double MathisBitsPerSecond(double mssBytes, double rttSeconds, double lossRate, double c = 1.22) =>
        mssBytes * 8 / rttSeconds * (c / Math.Sqrt(lossRate));

    /// <summary>Round trips needed to send `bytes` in slow start from an initial window of `initialSegments`, with no loss.</summary>
    public static int SlowStartRounds(long bytes, int mssBytes = 1460, int initialSegments = 10)
    {
        long segments = (bytes + mssBytes - 1) / mssBytes;
        int rounds = 0;
        long sent = 0, window = initialSegments;
        while (sent < segments) { sent += window; window *= 2; rounds++; }
        return rounds;
    }

    /// <summary>The delay a full buffer adds: the time to drain `bufferBytes` at the link rate.</summary>
    public static double QueueDelayMs(double bufferBytes, double linkBitsPerSecond) => bufferBytes * 8 / linkBitsPerSecond * 1000;

    /// <summary>Share of the wire bytes that are payload for a TCP segment over IPv4 and Ethernet (40 bytes of IP and TCP headers, 38 of Ethernet).</summary>
    public static double PayloadShare(int payloadBytes) => payloadBytes / (double)(payloadBytes + 40 + 38);
}
C#13 lines
Debug.Assert(Math.Abs(TcpMath.BandwidthDelayProductBytes(1e9, 0.08) - 10_000_000) < 1e-3);           // a gigabit path at 80 ms holds 10 MB

double windowLimited = TcpMath.WindowLimitedBitsPerSecond(65_535, 0.08);
Debug.Assert(Math.Abs(windowLimited - 6.55e6) < 0.01e6);                                              // 6.6 Mbps on a gigabit link
Debug.Assert(Math.Abs(TcpMath.WindowLimitedBitsPerSecond(4 * 1024 * 1024, 0.08) - 419.4e6) < 0.1e6);  // a 4 MiB window: about 420 Mbps

Debug.Assert(Math.Abs(TcpMath.MathisBitsPerSecond(1460, 0.08, 1e-4) - 17.8e6) < 0.1e6);              // 0.01% loss: about 18 Mbps
Debug.Assert(Math.Abs(TcpMath.MathisBitsPerSecond(1460, 0.08, 1e-6) - 178e6) < 1e6);                  // 0.0001% loss: about 180 Mbps

Debug.Assert(TcpMath.SlowStartRounds(15_000) == 2);
Debug.Assert(TcpMath.SlowStartRounds(100_000) == 3);
Debug.Assert(TcpMath.SlowStartRounds(1_000_000) == 7);
Debug.Assert(TcpMath.SlowStartRounds(10_000_000) == 10);

HLD

Small messages: headers, Nagle and delayed ACKs

Every packet carries headers: 40 bytes of IP and TCP, 38 of Ethernet framing and gaps. A full 1,460-byte segment is 95% payload; a 100-byte message is 56% payload and 44% overhead. Many small writes also mean many packets and many system calls, which is the packet-rate cost described in the inspection gateway case study.

Two old mechanisms interact badly with small request/response traffic:

  • Nagle's algorithm holds back a small write while earlier data is still unacknowledged, so tiny segments get coalesced.
  • Delayed acknowledgement makes a receiver wait (on Linux, a minimum of about 40 ms and at most 200 ms) hoping to piggyback its ACK on outgoing data.

When an application writes a message in two small pieces, the second piece waits for the ACK of the first, and the receiver is waiting 40 ms before sending that ACK. The result is a 40 ms stall on a request that should take a millisecond, often seen at the median, not just the tail. Fixes: disable Nagle with TCP_NODELAY (in .NET, socket.NoDelay = true), and, more importantly, write each message with a single call, so there is nothing to coalesce. On Linux, TCP_QUICKACK is the receiver-side counterpart.

C#
Debug.Assert(Math.Abs(TcpMath.PayloadShare(1460) - 0.949) < 0.001);          // a full segment is 95% payload
Debug.Assert(Math.Abs(TcpMath.PayloadShare(100) - 0.562) < 0.001);           // a 100-byte message wastes 44% of the wire

HLD

Packet size: MTU, MSS and the path

The MTU is the largest packet a link carries (1,500 bytes on standard Ethernet; jumbo frames of about 9,000 are common inside datacenters). The MSS is the largest TCP payload a segment carries, usually MTU minus 40 bytes of headers, so 1,460. A path's effective MTU is the smallest along it, and tunnels shrink it: VXLAN, GRE and IPsec each add bytes of encapsulation.

Hosts find the path MTU by sending packets with the "don't fragment" flag and reading the ICMP "fragmentation needed" messages that come back. If a firewall drops those ICMP messages, packets bigger than the real MTU vanish silently: connections open, small requests work, and large transfers hang. This is a PMTU black hole, and the symptom ("small works, big hangs, especially over a VPN") is a classic. Fixes: allow the required ICMP messages, and clamp the MSS at the tunnel endpoints so TCP never sends a segment that will not fit.

HLD

Queues in the network: bufferbloat

A buffer that holds 1 MB in front of a 10 Mbps uplink adds up to 8,000,000 ÷ 10,000,000 = 800 ms of delay when it is full. Large, unmanaged buffers keep links busy and make interactive traffic wait behind bulk transfers: the link shows full throughput while latency under load is terrible. This is bufferbloat. The remedies are the queue-discipline ideas from the overload lesson, applied to packets: active queue management that keeps standing queues short (CoDel and its flow-queueing variants), explicit congestion notification, and congestion control that does not need a full buffer to find the rate (BBR). When measuring, report latency under load, not only on an idle link.

C#
Debug.Assert(Math.Abs(TcpMath.QueueDelayMs(1_000_000, 10e6) - 800) < 1e-9);       // a full 1 MB buffer on a 10 Mbps link: 800 ms

Work from the outside in, as with any bottleneck.

  1. Is it the path or the host? Check round-trip time and loss with ping and mtr. Compare a single connection with several in parallel (iperf3): if parallel streams reach the link rate, one stream is window- or loss-limited.
  2. What is TCP doing? ss -ti shows each connection's congestion window, round-trip time, retransmits and whether it is limited by the sender, the receiver's window or the network. A small, constant window points to buffer limits or a missing window scale.
  3. Is there loss or reordering? A packet capture (tcpdump, then Wireshark) shows retransmissions, duplicate ACKs, zero-window advertisements and handshake timing.
  4. Is a host the limit? One CPU core saturated by network interrupts, an interface dropping packets, or offloads misconfigured: check per-core CPU, interface statistics and the receive queue drops.
  5. Is something in the middle? Firewalls, proxies and inspection devices can cap per-flow rates, strip options, drop ICMP or add delay. Compare a path through the device with one around it.
  6. Reproduce it. tc netem on a Linux host adds delay, loss and reordering, so you can test with a realistic wide-area path in the lab.
QuestionToolWhat it shows
How long and how lossy is the path?ping, mtrRound-trip time and loss per hop
What can one connection do?iperf3 (one stream, then several)Single-flow versus aggregate throughput
What is TCP doing right now?ss -tiWindow, round-trip time, retransmits, what limits the flow
Where are packets lost or delayed?tcpdump and WiresharkRetransmissions, duplicate ACKs, zero windows, handshake timing
Is the network card or kernel the limit?ethtool -S, sar -n DEV, /proc/net/softnet_statDrops, errors, per-core network processing
Can I reproduce a wide-area link?tc netemAdded delay, loss and reordering

Senior depth

What senior interviews ask about network performance

Interviewer follow-upL5A single download between two datacenters gets 7 Mbps on a 1 Gbps link with an 80 ms round trip. What do you check?How to answer

The bandwidth-delay product is 10 MB, and a 64 KB window gives 65,535 ÷ 0.08 = 6.6 Mbps, which matches. So check window scaling and socket buffer limits on both ends, and whether a middlebox strips the option. Then check loss, since 0.01% loss alone caps a Reno-style flow near 18 Mbps at that round trip. Confirm with ss -ti and a packet capture, and try parallel streams to see whether the link itself can carry more.

Interviewer follow-upL6Why does terminating TLS near the user make a global application faster even when the origin is far away?How to answer

The handshake needs two or three round trips, and near the user each one is cheap. The edge keeps warm, long-lived connections to the origin, so the user does not pay the origin's handshakes or slow start. A new TLS 1.3 connection to an origin 160 ms away costs about 480 ms to the first byte; through an edge 20 ms away it is about 200 ms. The same idea applies to connection pools between services and to sticking with fewer, longer-lived connections.

Interviewer follow-upL6Small request/response calls occasionally take about 40 ms extra. Why?How to answer

Likely Nagle's algorithm interacting with delayed acknowledgements: a message written in two parts, where the second part waits for the ACK of the first and the receiver delays that ACK for about 40 ms. Fix it by writing each message in a single call, and set TCP_NODELAY on the socket so small writes are sent immediately. Verify with a capture, which shows the gap before the second segment.

Interviewer follow-upL6Large transfers over a VPN hang, but small requests work. What is going on?How to answer

A path MTU problem. The tunnel adds encapsulation, so the usable MTU is smaller than the sender assumes, and the ICMP messages that would tell it so are being dropped, creating a black hole for large packets. Allow the needed ICMP, or clamp the TCP MSS at the tunnel endpoint so segments fit.

Interviewer follow-upL7Throughput between two sites is well below the link rate. Walk me through the diagnosis.How to answer

Establish whether the limit is per flow or in the path with single and parallel iperf3 runs. Compute the bandwidth-delay product and compare it with the observed window in ss -ti; look at retransmissions and the loss rate against the Mathis estimate; take a capture to separate loss, reordering and receiver-window stalls. Check hosts for a saturated core handling interrupts, interface drops and offload settings. Check middleboxes for per-flow limits, option stripping or inspection overhead, and test with the device bypassed. Consider the congestion control algorithm and queueing on the path. Reproduce with netem and change one thing at a time.

Interviewer follow-upL7How do you choose keep-alive and pool settings between two services?How to answer

Size the pool with Little's Law (in-flight requests = request rate × latency, with headroom) so requests do not queue for a connection. Keep connections long-lived so handshakes and slow start are amortized, and warm them before traffic arrives. Make the server's idle timeout longer than the client's pool idle timeout, otherwise the client reuses a connection the server has just closed and gets a reset on the first request. Cap lifetime so load balancers can rebalance, and watch the new-connection rate: spikes in it mean churn that costs handshakes.

Interviewer follow-upL7HTTP/2 or HTTP/3 for a mobile API?How to answer

Mobile networks have higher and variable round trips, real loss and changing addresses. HTTP/3 over QUIC saves a handshake round trip, avoids TCP's head-of-line blocking (a lost packet stalls only its own stream, not every stream on the connection) and can survive a change of network without a new handshake. HTTP/2 over TCP is simpler to operate and may be better inspected and tuned in some enterprise paths, where UDP can be blocked or throttled. Measure on the real population, keep a fallback to HTTP/2, and compare the tail latency and the handshake share of requests.

HLD

How to answer a network performance question in an interview

  1. Compute the floor: distance gives the round-trip time, and no tuning goes below it.
  2. Count round trips: connection setup, then the request, then slow start for the transfer size.
  3. Compute the bandwidth-delay product and compare it with the window, or throughput with window ÷ round-trip time.
  4. Include loss: the Mathis estimate, and which congestion control is in use.
  5. Check small-message behavior: headers, Nagle, delayed ACK, write batching.
  6. Check the path: MTU and MSS, middleboxes, buffers and latency under load.
  7. Name the tools and the order you would use them, and reproduce with a controlled delay.

Summary

Distance sets the latency floor, and short requests are paid for in round trips: handshakes, then one trip for the request, then slow start for anything beyond a few kilobytes. A connection can move at most its window per round trip, so a fast long link needs a window as large as the bandwidth-delay product, and loss caps throughput roughly in proportion to 1 ÷ (round-trip time × √loss). Small writes meet Nagle and delayed ACKs, mismatched MTUs create black holes, and big buffers create bufferbloat. Diagnose from the path inward with ping, iperf3, ss -ti and a capture, and reproduce with netem.

Check yourself

Try answering out loud before you reveal each answer.

QuestionA path has 1 Gbps of bandwidth and an 80 ms round-trip time. How much data must be in flight to fill it, and what is the throughput of a connection stuck with a 64 KB window?Reveal answer

The bandwidth-delay product is 1 Gbps × 80 ms = 10 MB. With a 64 KB window, throughput is at most 65,535 B ÷ 0.08 s, about 819 KB/s, or 6.6 Mbps.

QuestionHow many round trips before the first response byte on a new TCP connection with TLS 1.3, and what is that at an 80 ms round trip?Reveal answer

Two before the request (TCP handshake, TLS 1.3 handshake) plus one for the request and response: three round trips, 240 ms. A reused connection needs one (80 ms), a new QUIC connection two (160 ms).

QuestionA service sees steady 40 ms extra latency on small messages. What are the two mechanisms, and what are the fixes?Reveal answer

Nagle's algorithm holds the second small write until the first is acknowledged, and the receiver's delayed acknowledgement waits about 40 ms before acknowledging. Write each message in one call, and set TCP_NODELAY (socket.NoDelay = true in .NET).

Sources and further reading

  • Mathis, Semke, Mahdavi and Ott, "The Macroscopic Behavior of the TCP Congestion Avoidance Algorithm", ACM SIGCOMM Computer Communication Review, 1997: the throughput approximation. Padhye and co-authors give a more accurate model at higher loss.
  • IETF RFC 7323 (TCP extensions for high performance, including window scaling), RFC 6928 (increasing TCP's initial window to 10 segments), RFC 8446 (TLS 1.3), RFC 9000 (QUIC) and RFC 896 (Nagle's algorithm).
  • Van Jacobson, "Congestion Avoidance and Control", SIGCOMM 1988: slow start and congestion avoidance.
  • Kathleen Nichols and Van Jacobson, "Controlling Queue Delay", ACM Queue, 2012: CoDel, the answer to bufferbloat.
  • Brendan Gregg, Systems Performance, 2nd edition, Addison-Wesley, 2020, for the network analysis tools in the diagnosis section.
Lesson 18 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 19Observability: metrics, logs and tracesWhat metrics, logs and traces are each for and how a trace id joins them, the golden signals, the cost of a label, W3C trace context and head versus tail sampling tested in C#, logs that help, and how telemetry fails.

Send a message

It goes straight to my inbox. I usually reply within a few days.