Canonical: https://nitride.xyz/blog/backtesting-with-captured-shreds

# Backtesting with shreds you captured yourself

Record the feed yourself with kernel timestamps, keep it as pcap, replay it into your decoder, and know which questions a capture can never answer.

To backtest on Solana shreds, record them yourself. Capture every datagram with a kernel receive timestamp, using tcpdump at nanosecond precision or your own receiver, keep the files as pcap, and replay them into your decoder. Nitride.xyz offers no replay, backfill or historical shreds, so the recording is yours to make.

## Why the recording is yours to make

The feed is live. Shreds go out as they are broadcast ([Solana shreds, explained](https://nitride.xyz/learn/solana-shreds) covers what each datagram holds), and a datagram that missed your socket is gone. There is no replay and no backfill on our side, so if you want to backtest Solana shreds, you start recording before you need the data.

We would argue that is the better arrangement anyway. A backtest built on shreds is a claim about what your strategy would have done with what reached your server. Someone else's archive, even a perfect one, records arrival at their machine, on their route, with their losses. Your own capture records your arrival times, your gaps and your bad minutes. That is the input your bot actually lives on, and the input your backtest should be judged against.

Start the recorder on day one, next to the receiver, and treat it as production. The week you skip is always the week with the event you want to study.

## Capturing with tcpdump

The quickest recorder is tcpdump, run beside your receiver on the same port. It gets its own copy of each packet and does not take anything away from your program's socket:

```sh file="terminal"
sudo tcpdump -i eth0 -n -B 65536 --time-stamp-precision=nano \
  -G 3600 -Z root -w 'shreds-%Y%m%d-%H%M.pcap' 'udp dst port 9000'
```

What each part does, from the tcpdump man page:

- `-B 65536` sets the capture buffer in KiB, so 64 MiB. A small capture buffer is the classic way to lose packets in the recorder itself.
- `--time-stamp-precision=nano` asks for nanosecond timestamps. The default is microseconds, and the file then carries the nanosecond magic number described in pcap-savefile(5).
- `-G 3600` starts a new file every hour, named with the `strftime` pattern in `-w`. Hourly files are easy to compress, copy and delete.
- `-Z root` keeps tcpdump running as root. The man page lets a build drop privileges by default, before any output file is opened, and the build we tested wrote its files as a separate `tcpdump` user. With hourly rotation, that user must be able to create every new file in the directory.

When you stop it, tcpdump prints three counts. Watch `packets dropped by kernel`: it counts packets the capture mechanism lost for lack of buffer space. Anything above zero means the recording has holes your bot may not have had.

One property of tcpdump matters for backtests: it taps packets before the UDP socket's queue. In a test where a socket stopped reading and 3,000 datagrams were sent to it, the socket dropped 2,907 and delivered 93, while tcpdump captured all 3,000. So a tcpdump file records what reached the machine, not what your program read. That is ideal for studying the feed, and misleading if you want to reproduce your bot's own losses.

If your network card can stamp packets in hardware, `tcpdump -J` lists the timestamp types it supports. pcap-tstamp(7) explains the difference between `adapter` stamps, which are synchronized with the system clock, and `adapter_unsynced` ones, which are not. If you are not chasing microseconds, the host stamp is enough.

## Capturing from your own receiver

The other way is to write the file from the program that reads the socket. You then record exactly what your bot received, losses included. This recorder asks the kernel for a receive timestamp on every datagram with `SO_TIMESTAMPNS`, and writes a pcap file that tcpdump and Wireshark can open:

```python file="capture.py"
# capture.py: record every datagram with its kernel receive time into a pcap file.
# usage: python3 capture.py 9000 shreds-0001.pcap   (Linux, 64-bit)
import signal
import socket
import struct
import sys

SO_TIMESTAMPNS = getattr(socket, "SO_TIMESTAMPNS", 35)
LINKTYPE_USER0 = 147   # payload only: the shred bytes, no IP or UDP header
SNAPLEN = 2048

port, path = int(sys.argv[1]), sys.argv[2]
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))   # so kill flushes the file
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 8 << 20)
s.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
s.bind(("0.0.0.0", port))

with open(path, "wb", buffering=1 << 20) as out:
    # pcap file header with the nanosecond magic, version 2.4
    out.write(struct.pack("<IHHiIII", 0xA1B23C4D, 2, 4, 0, 0, SNAPLEN, LINKTYPE_USER0))
    while True:
        data, anc, _, _ = s.recvmsg(SNAPLEN, socket.CMSG_SPACE(16))
        sec = nsec = 0
        for level, kind, value in anc:
            if level == socket.SOL_SOCKET and kind == SO_TIMESTAMPNS:
                sec, nsec = struct.unpack("qq", value[:16])
        out.write(struct.pack("<IIII", sec, nsec, len(data), len(data)))
        out.write(data)
```

The kernel takes that stamp early in the receive path, before it knows which socket the packet is for, so time spent waiting in your socket buffer does not shift it. It is system time (`CLOCK_REALTIME`), which is the part to keep in mind later. [Measuring arrival time on your server](https://nitride.xyz/docs/receiver/arrival-time) goes deeper into kernel and hardware stamps; here the point is only that the stamp comes from the kernel, not from your loop.

Python 3.11 has no constant for the option, hence the fallback to 35, its value on x86-64 and arm64 Linux. The `SIGTERM` handler matters: our first version lost the last buffered records whenever it was stopped with `kill`.

## How to store a capture

Our preferences after a few rounds of this:

- **pcap, one file per hour.** Both recorders above write it, every capture tool reads it, and rotated files are easy to manage. The replay script below reads classic pcap only, not pcapng.
- **Compress closed files only.** Never the file being written. Measure your own ratio on an hour of real data before planning disk.
- **Size from your own numbers.** The record overhead is fixed: 16 bytes of pcap header per packet, plus the link, IP and UDP headers when tcpdump wrote it (48 bytes more with `-i any` on a tcpdump that writes the 20-byte Linux cooked v2 header). The payload volume depends on the network's activity, so count bytes over a busy day rather than trusting anyone's estimate.
- **An index beside each file.** After rotation, parse the shred headers once and write the first and last slot of the file. Searching hours of capture for one slot then takes a lookup instead of a scan. The offsets are on [parsing the shred header](https://nitride.xyz/docs/shreds/parse-header).
- **Keep the raw bytes.** Store the datagrams, not your decoded output. Decoders get fixed; a capture of decoded transactions freezes yesterday's bugs into every future backtest.

## Replaying a capture into your decoder

There are two ways to use a capture, and they answer different questions.

**Feed the bytes straight into your decoder**, with no socket. Read each record, call the same function your receiver calls, and pass the recorded timestamp along as the arrival time. This is deterministic, runs as fast as your disk, and is what a strategy backtest should use. From there the pipeline is the one in [recovering and decoding](https://nitride.xyz/docs/shreds/recover-and-decode): group by FEC set, recover, deshred, and read [entries](https://nitride.xyz/learn/entries).

**Send the packets back over UDP** with their original spacing, to test the receiver itself: buffers, threading, gap handling. This script reads pcap files from either recorder above, or from tcpdump on Ethernet or `-i any`, and sends the UDP payloads to a local port:

```python file="replay.py"
# replay.py: send the UDP payloads in a pcap file to a local port, keeping their spacing.
# usage: python3 replay.py capture.pcap 9100 [speed] [udp_port]   speed 0 sends as fast as possible
import socket
import struct
import sys
import time

def payloads(path, want_port=None):
    with open(path, "rb") as f:
        head = f.read(24)
        magic = struct.unpack("<I", head[:4])[0]
        if magic in (0xA1B2C3D4, 0xA1B23C4D):
            e = "<"
        elif magic in (0xD4C3B2A1, 0x4D3CB2A1):
            e = ">"
        else:
            raise SystemExit("not a classic pcap file (pcapng is not read here)")
        nano = magic in (0xA1B23C4D, 0x4D3CB2A1)
        linktype = struct.unpack(e + "I", head[20:24])[0] & 0xFFFF
        while True:
            rec = f.read(16)
            if len(rec) < 16:
                return
            sec, frac, incl, _ = struct.unpack(e + "IIII", rec)
            pkt = f.read(incl)
            ts = sec * 1_000_000_000 + (frac if nano else frac * 1000)
            if linktype == 147:            # written by capture.py: payload only
                yield ts, pkt
                continue
            if linktype == 1:              # Ethernet
                ethertype, ip = struct.unpack(">H", pkt[12:14])[0], 14
            elif linktype == 113:          # Linux cooked capture (tcpdump -i any)
                ethertype, ip = struct.unpack(">H", pkt[14:16])[0], 16
            elif linktype == 276:          # Linux cooked capture v2
                ethertype, ip = struct.unpack(">H", pkt[0:2])[0], 20
            elif linktype in (101, 228):   # raw IPv4
                ethertype, ip = 0x0800, 0
            else:
                raise SystemExit(f"unsupported link type {linktype}")
            if ethertype != 0x0800 or pkt[ip + 9] != 17:   # IPv4 and UDP only
                continue
            if struct.unpack(">H", pkt[ip + 6:ip + 8])[0] & 0x3FFF:
                continue                   # an IP fragment; shreds fit in one datagram
            udp = ip + (pkt[ip] & 0x0F) * 4
            dport, ulen = struct.unpack(">HH", pkt[udp + 2:udp + 6])
            if want_port is None or dport == want_port:
                yield ts, pkt[udp + 8:udp + ulen]

path, port = sys.argv[1], int(sys.argv[2])
speed = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0
only = int(sys.argv[4]) if len(sys.argv) > 4 else None   # keep one UDP port from a tcpdump file
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
first = start = None
sent = 0
for ts, payload in payloads(path, only):
    if first is None:
        first, start = ts, time.perf_counter_ns()
    if speed > 0:
        due = start + (ts - first) / speed
        while time.perf_counter_ns() < due:
            pass                           # spin: sleep() wakes too late for sub-millisecond gaps
    out.sendto(payload, ("127.0.0.1", port))
    sent += 1
print(f"replayed {sent} datagrams", file=sys.stderr)
```

We tested the pair end to end, away from port 9000. A sender put 2,000 numbered datagrams of 1,228 bytes on port 19300, while `capture.py` and tcpdump with `-i any` recorded them. Each file was then replayed at its original speed to a consumer that hashed what it got and timed the gaps:

```text file="output"
sent 2000 580885b37c7d8f13
19301 2000 580885b37c7d8f13 span_ms=2902.9 median_gap_us=1071 max_gap_ms=20.1
19302 2000 580885b37c7d8f13 span_ms=2902.9 median_gap_us=1071 max_gap_ms=20.1
```

Both replays delivered every datagram with the sender's hash and the original spacing. One warning from the same session: at speed 0, an earlier run lost 256 of 1,685 datagrams in the consumer's socket buffer. Flat out is a load test, not a faithful replay.

## What a capture cannot tell your backtest

A capture is honest about arrival and silent about everything else. Five gaps to keep in mind:

- **Loss.** Missing shreds in the file may be loss on the path, in the recorder or in the socket. Count them per slot with [gap detection](https://nitride.xyz/docs/receiver/gap-detection) before trusting a slot, and remember that coding shreds can rebuild some of them.
- **Skipped slots.** Some slots that produced shreds never became part of the chain. Label every slot afterwards with an RPC node's `getBlocks`, and keep skipped slots out of anything you score. [Skipped slots and your bot](https://nitride.xyz/blog/skipped-slots-and-your-bot) covers what they look like live.
- **The clock.** Kernel stamps are system time, and system time gets corrected. A clock that stepped during the capture shifts every arrival after it. Log your sync state beside the capture; [your clock is lying](https://nitride.xyz/blog/clock-sync-for-latency) covers NTP and PTP.
- **Regime changes.** Mainnet moved to 200 ms slots on October 9, 2026, and Alpenglow's Votor went live on October 21, 2026, with votes leaving the blocks. Captures from before those dates describe a different chain. Tag files with the dates of network upgrades and do not mix them in one test.
- **Your own effect.** A capture shows the market as it was, without your orders. It cannot tell you who would have reacted to them, or whether your transaction would have landed in the slot you aimed at.

The capture also holds only what reached one server. If you are judging a strategy that may move, [shreds for arbitrage](https://nitride.xyz/use-cases/arbitrage) explains why the location of the box changes the answer.

Each plan has a free 2-hour trial, once per person. Email support@nitride.xyz with the IPv4 address and UDP port you want to test. We verify you receive on that address, then your 2 hours start.
