Self-Hosted eBPF-Based TCP Retransmission and Packet Loss Root-Cause Analysis with tcpdump and BCC
Quick Summary (TL;DR)
- Problem: Silent packet loss causes TCP retransmissions that degrade throughput and latency, but traditional tools can’t tell you which socket, process, or kernel path is affected.
- Solution: Combine tcpdump (packet-level forensics) with BCC/bpftrace (kernel-level socket tracing) for full-stack visibility.
- Workflow: Baseline with tcpdump → trace sockets with
tcpretrans/tcprtt→ deep-dive with bpftrace → correlate timestamps → remediate.- Key tools:
tcpdump,tcpconnect,tcpaccept,tcpretrans,tcprtt, custombpftraceprobes.- Payoff: Identify loss patterns (congestion vs. hardware vs. bufferbloat) in minutes instead of hours of packet-capture archaeology.
Introduction: Why Silent Packet Loss Is Hard to Diagnose
TCP is designed to hide loss from applications. It retransmits, reorders, and reshuffles segments until the byte stream looks perfect to your application — which is precisely why silent loss is so insidious. By the time users notice latency or throughput drops, the kernel has already been quietly retransmitting for minutes or hours.
In self-hosted environments the problem is compounded. You own the whole stack — physical NICs, virtual switches, overlay networks (VXLAN, WireGuard), and the kernel itself — so there’s no cloud provider dashboard to blame. You need ground truth from inside the kernel.
That’s where eBPF shines. Instead of capturing every packet and analyzing it offline, eBPF lets you attach probes to kernel functions like tcp_retransmit_skb, tcp_rcv_established, and tcp_sendmsg and get real-time, per-socket metrics with negligible overhead. Combined with tcpdump for packet-level forensics, you get a complete root-cause analysis workflow.
Prerequisites and Environment Setup
Kernel and Tooling Requirements
eBPF requires a reasonably modern kernel. Here’s the minimum baseline:
| Component | Minimum | Recommended |
|---|---|---|
| Linux kernel | 4.9 (basic) | 5.15+ or 6.x |
| BTF support | 5.2+ | 5.8+ (CO-RE) |
bpftrace | 0.9 | 0.20+ |
| BCC | 0.10 | 0.28+ |
| Privileges | CAP_BPF + CAP_NET_ADMIN | root or sudo |
| Distro | Ubuntu 20.04 / RHEL 8 | Ubuntu 22.04 / RHEL 9 |
Verify your kernel supports BTF (needed for CO-RE and modern bpftrace):
uname -r
ls /sys/kernel/btf/vmlinux # should exist on 5.2+
sysctl kernel.unprivileged_bpf_disabled # 0 or 2 is fine
Installing BCC and bpftrace
On Debian/Ubuntu:
sudo apt update
sudo apt install -y bpfcc-tools bpftrace linux-headers-$(uname -r) \
python3-bpfcc tcpdump
On RHEL/Rocky/Alma:
sudo dnf install -y bcc-tools bpftrace kernel-devel-$(uname -r) tcpdump
Confirm the tools work:
sudo tcpretrans -h
sudo bpftrace -l 'tracepoint:tcp:*'
If bpftrace -l lists tracepoints, you’re ready to go.
Understanding TCP Retransmission Mechanisms
Retransmission Timeout (RTO) and Fast Retransmit
TCP recovers from loss through two primary mechanisms:
- Fast Retransmit — triggered by three duplicate ACKs. The sender retransmits the missing segment immediately, typically in tens of milliseconds. This is the “healthy” recovery path.
- Retransmission Timeout (RTO) — triggered when no ACK arrives before a timer expires. RTO is computed from smoothed RTT and variance (RFC 6298), with a minimum of ~200ms and exponential backoff on repeated failure. RTO-based retransmits signal serious loss or path failure.
If you see mostly fast retransmits, you have congestion or isolated drops. If you see RTO events, you likely have a broken path, overloaded receiver, or hardware fault.
How eBPF Provides Visibility
eBPF lets you attach kprobes to the exact kernel functions that handle retransmission, ACK processing, and RTT estimation. The kernel already tracks per-socket state — eBPF just surfaces it. The trade-off is: tcpdump sees packets on the wire, eBPF sees socket state in the kernel. Together they triangulate the root cause.
flowchart TD
A[Application write] --> B[tcp_sendmsg]
B --> C[TCP transmit queue]
C --> D{Loss detected?}
D -- No --> E[ACK received<br/>tcp_rcv_established]
D -- Yes, 3 dup ACKs --> F[Fast retransmit<br/>tcp_retransmit_skb]
D -- Yes, RTO expiry --> G[RTO retransmit<br/>tcp_retransmit_skb]
F --> H[eBPF probe: tcpretrans]
G --> H
E --> I[eBPF probe: tcprtt]
H --> J[Kernel ring buffer]
I --> J
J --> K[Userspace: BCC / bpftrace]
K --> L[Correlate with tcpdump]
Step 1: Baseline Your Network with tcpdump
Capturing Retransmissions with tcpdump
Start with a bounded, rotating capture on the affected host. Don’t capture “everything” — that’s how you fill disks and lose the incident.
sudo tcpdump -i eth0 -s 128 -w /var/capture/$(hostname)-$(date +%s).pcap \
-G 300 -W 12 'tcp and (port 443 or port 5432)'
-s 128truncates payloads (headers are all you need for retransmit analysis).-G 300 -W 12rotates a new file every 5 minutes, keeping 12 files (1 hour).- The BPF filter scopes to the ports you care about.
Analyzing Capture Files
tcpdump can flag retransmissions directly with -vv:
tcpdump -r capture.pcap -nn -vv 'tcp' 2>&1 | grep -i retrans
For deeper analysis, load it into Wireshark’s tcp.analysis.retransmission filter, or use tshark:
tshark -r capture.pcap -Y 'tcp.analysis.retransmission' \
-T fields -e frame.time -e ip.src -e ip.dst -e tcp.seq -e tcp.analysis.rto
This gives you a timestamped retransmission list. What it cannot tell you is which process owned the socket, how much data was in flight, or whether the sender was a local server or a client. That’s the gap eBPF fills.
Step 2: Kernel-Level Socket Tracing with BCC
Using tcpconnect and tcpaccept
Before diagnosing retransmits, confirm the connection topology. tcpconnect shows outbound connections with PID and comm:
sudo tcpconnect -t
TIME(s) PID COMM IP SADDR DADDR DPORT
0.000 1234 curl 4 10.0.1.5 93.184.216.34 443
tcpaccept shows inbound accepts:
sudo tcpaccept -t
If you see connections from unexpected PIDs or to unexpected destinations, you may have a routing or NAT issue masquerading as packet loss.
Tracing Retransmits with tcpretrans
tcpretrans is the workhorse for this problem. It hooks tcp_retransmit_skb and prints one line per retransmit:
sudo tcpretrans -l -T
TIME PID IP LADDR:LPORT RADDR:RPORT STATE
14:22:01 4521 4 10.0.1.5:443 198.51.100.7:51234 ESTABLISHED
Key flags:
-lincludes the loss reason (RTOvs.fast retransmit) — critical for triage.-Tadds timestamps.-c Nlimits to N events (useful for sampling).
If a single PID dominates the output, you’ve localized the problem to one application. If many sockets show retransmits to the same destination, the problem is on the path.
Monitoring RTT with tcprtt
tcprtt builds a histogram of round-trip times using the kernel’s own RTT estimator:
sudo tcprtt -i 1 -d 10.0.0.0/8 -b
usecs : count distribution
0 -> 1 : 0 | |
2 -> 3 : 12 |***** |
4 -> 7 : 89 |****************************************|
8 -> 15 : 34 |*************** |
16 -> 31 : 3 |* |
-dfilters by destination CIDR.-bbuckets by latency range.-isets the reporting interval.
A bimodal distribution (a spike at low RTT plus a tail at 100ms+) usually indicates bufferbloat or a congested path. A uniformly high RTT suggests a long-haul path or an overloaded receiver.
Step 3: Deep Dive with bpftrace for Custom Metrics
Tracing Kernel Functions for Packet Loss
When the stock tools aren’t enough, bpftrace lets you instrument exactly what you need. To see which kernel path triggers retransmits per socket:
sudo bpftrace -e '
kprobe:tcp_retransmit_skb
{
@retrans[comm, pid, args->sk->__sk_common.skc_dport] = count();
}
interval:s:10 { print(@retrans); clear(@retrans); }
'
This aggregates retransmissions per process, PID, and destination port, printing every 10 seconds. If you see a single comm dominating, you’ve found the culprit.
Building a Retransmission Heatmap
To correlate retransmits with the local port (useful for load-balanced servers), bucket by port range:
sudo bpftrace -e '
kprobe:tcp_retransmit_skb
{
$port = args->sk->__sk_common.skc_num;
@by_port[($port / 100) * 100] = count();
}
interval:s:30 { print(@by_port); clear(@by_port); }
'
The output groups retransmits into 100-port buckets — instantly showing whether loss concentrates on one service or is spread across the host.
For RTO vs. fast-retransmit differentiation, hook the tracepoints instead:
sudo bpftrace -e '
tracepoint:tcp:tcp_retransmit_skb
{
@reason[args->reason] = count();
}
'
The reason field distinguishes SKB_DROP_REASON_* codes — invaluable for pinpointing whether the kernel dropped the packet or the wire did.
Step 4: Correlating eBPF Data with tcpdump
Time-Synchronized Analysis
The trick to correlating eBPF and tcpdump is consistent timestamps. Both tools use CLOCK_MONOTONIC under the hood but expose it differently:
tcpdumpuses wall-clock by default (with-ttttfor full date).bpftraceand BCC tools use monotonic time.
Normalize by logging wall-clock in bpftrace:
sudo bpftrace -e '
kprobe:tcp_retransmit_skb
{
printf("%llu %s %d %s:%d\n",
nsecs, comm, pid,
ntop(args->sk->__sk_common.skc_daddr),
args->sk->__sk_common.skc_dport);
}
'
Now you can grep both streams for a specific 1-second window and match events. If a tcpretrans event at 14:22:01 corresponds to a tcpdump retransmit at 14:22:01.003, you have a confirmed wire-level loss. If the eBPF event exists but no packet appears on the wire, the kernel dropped it before transmission — a local queue or qdisc issue.
Identifying Loss Patterns
| Pattern | eBPF signal | tcpdump signal | Likely cause |
|---|---|---|---|
| Bursty loss | RTO spikes, many PIDs affected | Retransmits clustered in time | Network congestion |
| Single-socket loss | One PID, one dest | Retransmits on one flow | Application backpressure |
| Loss to one peer | Many PIDs, same dest | Retransmits to one IP | Path/hardware fault |
| No wire packet | eBPF fires, tcpdump silent | Missing | qdisc drop / local buffer |
| Fast retransmit only | -l shows “fast” | 3 dup ACKs | Mild congestion |
Comparison of Tools and Techniques
| Tool | Layer | Overhead | Best for | Limitations |
|---|---|---|---|---|
tcpdump | Wire | Medium–High (I/O, disk) | Forensic packet analysis, evidence | No process/socket context |
tcpretrans | Kernel socket | Very low | Continuous retransmit monitoring | No payload or timing detail |
tcprtt | Kernel socket | Very low | RTT distribution, bufferbloat | Aggregated, no per-flow history |
tcpconnect/tcpaccept | Kernel socket | Very low | Topology discovery | Connection events only |
bpftrace custom | Kernel (any) | Low–Medium | Custom metrics, edge cases | Requires kernel knowledge |
ss -ti | Kernel socket | Negligible | On-demand socket state | Point-in-time snapshot only |
Rule of thumb: Use tcpretrans for monitoring, tcpdump for evidence, and bpftrace for the “why” that neither can answer alone.
Actionable Remediation Strategies
Network Tuning
Start with sysctl tuning matched to your workload:
# /etc/sysctl.d/99-tcp-tuning.conf
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_congestion_control = bbr
net.core.default_qdisc = fq_codel
Apply with sudo sysctl -p /etc/sysctl.d/99-tcp-tuning.conf. BBR + fq_codel is the highest-impact change for most self-hosted deployments — it eliminates bufferbloat-induced RTOs and improves throughput on lossy paths.
Application and Kernel Adjustments
- Verify MTU end-to-end; PMTU black holes cause silent drops on large segments. Use
ping -M do -s 1472to test. - Check NIC offloads — GRO/LRO can mask retransmits from tcpdump. Disable with
ethtool -K eth0 gro off lro offwhen debugging. - Isolate CPU contention — if retransmits correlate with CPU spikes (visible via bpftrace
commaggregation), pin network-heavy processes or enable RPS/RFS. - Audit virtual switches — overlay networks (VXLAN, WireGuard) add encapsulation overhead. Verify MTU is reduced by the tunnel header size (typically 50–80 bytes).
- Upgrade hardware — if
tcpretrans -lshows RTO-heavy loss on a single peer while fast retransmits dominate elsewhere, suspect a bad cable, SFP, or switch port.
Conclusion
Silent packet loss is only silent if you don’t look at the kernel. By pairing tcpdump for wire-level evidence with BCC and bpftrace for socket-level context, you can move from “the network is slow” to “PID 4521 on port 443 to 198.51.100.7 is RTO-retransmitting due to a 5% drop on the path” in a single incident window.
The workflow is repeatable: baseline with tcpdump, monitor with tcpretrans/tcprtt, deep-dive with bpftrace, correlate timestamps, then remediate with BBR + fq_codel and targeted hardware checks. Run the monitoring tools continuously on production hosts — the overhead is negligible, and the alternative is flying blind.
FAQ
What causes TCP retransmissions in self-hosted environments? TCP retransmissions occur when packets are lost or corrupted in transit. Common causes include network congestion, faulty hardware (NICs, cables, switches), misconfigured buffers, and high CPU load leading to delayed ACKs. In self-hosted environments, virtualized network stacks and overlay networks can also introduce loss.
How does eBPF help in diagnosing packet loss compared to traditional tools? eBPF provides kernel-level visibility with low overhead, allowing you to trace socket events, measure RTT, and count retransmissions in real-time without packet capture. It can correlate application behavior with network events, offering insights that tcpdump alone cannot provide, such as which process or socket is affected.
Can I use BCC tools in production without impacting performance?
Yes, BCC tools are designed for production use with minimal overhead. However, always test in a staging environment first. Tools like tcpretrans and tcprtt use in-kernel aggregation and sampling to reduce overhead. Avoid running multiple heavy traces simultaneously and monitor system load.
What is the difference between tcpretrans and tcpdump for retransmission analysis?
tcpdump captures raw packets and can show retransmissions via sequence number analysis, but it requires post-processing and can be resource-intensive. tcpretrans uses eBPF to count retransmissions per socket in real-time, providing immediate insights with less overhead. They are complementary: use tcpdump for detailed packet-level forensics and tcpretrans for continuous monitoring.
How do I interpret RTT measurements from tcprtt?
tcprtt shows the distribution of round-trip times for TCP connections. High RTT variance or spikes indicate network congestion or bufferbloat. Compare RTT across different hosts and times to identify patterns. Use the -d flag to include destination addresses and -b to bucket by latency ranges.
What remediation steps can reduce TCP retransmissions?
Remediation includes tuning TCP parameters (e.g., increasing tcp_rmem and tcp_wmem), enabling selective acknowledgments (SACK), adjusting congestion control algorithms (e.g., BBR), upgrading network hardware, and reducing bufferbloat with fq_codel. Also, ensure proper MTU settings and avoid oversubscription.