28.5. Diagnosing Network and Application Bottlenecks

A slow request is often not slow on the host at all. It may be waiting for a name to resolve, for a TCP handshake, for a TLS handshake, for a backend, or for a congested path. The network counters separate those possibilities, and controlled traffic provides a known baseline.

28.5.1. Interface Drops, Retransmissions, and Socket Queues

Start with the interface counters. The commands used in this subsection are:

Command Description
ip -s link show IFACE Show bytes, packets, errors, drops, and missed frames.
ss -s Summarize sockets by protocol and state.
ss -lnt List listening TCP sockets with receive and send queues.
nstat -az Show all network counters, including zero-valued ones, with rates.

On perf1, ip -s link reports bytes, packets, errors, drops, and missed frames:

$ ip -s link show eth1
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
    link/ether 52:54:00:0a:36:40 brd ff:ff:ff:ff:ff:ff
    RX:    bytes packets errors dropped  missed   mcast
   21712177  170828      0    2512       0       0
    TX:    bytes packets errors dropped carrier collsns
    21897323065  474184      0       0       0       0
    altname enp0s7
    altname ens7
    altname enx5254000a3640

Received drops of 2,512 with no receive errors point to a queue or buffer problem rather than corrupt frames; transmitted drops and collisions are zero. The counters are cumulative, so compare two readings or use nstat for rates. nstat exposes TCP retransmission and loss counters as rates; a measurement taken after the controlled-loss test appears in Section 28.5.2. A nonzero retransmission count is not automatically a problem, but a rising rate alongside falling throughput is. ss shows listener and established-socket queues:

$ ss -lnt
State  Recv-Q Send-Q  Local Address:Port Peer Address:Port
LISTEN 0      511    192.168.228.10:80        0.0.0.0:*
LISTEN 0      32            0.0.0.0:53        0.0.0.0:*
LISTEN 0      511    192.168.228.10:443       0.0.0.0:*
LISTEN 0      128           0.0.0.0:22        0.0.0.0:*
LISTEN 0      5           127.0.0.1:8080      0.0.0.0:*
LISTEN 0      32               [::]:53           [::]:*
LISTEN 0      128              [::]:22           [::]:*
LISTEN 0      4096                *:9093            *:*
LISTEN 0      4096                *:9094            *:*
LISTEN 0      4096                *:9090            *:*
LISTEN 0      4096                *:9100            *:*
LISTEN 0      4096                *:9115            *:*

For a listening socket, Recv-Q is the current accept backlog and Send-Q is the configured maximum. A backlog near the limit with connection timeouts is a sign that the application is not accepting connections quickly enough, not that the network is dropping packets. ss -s gives a protocol summary:

$ ss -s
Total: 134
TCP:   54 (estab 8, closed 34, orphaned 0, timewait 34)

Transport Total     IP        IPv6
RAW   0         0         0
UDP   6         3         3
TCP   20        9        11
INET      26        12        14
FRAG      0         0         0

The timewait count is normal for short-lived connections; a large number of orphaned sockets would point to a process that closed descriptors without reading responses.

28.5.2. Measuring Network Paths with Controlled Traffic

ping measures round-trip time and loss on a path, and iperf3 measures achievable TCP throughput. The ping and iperf3 options used here are:

Option Description
ping -c COUNT Send COUNT probes and exit.
ping -W SECONDS Wait at most SECONDS for each reply before declaring it lost.
iperf3 -s Run as the test server.
iperf3 -B ADDRESS Bind the server to one local address.
iperf3 -1 Serve one test and exit instead of waiting for more.
iperf3 -c HOST Run as a client against HOST.
iperf3 -t SECONDS Run the test for the given duration.

Start the one-shot server on perf2, in the root shell; because of -1 it will need to be started again for each later test:

# systemd-run --unit=iperf-srv --uid=john --collect iperf3 -s -B 192.168.228.20 -1
Running as unit: iperf-srv.service; invocation ID: f7268fbac689456db0d9df4fa11dc129

From perf1, run a three-second client:

$ iperf3 -c 192.168.228.20 -t 3
Connecting to host 192.168.228.20, port 5201
[  5] local 192.168.228.10 port 34488 connected to 192.168.228.20 port 5201
[ ID] Interval           Transfer     Bitrate         Retr  Cwnd
[  5]   0.00-1.00   sec  1.50 GBytes  12.9 Gbits/sec    2   4.17 MBytes
[  5]   1.00-2.00   sec  1.65 GBytes  14.2 Gbits/sec    0   4.17 MBytes
[  5]   2.00-3.00   sec  1.59 GBytes  13.7 Gbits/sec    0   4.17 MBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bitrate         Retr
[  5]   0.00-3.00   sec  4.75 GBytes  13.6 Gbits/sec    2            sender
[  5]   0.00-3.00   sec  4.75 GBytes  13.6 Gbits/sec                  receiver

iperf Done.

The isolated virtio link reaches about 13.6 Gbit/s with two retransmissions. That is a baseline for this pair of guests, not a prediction for physical hardware. On perf1, add a known delay to the existing eth1 queue. The traffic-control options used here are:

Option Description
tc qdisc add dev eth1 root netem Install a network emulator as the root queue discipline.
delay 20ms Add a fixed one-way delay.
loss 2% Drop two percent of packets.
tc qdisc del dev eth1 root Remove the emulator and restore the default queue.

The delay is applied with:

$ sudo tc qdisc add dev eth1 root netem delay 20ms

tc prints nothing when the change succeeds; the ping below is what confirms it. On perf1:

$ ping -c 4 -W 2 192.168.228.20
PING 192.168.228.20 (192.168.228.20) 56(84) bytes of data.
64 bytes from 192.168.228.20: icmp_seq=1 ttl=64 time=20.4 ms
64 bytes from 192.168.228.20: icmp_seq=2 ttl=64 time=20.6 ms
64 bytes from 192.168.228.20: icmp_seq=3 ttl=64 time=20.3 ms
64 bytes from 192.168.228.20: icmp_seq=4 ttl=64 time=20.4 ms

--- 192.168.228.20 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 20.344/20.416/20.560/0.084 ms

Remove the delay before the next test; as before, the removal is silent:

$ sudo tc qdisc del dev eth1 root

A 2 percent loss rate produces a different symptom. On perf2, repeat the one-shot server command from above. On perf1, apply loss to eth1, again silently:

$ sudo tc qdisc add dev eth1 root netem loss 2%
$ iperf3 -c 192.168.228.20 -t 5
Connecting to host 192.168.228.20, port 5201
[  5] local 192.168.228.10 port 39490 connected to 192.168.228.20 port 5201
[ ID] Interval           Transfer     Bitrate         Retr  Cwnd
[  5]   0.00-1.00   sec   183 MBytes  1.54 Gbits/sec  2714   36.8 KBytes
[  5]   1.00-2.00   sec   211 MBytes  1.77 Gbits/sec  2902   19.8 KBytes
[  5]   2.00-3.00   sec   231 MBytes  1.94 Gbits/sec  2939   36.8 KBytes
[  5]   3.00-4.00   sec   147 MBytes  1.24 Gbits/sec  1996    279 KBytes
[  5]   4.00-5.00   sec   141 MBytes  1.18 Gbits/sec  2129   18.4 KBytes
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bitrate         Retr
[  5]   0.00-5.00   sec   913 MBytes  1.53 Gbits/sec  12680            sender
[  5]   0.00-5.00   sec   909 MBytes  1.52 Gbits/sec                  receiver

iperf Done.

Throughput falls from about 13.6 to 1.53 Gbit/s, and the sender reports 12,680 retransmissions. nstat confirms the kernel's view:

$ nstat -az | grep -E '^TcpRetransSegs|^TcpExtTCPLostRetransmit'
TcpRetransSegs                  88970              0.0
TcpExtTCPLostRetransmit         1611              0.0

The counters are cumulative; the delta between two readings is the useful signal. On perf1, remove the loss and restore the normal queue; the removal prints nothing:

$ sudo tc qdisc del dev eth1 root

tc netem is a guest-local test tool. It changes the isolated interface only; do not apply it to a production path unless you intend to degrade that traffic.

28.5.3. Tracing Application Delays with strace and perf

When the host and network look healthy, trace the application on perf1. The tracing options used in this section are:

Option Description
strace -c -f command Summarize syscall time and counts for the command and its children.
strace -T -e trace=set Print the duration of each call in the selected set.
perf record -g -e cpu-clock Sample CPU stacks with a software event.
perf report --stdio --percent-limit N Print resolved samples above a percentage threshold.

strace -c summarizes syscall time and call counts for a command:

$ strace -c -f curl -s -o /dev/null http://192.168.228.10/
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 32.80    0.003585          22       159           mmap
 13.51    0.001477          21        68        16 openat
  8.56    0.000936          16        56           close
  8.28    0.000905          26        34           mprotect
  8.09    0.000884          16        53           fstat
  6.58    0.000719          17        42           clock_gettime
  6.36    0.000695          16        42           read
  3.01    0.000329         329         1           execve
  2.89    0.000316          14        22           rt_sigaction
  1.38    0.000151          15        10            brk
  1.29    0.000141          47         3         3 connect
------ ----------- ----------- --------- --------- ----------------
100.00    0.010930          19       555        24 total

Selected output is shown. The total syscall time is 10.9 ms, with mmap, openat, and process startup dominating; the connect calls take little time. For a delay inside a single call, -T prints the duration after the return value:

$ strace -T -e trace=clock_nanosleep sleep 0.25
clock_nanosleep(CLOCK_REALTIME, 0, {tv_sec=0, tv_nsec=250000001}, 0x7ffc3dd1a350) = 0 <0.250359>
+++ exited with 0 +++

The <0.250359> is the time spent in the sleep call. If the same delay appeared inside a read, poll, or connect, the trace would point at the layer that blocked. strace adds overhead, so use it on a bounded reproduction, not as a permanent production profiler.

For CPU time inside the application, perf record samples the call stack and perf report groups the samples by function:

$ sudo perf record -g -e cpu-clock -o /tmp/perf.data python3 /home/john/debian-handbook/performance/cpu-work.py 5000000
loops=5000000 checksum=360452801 elapsed=1.328s
[ perf record: Woken up 2 times to write data ]
[ perf record: Captured and wrote 0.376 MB /tmp/perf.data (5357 samples) ]

The first line is the measured program's own output. The bracketed lines are perf's capture summary, written to standard error: the samples were flushed in two batches and stored in /tmp/perf.data. Selected output from the report is shown; the leading banner, the call-graph continuation lines under each entry, and the closing tip line are omitted:

$ sudo perf report --stdio -i /tmp/perf.data --percent-limit 5
# Samples: 5K of event 'cpu-clock'
# Event count (approx.): 1339250000
#
# Children      Self  Command  Shared Object         Symbol
# ........  ........  .......  ....................  .....................................
#
    25.44%    25.44%  python3  python3.13            [.] _PyEval_EvalFrameDefault
    16.76%     0.00%  python3  [unknown]             [.] 0x0000000000a06b80
    16.15%     0.00%  python3  [unknown]             [.] 0x0000000000a06ec0
    10.47%     0.00%  python3  [unknown]             [.] 0x075300220b5c0020
     6.57%     0.00%  python3  [unknown]             [.] 0x0020000b0104104d

The named Python interpreter frame accounts for a quarter of the samples; the unnamed addresses are unresolved library or generated frames. On a Debian system, installing debug symbols for the relevant packages resolves more frames, but even the unresolved profile distinguishes interpreter work from kernel or I/O time. perf hardware events may be unavailable in a virtual machine; cpu-clock is a software event and is sufficient to find a hot function.

28.5.4. Separating DNS, Connection, TLS, and Backend Latency

The timing measurements on perf1 use a local TLS service. The Python backend from Section 28.1 listens on 127.0.0.1:8080; nginx terminates TLS for backend.perf.lab and proxies two paths to that backend. The certificate is self-signed for the example. The openssl options used to generate it are:

Option Description
req -x509 Produce a self-signed certificate rather than a signing request.
-newkey rsa:2048 Generate a new 2048-bit RSA key.
-nodes Store the key unencrypted.
-days N Set the certificate's validity period.
-subj /CN=NAME Supply the subject non-interactively.
-addext subjectAltName=DNS:NAME Add the name clients actually verify.

Create a directory for the key material; the command is silent:

$ sudo install -d /etc/nginx/tls

Then generate the key and certificate:

$ sudo openssl req -x509 -newkey rsa:2048 -sha256 -nodes -days 2 \
    -subj /CN=backend.perf.lab \
    -addext subjectAltName=DNS:backend.perf.lab \
    -keyout /etc/nginx/tls/backend.key -out /etc/nginx/tls/backend.crt

openssl writes the two files and prints a short burst of key-generation progress (....+...) on standard error; nothing appears on standard output. Restrict the key's permissions; this command also prints nothing:

$ sudo chmod 600 /etc/nginx/tls/backend.key

Write the nginx server block:

server {
    listen 192.168.228.10:80;
    listen 192.168.228.10:443 ssl;
    server_name backend.perf.lab;

    ssl_certificate     /etc/nginx/tls/backend.crt;
    ssl_certificate_key /etc/nginx/tls/backend.key;

    location /slow {
        proxy_pass http://127.0.0.1:8080;
    }

    location /variable {
        proxy_pass http://127.0.0.1:8080;
    }

    location / {
        root /var/www/html;
        index index.nginx-debian.html;
    }
}

Save it as /etc/nginx/sites-available/perf.conf. Enable it, and remove the package's default site, whose wildcard listen 80 conflicts with the specific address this server block binds:

$ sudo ln -s /etc/nginx/sites-available/perf.conf /etc/nginx/sites-enabled/perf.conf

The command is silent. Removing the default site's symlink disables it without deleting the file in sites-available:

$ sudo rm /etc/nginx/sites-enabled/default

That command is also silent. Validate the configuration:

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Then apply it; the restart is silent:

$ sudo systemctl restart nginx

Name resolution for the example is provided by a local dnsmasq. Add its address record in /etc/dnsmasq.d/perf.conf:

address=/backend.perf.lab/192.168.228.10

Apply that as well; the restart prints nothing:

$ sudo systemctl restart dnsmasq

The --resolve option in the curl commands below supplies the address directly so that DNS is measured separately by dig; that is deliberate, not an omission.

curl -w prints a timing breakdown for one request. The variables used here are cumulative phases:

Variable Meaning
time_namelookup Time until name resolution completes.
time_connect Time until the TCP handshake completes.
time_appconnect Time until the TLS handshake completes.
time_starttransfer Time until the first response byte arrives.
time_total Total time until the transfer completes.
http_code HTTP status code.

The values are cumulative: subtract successive phases to get the duration of each stage:

$ curl -sS -o /dev/null -w 'dns=%{time_namelookup}s connect=%{time_connect}s tls=%{time_appconnect}s ttfb=%{time_starttransfer}s total=%{time_total}s http=%{http_code}\n' --resolve backend.perf.lab:443:192.168.228.10 --cacert /etc/nginx/tls/backend.crt https://backend.perf.lab/
dns=0.000019s connect=0.000150s tls=0.010355s ttfb=0.011899s total=0.011941s http=200
$ curl -sS -o /dev/null -w 'dns=%{time_namelookup}s connect=%{time_connect}s tls=%{time_appconnect}s ttfb=%{time_starttransfer}s total=%{time_total}s http=%{http_code}\n' --resolve backend.perf.lab:443:192.168.228.10 --cacert /etc/nginx/tls/backend.crt https://backend.perf.lab/slow
dns=0.000032s connect=0.000259s tls=0.008568s ttfb=0.263514s total=0.263580s http=200

The --resolve option supplies the address so the request does not depend on DNS; it is what makes dns nearly zero here. DNS is measured separately with dig. Its +stats option requests the query-time and message-size lines; it is enabled by default, so a plain dig prints them too:

$ dig +stats backend.perf.lab @127.0.0.1
; <<>> DiG 9.20.30-1~deb13u1-Debian <<>> +stats backend.perf.lab @127.0.0.1
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8277
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;backend.perf.lab.      IN  A

;; ANSWER SECTION:
backend.perf.lab.   0   IN  A   192.168.228.10

;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1) (UDP)
;; WHEN: Tue Nov 24 00:38:54 UTC 2026
;; MSG SIZE  rcvd: 61

The local dnsmasq answers from its cache in under a millisecond. In a production incident, run dig against the resolver the application actually uses, and compare a cached name with an uncached one. A slow resolver adds to time_namelookup; a slow TLS handshake adds to the difference between time_connect and time_appconnect; a slow backend adds to the difference between time_appconnect and time_starttransfer.

Latency waterfall

Figure 28.6. Measured request phases from the two curl requests. The slow path adds roughly 0.25 seconds behind the TLS handshake; connection setup and the handshake are essentially unchanged.

The full timing command is verbose. A shell function or a small script can make it repeatable, but keep the raw values for the incident record. curl supports HTTP/2 and connection reuse, so repeated measurements may skip the handshake; use fresh connections or --no-keepalive when handshake time is the subject.