Introduction
Welcome to the Xylem documentation!
Xylem is a high-performance and modular traffic generator and measurement tool designed for RPC workloads. It provides a flexible framework for benchmarking and load testing distributed systems with different combinations of application protocols (e.g., Redis, HTTP, Memcached) and transport protocols (e.g., TCP, UDP, Unix Domain Socket).
Key Features
- Multi-Protocol Support: Built-in support for Redis, HTTP, Memcached, Masstree, and xylem-echo protocols
- Flexible Transport Layer: Support for TCP, UDP, and Unix Domain Sockets
- High Performance: Efficient event-driven architecture for generating high loads
- Reproducible: Configuration-first design using TOML profiles ensures reproducibility
- Detailed Metrics: Latency measurements and statistics using various sketch algorithms
- Multi-Threaded: Support for thread affinity and multi-threaded workload generation
Use Cases
Xylem is ideal for:
- Performance Benchmarking: Measure the performance of your RPC services under various load conditions
- Load Testing: Generate realistic traffic patterns to test system behavior under stress
- Latency Analysis: Collect detailed latency statistics to identify performance bottlenecks
- Protocol Testing: Validate protocol implementations across different transport layers
- Capacity Planning: Determine the maximum throughput and optimal configuration for your services
Project Status
Xylem is actively developed and maintained. The project is licensed under MIT OR Apache-2.0.
Getting Help
- GitHub Issues: Report bugs or request features at github.com/minhuw/xylem/issues
- Source Code: View the source code at github.com/minhuw/xylem
Next Steps
- Follow the Quick Start guide
- Learn about CLI Reference
- Explore the Architecture to understand Xylem’s design
Quick Start
This guide will help you run your first benchmark with Xylem.
Prerequisites
- Rust 1.99 or later
- A target service to benchmark (e.g., Redis, HTTP server, Memcached)
Build Xylem
# Clone the repository
git clone https://github.com/minhuw/xylem.git
cd xylem
# Build in release mode
cargo build --release
# The binary will be at target/release/xylem
Running a Redis Benchmark
1. Start a Redis Server
First, ensure you have a Redis server running. You can use Docker for easy setup:
docker run -d -p 6379:6379 redis:latest
Or use Docker Compose with the provided test configuration:
docker compose -f tests/redis/docker-compose.yml up -d
By default, Redis listens on localhost:6379.
2. Run the Benchmark
Use one of the included example profiles:
./target/release/xylem -P tests/redis/redis-get-zipfian.toml
This profile runs a Redis GET benchmark with a Zipfian key distribution.
3. Understanding the Output
Xylem will display statistics about the benchmark, including:
- Latency percentiles (p50, p95, p99, p99.9, etc.)
- Throughput (requests per second)
- Error rates
- Per-thread statistics
Configuration-First Design
Xylem uses TOML configuration files (called “profiles”) to define experiments. This ensures reproducibility and simplifies complex workload specifications.
Basic Syntax
xylem -P <profile.toml>
Example Profiles
Xylem includes example profiles in the profiles/ directory:
# Run a Redis GET benchmark with Zipfian distribution
xylem -P tests/redis/redis-get-zipfian.toml
# Run an HTTP load test
xylem -P profiles/http-spike.toml
# Run a Memcached benchmark
xylem -P profiles/memcached-ramp.toml
Customizing the Benchmark
You can override configuration values using the --set flag with dot notation:
# Change target address for the first traffic group
./target/release/xylem -P tests/redis/redis-get-zipfian.toml \
--set traffic_groups.0.target=192.168.1.100:6379
# Change experiment duration
./target/release/xylem -P tests/redis/redis-get-zipfian.toml \
--set experiment.duration=120s
Creating a Custom Profile
Create your own TOML profile file:
# my-benchmark.toml
[experiment]
name = "redis-benchmark"
duration = "30s"
seed = 123
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
max_pending_per_connection = 1
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 10000
theta = 0.99
value_size = 100
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.sampling_policy]
type = "unlimited"
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "human"
file = "results.json"
Run with:
./target/release/xylem -P my-benchmark.toml
Profile File Structure
A typical profile file includes:
# Experiment configuration
[experiment]
name = "redis-benchmark"
duration = "60s"
seed = 123
# Traffic groups (each with its own protocol, target, and rate control)
[[traffic_groups]]
transport = "tcp"
name = "group-1"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
max_pending_per_connection = 1
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results.json"
Logging
Control logging verbosity:
# Debug level logging
xylem -P tests/redis/redis-get-zipfian.toml --log-level debug
# Using RUST_LOG environment variable
RUST_LOG=debug xylem -P tests/redis/redis-get-zipfian.toml
Next Steps
- Explore CLI Reference for all available options
- Learn about Configuration file format
- Check out example profiles in the
profiles/directory
CLI Reference
Complete reference for Xylem command-line interface.
Xylem uses a config-first design with TOML profile files. This ensures reproducibility and simplifies complex workload specifications.
Basic Usage
xylem -P tests/redis/redis-get-zipfian.toml
Global Options
--version
Display version information.
xylem --version
--help
Display help information.
xylem --help
-P, --profile <FILE>
Path to TOML profile configuration file.
xylem -P tests/redis/redis-bench.toml
--set <KEY=VALUE>
Override any configuration value using dot notation. Can be specified multiple times. The path must name a key of the profile format, and an index an existing array entry; otherwise Xylem stops with an error that quotes the override and suggests the closest valid key.
xylem -P tests/redis/redis-get-zipfian.toml --set traffic_groups.0.target=192.168.1.100:6379
xylem -P profiles/http-spike.toml --set experiment.duration=60s --set experiment.seed=12345
Examples:
--set traffic_groups.0.target=127.0.0.1:6379--set traffic_groups.0.protocol=redis--set experiment.duration=60s--set experiment.seed=999--set traffic_groups.0.protocol_config.keys.n=1000000--set traffic_groups.0.protocol_config.keys.strategy=zipfian--set traffic_groups.0.threads=[0,1,2,3]--set output.file=/tmp/results.json
-l, --log-level <LEVEL>
Set log level (trace, debug, info, warn, error).
Default: info
xylem -P tests/redis/redis-get-zipfian.toml --log-level debug
Subcommands
completions <SHELL>
Generate shell completion scripts.
Supported shells:
- bash
- zsh
- fish
- powershell
- elvish
Examples:
# Bash
xylem completions bash > ~/.local/share/bash-completion/completions/xylem
# Zsh
xylem completions zsh > ~/.zsh/completions/_xylem
# Fish
xylem completions fish > ~/.config/fish/completions/xylem.fish
schema
Generate JSON Schema for configuration files.
xylem schema > config-schema.json
Configuration Overrides
The --set flag uses dot notation to override any configuration value:
# Override target address for a traffic group
xylem -P tests/redis/redis-get-zipfian.toml --set traffic_groups.0.target=127.0.0.1:6379
# Override protocol for a traffic group
xylem -P profiles/memcached-ramp.toml --set traffic_groups.0.protocol=memcached-ascii
# Override experiment parameters
xylem -P profiles/memcached-ramp.toml --set experiment.duration=300s --set experiment.seed=42
# Override protocol_config settings (keys, operations, value sizes)
xylem -P tests/redis/redis-get-zipfian.toml --set traffic_groups.0.protocol_config.keys.n=1000000
xylem -P tests/redis/redis-get-zipfian.toml --set traffic_groups.0.protocol_config.keys.strategy=zipfian
# Override traffic group settings
xylem -P profiles/multi-protocol-example.toml --set traffic_groups.0.threads=[0,1,2,3]
Profile Files
Xylem requires a TOML profile file that defines the experiment configuration. See the profiles/ directory for example configurations.
Example profile structure:
[experiment]
name = "redis-benchmark"
duration = "60s"
seed = 123
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
max_pending_per_connection = 10
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.sampling_policy]
type = "unlimited"
[output]
format = "json"
file = "/tmp/results.json"
Exit Status
| Status | Meaning |
|---|---|
| 0 | The run passed its validity checks and thresholds, or none applied |
| 1 | Error, including an invalid profile or unwritable result files |
| 2 | Thresholds failed: a [thresholds] expression did not hold |
| 3 | Invalid run: a [validity] check failed, so the results do not describe the configured load (takes precedence over 2) |
Result files are written before the exit with 2 or 3. See Thresholds and Validity.
Environment Variables
Xylem respects the following environment variables:
RUST_LOG- Set logging level (e.g.,debug,info,warn,error)
RUST_LOG=debug xylem -P tests/redis/redis-get-zipfian.toml
See Also
- Configuration - Detailed configuration file format
- Thresholds and Validity - Verdicts and exit statuses
- Configuration Schema - Configuration schema reference
Configuration
Xylem uses TOML configuration files (called “profiles”) for defining experiments.
Configuration File Structure
A profile is a TOML document with the following top-level sections:
[experiment]
name = "redis-benchmark"
duration = "60s"
seed = 123
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
[traffic_groups.protocol_config.keys]
strategy = "sequential"
start = 0
value_size = 64
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results.json"
Sections
The configuration is divided into several sections:
- Protocol Configuration - Define key distributions and operations per traffic group
- Transport Configuration - Configure network transport options
- Protocol Selection - Protocol-specific settings
- Thresholds and Validity -
[thresholds]and[validity]: pass/fail limits on the results, checks that the run applied its load, and the exit status
Basic Example
[experiment]
name = "redis-benchmark"
duration = "60s"
seed = 42
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
max_pending_per_connection = 1
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 10000
theta = 0.99
value_size = 100
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.sampling_policy]
type = "unlimited"
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results.json"
Supported Output and Statistics Options
output.format accepts json, html, both, and human. JSON includes global
and per-group statistics; set stats.include_records = true for raw time-bucket
records. HTML currently supports only output.html.library = "chartjs" and
output.html.theme = "light". output.real_time must be false: the CLI
rejects this unsupported setting instead of silently ignoring it.
TCP and UDP targets require numeric IP addresses, such as 127.0.0.1:6379 or
[::1]:6379. Set transport in each traffic group; there is no global [target]
configuration section.
Unknown and Removed Keys
Every table in a profile rejects keys it does not know. That includes each
traffic group’s protocol_config, whose valid keys are those of the group’s
protocol: keys in an http group is an error, not ignored. A misspelled or
misplaced key stops Xylem before the run with an error that names the key,
where it is, the keys valid there, and the closest one if it looks like a typo.
Xylem checks every key first and reports all unknown keys together, one per
line:
Error: Failed to parse config file: profile.toml
Caused by: The profile has 2 errors:
- unknown field `durationn` in experiment (did you mean `duration`?); expected one of `busy_poll_us`, `description`, `drain_timeout`, `duration`, `name`, `numa_membind`, `seed`, `setup_timeout`, `tx_timestamp_timeout`
- unknown field `valu_size` in traffic_groups[0].protocol_config.keys (did you mean `value_size`?); expected one of `n`, `prefix`, `strategy`, `theta`, `value_size`
The one table whose keys are not fixed is [thresholds]: its keys are
metric names, so this check accepts any key there, and the
thresholds check rejects an unknown metric with
the value errors. [validity], a group’s timestamps = { hardware = ... }
table and every other table take only their own keys.
Then it checks the values, and again reports every problem at once, invalid
thresholds and validity limits included. Keys and
values that older versions accepted say what replaced them: the top-level
[target] and [workload] sections, stats.streaming, a traffic group’s
sampling_rate, the adaptive sampling policy, the redis-cluster protocol,
and Redis protocol_config.data_import.
Configuration Overrides
You can override any configuration value using the --set flag with dot notation:
# Override target address for a traffic group
xylem -P profile.toml --set traffic_groups.0.target=192.168.1.100:6379
# Override experiment duration
xylem -P profile.toml --set experiment.duration=120s
Each override’s path must exist in the profile format: a key that does not
belong where the path puts it, or an index past the end of an array, fails
with an error that quotes the override and suggests the closest key. A key
the profile leaves unset, such as request_dump.directory, can still be set.
Under protocol_config the valid keys are those of the group’s protocol, so
switching a group to another protocol may need a new protocol_config too,
for example --set traffic_groups.0.protocol=http --set traffic_groups.0.protocol_config={}.
Loading Configuration
Use the -P or --profile flag to load a profile file:
xylem -P tests/redis/redis-get-zipfian.toml
See Also
- Protocol Configuration
- Transport Configuration
- Protocol Selection
- Thresholds and Validity
- Configuration Schema
Protocol Configuration
Protocol configuration in Xylem is defined per-traffic-group using the protocol_config section. This is where you specify how each traffic group generates load: which keys to access, what operations to perform, and how data sizes vary.
Configuration Structure
All protocol-specific configuration lives under [[traffic_groups]] in the protocol_config section. Its keys depend on the group’s protocol, and a key the protocol does not take is an error rather than ignored:
[[traffic_groups]]
name = "main"
threads = [0, 1, 2, 3]
connections_per_thread = 25
max_pending_per_connection = 10
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 128
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.8
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.2
[traffic_groups.traffic_policy]
type = "fixed-rate"
rate = 100.0
Key Distribution Strategies
The keys section determines which keys your benchmark accesses.
Sequential Keys
Access keys in order - useful for baselines:
[traffic_groups.protocol_config.keys]
strategy = "sequential"
start = 0
value_size = 128
Random Keys
Uniform random access - worst case for caching:
[traffic_groups.protocol_config.keys]
strategy = "random"
max = 1000000
value_size = 128
Round-Robin Keys
Cycle through keys predictably:
[traffic_groups.protocol_config.keys]
strategy = "round-robin"
max = 100000
value_size = 128
Zipfian Distribution
Model real-world hot key patterns where some keys receive far more traffic:
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99 # Higher = more skewed
value_size = 128
At theta=0.99, the top 1% of keys might receive 80% of requests.
Gaussian Distribution
Model temporal locality where recent data is hot:
[traffic_groups.protocol_config.keys]
strategy = "gaussian"
mean_pct = 0.5 # Center of hot zone (50% of keyspace)
std_dev_pct = 0.1 # How concentrated (10% of keyspace)
max = 10000
value_size = 128
Operations Configuration
Control what operations your benchmark performs.
Fixed Operation
Single operation type:
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
Weighted Operations
Mix operations with specified probabilities:
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.7 # 70% reads
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.3 # 30% writes
Common patterns:
- Cache workload: GET 0.95, SET 0.05
- Session store: GET 0.7, SET 0.3
- Counter system: GET 0.5, INCR 0.5
Value Size Configuration
Configure value sizes in the protocol_config:
[traffic_groups.protocol_config.value_size]
strategy = "fixed"
size = 128
Or use variable sizes:
[traffic_groups.protocol_config.value_size]
strategy = "uniform"
min = 64
max = 4096
[traffic_groups.protocol_config.value_size]
strategy = "normal"
mean = 512.0
std_dev = 128.0
min = 64
max = 4096
Or draw sizes from a weighted list, such as a measured size histogram; weights are relative and need not sum to 1:
[traffic_groups.protocol_config.value_size]
strategy = "weighted"
sizes = [
{ size = 32, weight = 0.6 },
{ size = 512, weight = 0.3 },
{ size = 8192, weight = 0.1 },
]
strategy = "per_command" gives commands their own size (distribution is
fixed, uniform, normal or weighted) and the others default. The sizes
apply to the values a request sends: Redis SET (and the other writing
commands), Memcached SET, ADD and REPLACE, and Masstree SET and each PUT
column. Without a value_size section, every value has keys.value_size
bytes.
Redis Connection Setup
Redis groups can authenticate, select a database and switch to RESP3 on every connection before the workload starts:
[traffic_groups.protocol_config]
auth = { password = "secret" } # or { username = "bench", password_env = "REDIS_PASSWORD" }
db = 3
resp = 3
These commands are connection setup, not part of the operation mix. See Redis connection setup.
Complete Example
Here’s a complete traffic group configuration for a session store workload:
[[traffic_groups]]
name = "session-store"
threads = [0, 1, 2, 3]
connections_per_thread = 25
max_pending_per_connection = 10
# Temporal locality - recent sessions are hot
[traffic_groups.protocol_config.keys]
strategy = "gaussian"
mean_pct = 0.6
std_dev_pct = 0.15
max = 10000
value_size = 512
# Read-heavy with significant writes
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.7
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.3
[traffic_groups.traffic_policy]
type = "fixed-rate"
rate = 100.0 # Requests per second of the whole group
[traffic_groups.sampling_policy]
type = "unlimited"
Multiple Traffic Groups
You can define multiple traffic groups with different configurations:
# Latency measurement agent - low rate, 100% sampling
[[traffic_groups]]
name = "latency-agent"
threads = [0, 1]
connections_per_thread = 10
max_pending_per_connection = 1
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "poisson"
rate = 100.0
[traffic_groups.sampling_policy]
type = "unlimited"
# Throughput agent - high rate, sampled
[[traffic_groups]]
name = "throughput-agent"
threads = [2, 3, 4, 5, 6, 7]
connections_per_thread = 25
max_pending_per_connection = 32
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.sampling_policy]
type = "limited"
rate = 0.01
See Also
- Redis Protocol - Redis-specific operations
- Traffic Groups - Traffic group configuration
- Configuration Schema - Complete reference
Transport Configuration
Each [[traffic_groups]] section specifies its own transport and target. Transport defaults to "tcp". Groups sharing a thread must use the same transport.
Available Transports
tcp- TCP/IP connectionsudp- UDP connectionsunix- Unix domain socketsntcp- User-space TCP over a TUN device; needs thentcpbuild feature and an[ntcp]section (see ntcp)
Configuration
TCP (IP:port)
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
# ...
Unix Domain Socket (filesystem path)
[[traffic_groups]]
transport = "unix"
name = "main"
protocol = "redis"
target = "/var/run/redis/redis.sock"
# ...
UDP (IP:port)
UDP works with the protocols that frame requests as datagrams and match replies by request ID:
| Protocol | Over UDP |
|---|---|
memcached-ascii | memcached’s UDP frame header; multi-datagram responses are reassembled |
memcached-binary | the same frame header; verified against memcached 1.6.45 |
dns | one bare DNS message per datagram (no 2-byte length); truncated responses count as error kind TC |
xylem-echo | one 16-byte request per datagram, for xylem-echo-server’s UDP listener |
redis, http, http2, grpc, masstree, nvme-tcp and clickhouse with
transport = "udp" fail validation.
[[traffic_groups]]
transport = "udp"
name = "main"
protocol = "memcached-ascii"
target = "127.0.0.1:11211"
request_timeout = "500ms" # optional; default 1s for UDP
# ...
memcached 1.5.6 and later disable UDP; start it with -U <port>.
Datagrams
xylem parses each received datagram on its own; bytes of one datagram are never joined with the next. A protocol may absorb a datagram that completes no request yet, such as one fragment of a multi-datagram response, a duplicate, or a reply for an unknown request ID.
memcached frame header
Every memcached datagram starts with the 8-byte header of memcached’s
protocol.txt (“UDP protocol”), big-endian u16 fields:
[request id][sequence number][total datagrams][reserved = 0]
A request is one datagram whose request id is the low 16 bits of the
connection’s request counter, so a request with its value must fit one
datagram: values above 64,987 bytes fail validation. memcached splits a
response into datagrams of at most 1400 bytes, numbered 0..total. xylem
reassembles them per connection by request id and sequence number in any
arrival order, and drops duplicates and datagrams for unknown request ids. A
response that lost a datagram never completes; its request times out.
Request timeout
UDP does not retransmit, so a lost request or response would leave its request
pending, and a closed-loop connection with pipeline depth D would stall after
D losses. Each UDP group therefore has a request_timeout (humantime,
default 1s), counted from the send. A request still pending when it expires:
- frees its pipeline slot, so the connection sends again;
- counts in
requests.timed_out; - records no latency: the latency is censored, not set to the timeout.
A response that arrives later is dropped by request ID and counted in
requests.late_responses. Open-loop schedules keep their intended send times;
a timeout only frees the slot that a full pipeline was waiting on, and the
delay still shows as send lag and unsent. Timeouts also run during the
drain, and warmup requests time out without being counted. Stream transports
(tcp, unix, ntcp) retransmit, never time out requests, and reject
request_timeout.
Timestamps
timestamps chooses where a traffic group’s send and receive timestamps come
from. It applies to tcp and udp groups on Linux, and "nic" to ntcp
groups with the DPDK backend:
[[traffic_groups]]
transport = "udp"
timestamps = "kernel" # "user" (default), "kernel", or { hardware = "data0" }
# ...
"user"(default): only the CPU timestamp counter (RDTSC), read in user space when each send and receive call completes. NoSO_TIMESTAMPINGand no error-queue reads."kernel": also kernel software timestamps (SO_TIMESTAMPING, on the system clock): a TX timestamp when the request leaves the kernel’s stack for the driver, read back from the socket’s error queue, and an RX timestamp when the response enters the stack. Any interface has them, loopback too.{ hardware = "<interface>" }: NIC hardware timestamps, on the NIC’s PTP clock, and every socket is bound to the interface. The interface must already have hardware timestamping switched on, for example by a PTP daemon or with linuxptp’shwstamp_ctl -i data0 -t 1 -r 1as root. When the run starts, before any worker, xylem reads the interface’s setting withSIOCGHWTSTAMPand fails with an error if it is off or unsupported. It never switches NIC timestamping on, and never falls back to another source."nic": forntcpgroups withntcp.backend = "dpdk"only, which own the NIC: the NIC’s hardware RX timestamps converted to xylem’s clock, and the time ntcp queued each request to the NIC as its TX timestamp. See ntcp NIC timestamps.
Every timestamp keeps its user-space cycles. A request’s latency uses the
kernel timestamps when its send and its response both have one from the same
clock, and the cycles otherwise; either way the
latency breakdown reports the
service latency, and with kernel timestamps it splits the round trip into the
part between the user-space and the kernel timestamps (host_stack_us) and
the kernel round trip (network_server_us), and reports the whole user-space
round trip of those requests (user_round_trip_us). A
request whose TX or RX timestamp did not arrive is measured in cycles and
counted in service_us alone; kernel_split_count says how many were split,
and kernel_split_missing why the others were not (no TX timestamp, no RX
timestamp, or timestamps of different clocks).
A response can arrive before its request’s TX timestamp was read from the
error queue: a NIC reports a hardware TX timestamp only once the transmit
completed, which can be later than a fast round trip. Such a response
completes its request at once, so the connection sends its next request on
schedule and an adaptive traffic policy gets the latency measured so far, in
cycles; only the latency sample waits for the TX timestamp, for at most
experiment.tx_timestamp_timeout (default 10 ms; see the
experiment fields). With the stamp in
time, the sample is split like any other; without, or still waiting at the
end of the drain, it is measured in cycles and counts in
kernel_split_missing.tx. Either way it counts in the time bucket of its
response’s receive, and in the measurement window if the response arrived in
it, however late it is recorded. Sampling only the requests whose stamp came
first would favour slow requests, more so the faster the server.
With "kernel" or { hardware = ... }, xylem never falls back to
user-space timestamps without saying so:
-
Each socket must accept
SO_TIMESTAMPING(and, for hardware timestamps,SO_BINDTODEVICE). If one refuses, the run fails while it opens its connections, with an error naming the traffic group, the connection, the socket option and the errno, as inTraffic group 0: cannot open a connection to 10.0.0.2:2117: Could not enable kernel software timestamps on TCP connection 3: setsockopt(SOL_SOCKET, SO_TIMESTAMPING, 0x89a) failed: .... -
Reading a socket’s error queue (
recvmsgwithMSG_ERRQUEUE) for TX timestamps fails the run on any error but an empty queue, and on a message that carries no TX timestamp. -
A group that completed requests but split none of them makes the run invalid (exit status 3, results written; see the
kernel_splitvalidity check), with the counts ofkernel_split_missingand the likely fix: without TX timestamps, the interface’s driver lacks software-transmit timestamping (checkethtool -T <interface>on the interface that reaches the target); without RX timestamps, check software-receive, or for hardware timestamps the NIC’shwstamp_ctlRX filter. A group that split only some logs a warning with the counts. -
unixgroups reject anything but"user", andntcpgroups anything but"user"and (with the DPDK backend)"nic": neither has kernel packet timestamps. -
Traffic groups that share a thread share its connection group, whose sockets are configured alike, so they must use the same
timestamps. -
Kernel timestamps cost an error-queue read per poll for each connection with sends not yet stamped, and a
recvmsgwith ancillary data per read. Compare runs with the same source.
See the Architecture - Transport Layer for implementation details.
Protocol Configuration
Configure the protocol and target address for each traffic group in your TOML profile.
Specifying Protocol
Each traffic group must specify its own protocol and target:
[[traffic_groups]]
name = "main"
protocol = "redis" # or "http", "http2", "grpc", "memcached-binary", "memcached-ascii", "masstree", "dns", "nvme-tcp", "clickhouse", "xylem-echo"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 10
max_pending_per_connection = 1
Multi-Protocol Experiments
You can run different protocols in separate traffic groups:
[[traffic_groups]]
name = "redis-load"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1]
# ...
[[traffic_groups]]
name = "memcached-load"
protocol = "memcached-binary"
target = "127.0.0.1:11211"
threads = [2, 3]
# ...
Supported Protocols
- redis - Redis Serialization Protocol (RESP)
- http - HTTP/1.1
- http2 - HTTP/2 over cleartext, prior knowledge (see HTTP/2 Protocol)
- grpc - gRPC unary calls (see gRPC Protocol)
- memcached-binary - Memcached binary protocol
- memcached-ascii - Memcached text protocol
- dns - DNS queries (see DNS Protocol)
- nvme-tcp - NVMe over Fabrics on TCP (see NVMe/TCP Protocol)
- clickhouse - ClickHouse native protocol queries (see ClickHouse Protocol)
- xylem-echo - Echo protocol (testing/development only)
See the Architecture - Protocol Layer for implementation details.
Protocols
Xylem supports multiple application protocols for different types of RPC workloads.
Supported Protocols
- Redis - Redis protocol for key-value operations
- HTTP - HTTP/1.1 protocol for web services
- HTTP/2 - Cleartext HTTP/2 with prior knowledge (h2c)
- gRPC - gRPC unary calls with raw protobuf request messages
- Memcached - Memcached protocol for caching
- DNS - DNS queries over TCP (RFC 7766 framing) or UDP
- NVMe/TCP - NVM reads and writes against an NVMe over Fabrics target
- ClickHouse - SQL queries over the ClickHouse native TCP protocol
Protocol Selection
Specify the protocol for each traffic group in your TOML profile configuration:
[[traffic_groups]]
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
# ...
Protocol Architecture
All protocols in Xylem implement a common interface that provides:
- Request Generation - Convert logical operations to wire format
- Response Parsing - Parse responses from the server
- State Management - Track request-response correlation
- Error Handling - Detect and report protocol errors
See Also
Benchmarking Redis with Xylem
When you’re benchmarking Redis, you’re speaking RESP—the Redis Serialization Protocol. It’s the language Redis uses to understand your commands and send back responses. This guide walks you through how RESP works, what commands Xylem knows how to speak, and how to craft realistic Redis workloads for your benchmarks.
Understanding RESP
RESP is elegantly simple. Commands look almost like what you’d type at a Redis CLI, but they’re formatted in a way that machines can parse efficiently. Everything is text-based—printable ASCII with CRLF line endings—which makes debugging easy. You can literally read RESP messages in a network capture.
But don’t let the text format fool you. RESP is binary-safe. When you send a value, you tell Redis exactly how many bytes to expect, so you can store JPEGs, protocol buffers, or any binary blob without escaping special characters. Redis doesn’t care what’s in your data; it just reads the exact number of bytes you promised and sends it back when you ask for it.
The communication pattern is straightforward: you send a command, Redis sends back a response. One command, one response. But here’s the clever part: you don’t have to wait for the response before sending the next command. This is called pipelining, and it’s how you get serious throughput. Send a batch of GET commands back-to-back, and Redis will send back a batch of responses in the same order. No request IDs needed—FIFO ordering per connection keeps everything straight.
Each command stands alone. Redis doesn’t maintain conversation state (except for transactions and pub/sub, which are special cases). This statelessness is what makes Redis fast and scalable.
The Wire Format
RESP speaks in five types, each starting with a special character:
Simple strings (+) are for short status messages. When you SET a key, Redis responds with +OK\r\n. That’s it—a plus sign, the message, and a newline.
Errors (-) look similar but start with a minus. -ERR unknown command\r\n tells you something went wrong. The distinction between simple strings and errors lets clients handle success and failure differently without parsing the message content.
Integers (:) are for numeric results. When you INCR a counter, Redis might send back :42\r\n—that’s the new count. The colon says “interpret what follows as a number.”
Bulk strings ($) are where it gets interesting. These can hold any binary data of any size. The format is $<length>\r\n<data>\r\n. So $5\r\nhello\r\n is a 5-byte string containing “hello”. The length-prefix is what makes RESP binary-safe—Redis knows exactly how many bytes to read, regardless of what’s in them. A null value is $-1\r\n, which is how Redis says “this key doesn’t exist.”
Arrays (*) let you send or receive multiple values. The format is *<count>\r\n followed by that many elements. Each element can be any RESP type—strings, integers, even nested arrays. This is how commands work: GET key:1234 becomes *2\r\n$3\r\nGET\r\n$8\r\nkey:1234\r\n—an array of two bulk strings.
RESP3 adds more types: true nulls (_\r\n), booleans (#t\r\n or #f\r\n), doubles for floating-point numbers (,3.14\r\n), maps (%<count>\r\n) for key-value pairs, sets (~<count>\r\n) for unique collections, and a few others. A connection speaks RESP2 until it sends HELLO 3; see Connection Setup. These semantic types make client libraries simpler because they don’t have to guess whether a bulk string is a number or text.
Commands on the Wire
Every Redis command is an array of bulk strings. Even simple ones. GET key:1234 becomes:
*2\r\n # Array with 2 elements
$3\r\nGET\r\n # First element: "GET" (3 bytes)
$8\r\nkey:1234\r\n # Second element: "key:1234" (8 bytes)
SET looks similar but with three elements:
*3\r\n # Array with 3 elements
$3\r\nSET\r\n # Command
$8\r\nkey:1234\r\n # Key
$128\r\n<128 bytes>\r\n # Value
Responses match what the command returns. A successful GET sends back the value as a bulk string. A missing key sends $-1\r\n. SET responds with +OK\r\n. INCR returns an integer like :43\r\n.
Pipelining: The Secret to Throughput
Here’s where Redis shines. Instead of this:
- Send GET key1
- Wait for response
- Send GET key2
- Wait for response
You do this:
- Send GET key1, GET key2, GET key3
- Read three responses
The latency savings are dramatic. If each round-trip takes 1ms, the first approach takes 2ms for two GETs. Pipelining takes just over 1ms total. With 10 keys, you go from 10ms to ~1ms. The more you pipeline, the closer you get to wire speed.
Redis guarantees responses come back in the same order you sent requests, per connection. You don’t need to tag requests with IDs—just keep track of how many you’ve sent and match them up with responses as they arrive. This is what Xylem does automatically with the max_pending_per_connection setting.
The Commands
A profile can select these commands by name: get, set, incr, mget, setex, setrange, getrange, scan, wait, multi, exec, discard, and custom for a command template. Names are case-insensitive. Every other Redis command goes through a template; see Custom Commands via Templates.
Let’s talk about what these commands actually do and when you’d use them in benchmarks.
GET retrieves a value. It’s your bread-and-butter read operation. Benchmark GET to measure read latency, cache hit rates, and how Redis handles concurrent readers. When the key doesn’t exist, you get back a null ($-1\r\n).
SET stores a value. This is your write operation. Redis overwrites any existing value, so SET is idempotent—run it twice and you get the same result. Benchmark SET to test write throughput, persistence overhead (if you have AOF or RDB enabled), and replication lag.
SETEX combines SET with an expiration time. SETEX session:abc123 1800 <data> stores the session and tells Redis to delete it in 30 minutes. This is atomic—no race between SET and EXPIRE. Use it to benchmark TTL accuracy, eviction behavior, and how expiring keys affect memory management.
INCR atomically increments a counter. If the key doesn’t exist, Redis treats it as zero and increments to one. This is crucial for testing atomic operations, counters (like rate limiters or page view trackers), and how Redis handles numeric operations under concurrency.
MGET fetches multiple keys in one command: MGET key:1 key:2 key:3. The response is an array of values (or nulls for missing keys). Use this to benchmark batch operations and see if your network round-trip time dominates your latency.
WAIT blocks until previous writes replicate to N replicas or a timeout expires: WAIT 2 1000 waits for 2 replicas with a 1-second timeout. The response is how many replicas acknowledged. This lets you benchmark replication lag and consistency guarantees.
SETRANGE and GETRANGE work on offsets within a value. SETRANGE key:1000 5 hello overwrites 5 bytes starting at offset 5. GETRANGE key:1000 5 -1 reads from offset 5 to the end. These are useful for large-value workloads where you only modify or read part of the data—think partial updates to binary structures or reading substrings from log entries.
SCAN iterates over the keyspace: SCAN 0 COUNT 100 MATCH key:*. Set cursor, count and pattern with params = { cursor = 0, count = 100, pattern = "key:*" }; each request sends the same cursor. Use it to measure the cost of keyspace iteration alongside regular traffic.
MULTI, EXEC and DISCARD start, commit and abort a transaction. Each is sent as a separate weighted command, so commands picked between them are queued and answered with +QUEUED.
Custom Commands via Templates
Command templates send any Redis command the profile can’t select by name: DEL, MSET, hashes, lists, sets, sorted sets, CLUSTER SLOTS, GEOADD, and so on. A template is a custom command with params.template:
[[traffic_groups.protocol_config.operations.commands]]
name = "custom"
weight = 0.1
params = { template = "ZADD leaderboard __value_size__ __key__" }
The template is split on whitespace into the arguments of a RESP array. Xylem replaces __key__ with the current key (including the key prefix, so key:42), __data__ with a generated value, and __value_size__ with the value size as a number. A variable is always a whole argument: player:__key__ sends two arguments, player: and key:42. So a key can’t carry a type prefix such as list:. Use a fixed collection name and put __key__ in a member or field position, or give the data structure commands their own keyspace by putting them in a separate traffic group with a different keys.prefix.
Templates for common commands:
| Data type | Templates |
|---|---|
| Keys | DEL __key__, MSET __key__ __data__ other __data__, EXPIRE __key__ 60 |
| Hash | HSET __key__ field __data__ (one hash per key), HSET users __key__ __data__ (one shared hash), HGET __key__ field, HGETALL __key__, HDEL __key__ field |
| List | LPUSH queue __data__, RPUSH queue __data__, LPOP queue, LRANGE queue 0 9, LLEN queue |
| Set | SADD tags __key__, SREM tags __key__, SISMEMBER tags __key__, SMEMBERS tags, SCARD tags |
| Sorted set | ZADD leaderboard __value_size__ __key__, ZSCORE leaderboard __key__, ZRANGE leaderboard 0 9 WITHSCORES, ZREM leaderboard __key__, ZCARD leaderboard |
| Cluster | CLUSTER SLOTS |
Replies are framed generically, so integers, bulk strings, nils, arrays, nested arrays and RESP3 types all count as one completed request. An error reply, such as WRONGTYPE when a template uses a key that already holds another type, completes its request as an error reply (see below). Watch for this when templates and get/set draw from the same keyspace.
Error Replies
A top-level error reply, a simple error (-) or a RESP3 blob error (!), completes its request and counts in requests.errors, by its error code: the first word of its text, such as ERR, WRONGTYPE, OOM, NOAUTH, MOVED or EXECABORT. Its latency goes to error_latency, not the latency distribution; see Output Formats. A nil ($-1, *-1, _) is a successful reply. Only the top-level reply counts: an EXEC array holding the error of one of its commands is a successful reply. Set on_error = "abort" on the traffic group to stop the run at the first error reply instead.
Malformed RESP still stops the run, and so does an error reply to connection setup (below).
Connection Setup: AUTH, SELECT and HELLO
AUTH, SELECT and HELLO configure a connection rather than exercise the server, so Xylem never puts them in the command mix. You set them in the traffic group’s protocol_config, and every connection sends them once, right after it connects and before any insert-phase or measured request:
[traffic_groups.protocol_config]
auth = { password = "secret" } # AUTH secret (requirepass)
db = 3 # SELECT 3
resp = 3 # HELLO 3
auth authenticates the connection. With only a password, Xylem sends AUTH <password>, which checks the server’s requirepass. Add a username for a Redis 6+ ACL user, and Xylem sends AUTH <username> <password>. To keep the password out of the profile, name an environment variable instead with password_env; Xylem reads it when the run starts and stops with an error naming the variable if it is not set. Set exactly one of password and password_env:
[traffic_groups.protocol_config]
auth = { username = "bench", password_env = "REDIS_PASSWORD" } # or password = "secret"
db selects a logical database with SELECT <db>. Without it, connections stay in the server’s default database 0. The server decides how many databases exist (16 by default).
resp picks the protocol version: 2 (the default, so no HELLO) or 3, which sends HELLO 3. Xylem frames every RESP3 reply type, including maps, sets, doubles, booleans, big numbers, verbatim strings and attributes. Out-of-band push messages, such as client-tracking invalidations, answer no request: Xylem skips them instead of matching them to a pending request.
The setup commands go out one at a time, in the order AUTH, SELECT, HELLO, each waiting for its reply. Separate commands, rather than a combined HELLO 3 AUTH user pass, keep AUTH and SELECT working on servers without HELLO, and tell you which step failed. Setup requests are warmup: they count toward no latency, throughput, byte or request count, never appear in the request dump, and do not use up a rate-limited connection’s schedule. They go out as soon as the connection can send, without waiting for its intended send times, and the schedule starts at its first intended time after setup completes. An error reply to any of them, such as WRONGPASS, NOAUTH, NOPERM, an out-of-range database or an unknown HELLO, stops the run with an error naming the command and connection. Xylem never writes the password to its output, logs or errors.
A complete profile for a password-protected server:
[experiment]
name = "redis-auth"
duration = "30s"
[[traffic_groups]]
name = "bench"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0]
connections_per_thread = 8
max_pending_per_connection = 4
[traffic_groups.protocol_config]
auth = { username = "bench", password = "secret" } # or password_env = "REDIS_PASSWORD"
db = 3
[traffic_groups.protocol_config.keys]
strategy = "random"
max = 100000
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/redis-auth.json"
Building Realistic Workloads
Real applications don’t just GET and SET uniformly distributed keys. They have patterns: hot keys, read-heavy ratios, varied value sizes, bursts of traffic. Xylem lets you model all of this.
Command Mixes
All workload configuration goes inside each traffic group’s protocol_config section. Start simple. A pure GET workload tests read performance:
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
But production is rarely pure reads. Model a cache with 70% reads and 30% writes:
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.7
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.3
Xylem picks commands randomly based on their weights. Over time, you’ll see 70% GETs and 30% SETs.
Add INCR for counters, MGET for batch reads, and WAIT to test replication:
[[traffic_groups.protocol_config.operations.commands]]
name = "incr"
weight = 0.1
[[traffic_groups.protocol_config.operations.commands]]
name = "mget"
weight = 0.05
params = { count = 10 } # Fetch 10 keys per MGET
[[traffic_groups.protocol_config.operations.commands]]
name = "wait"
weight = 0.02
params = { num_replicas = 2, timeout_ms = 1000 }
Now you’re testing a realistic mix: mostly GETs, some SETs, occasional counter increments, batch reads, and periodic replication checks.
Key Distributions
Uniform random keys are easy to understand but unrealistic. Real workloads have hot keys—some data gets accessed way more than others.
Zipfian distribution models this. With a Zipfian exponent of 0.99, a tiny fraction of keys get most of the traffic:
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
This is perfect for CDN caching (some content is always popular), user sessions (active users generate more requests), or product catalogs (bestsellers dominate).
Gaussian (normal) distribution clusters keys around a mean. This models temporal locality—recent data is hot, older data cools off:
[traffic_groups.protocol_config.keys]
strategy = "gaussian"
mean_pct = 0.5 # Center at 50% of key space
std_dev_pct = 0.1 # 10% spread
max = 10000
value_size = 64
Use this for time-series data, sliding windows, or any scenario where “recent” matters.
Sequential access walks through keys in order. Good for range scans or import/export workloads:
[traffic_groups.protocol_config.keys]
strategy = "sequential"
start = 0
value_size = 64
Random is truly uniform. Every key has equal probability. This is your baseline for understanding Redis’s raw performance without hot keys skewing results:
[traffic_groups.protocol_config.keys]
strategy = "random"
max = 100000
value_size = 64
Value Sizes
The value_size in keys configuration sets a fixed size. For variable sizes, add a separate value_size section:
[traffic_groups.protocol_config.value_size]
strategy = "fixed"
size = 128 # All values are 128 bytes
But production has variation. Some cache entries are tiny (user preferences), others are huge (HTML fragments). Model this with distributions:
[traffic_groups.protocol_config.value_size]
strategy = "normal"
mean = 512.0
std_dev = 128.0
min = 64
max = 4096
Or use uniform distribution for evenly spread sizes:
[traffic_groups.protocol_config.value_size]
strategy = "uniform"
min = 256
max = 2048
This models scenarios like caching API responses (small reads) and storing rendered pages (large writes).
Common Workload Patterns
Let me paint some pictures of real-world workloads and how to model them.
CDN Edge Cache: 95% GETs, 5% SETs. Zipfian key distribution (popular content dominates). Small reads (64B for metadata), medium writes (512B average, normal distribution for HTML snippets and JSON). High throughput, moderate pipelining. Watch for cache hit rates and P99 latency on those few misses that go to origin.
Session Store: 70% GETs, 30% SETs. Gaussian distribution (recent sessions are hot). Small uniform values (256-512B for session tokens and user state). Low latency is critical—sessions are in the critical path. Use SETEX with realistic TTLs (30-60 minutes) and measure how eviction affects memory and performance.
Rate Limiter: 50% GET (check current count), 50% INCR (increment count). Random or round-robin keys (different users/IPs). Tiny values (just counters). Extremely high throughput, short TTLs (60 seconds for sliding windows). Focus on atomic operation latency and throughput under contention.
Write-Heavy Logging: 80% SET, 20% GET. Sequential keys (time-ordered logs). Uniform value sizes (log entry length is predictable). High write throughput with pipelining. Test persistence overhead (AOF fsync), replication lag, and memory growth.
E-Commerce Product Catalog: 90% GET (browsing), 10% SET (inventory updates). Zipfian (bestsellers are hot). Medium values (1-4KB for product details with images). Add MGET for “customers who bought this also bought” features. Benchmark cache stampede behavior when popular items update.
Wrapping Up
Redis benchmarking is about understanding your workload and translating it into RESP commands. Xylem gives you the tools: command mixes, key distributions, value sizes, and pipelining control. The trick is using them to model what your production system actually does.
Start simple. Benchmark pure GETs and SETs with uniform keys to understand Redis’s baseline. Then add complexity: hot keys with Zipfian distribution, mixed command ratios, varied value sizes. Pipeline aggressively to see maximum throughput. Test failure modes: what happens during resharding, replication lag, eviction under memory pressure?
Your benchmarks should tell a story. Not just “Redis can do 100K QPS,” but “our session store can handle 10K users with P99 latency under 2ms, and we can lose a replica without dropping requests.” That’s the insight that lets you ship with confidence.
See Also
- Workload Configuration - Detailed configuration guide
- Configuration Schema - Complete reference
- Redis Documentation - Official Redis protocol documentation
HTTP Protocol
Xylem speaks HTTP/1.1 over persistent (keep-alive) connections for
benchmarking web servers and APIs. Every request on a connection reuses it,
and with max_pending_per_connection above 1 requests are pipelined:
responses come back in request order, so no request IDs are needed.
Configuration
[experiment]
name = "http-get"
duration = "30s"
[[traffic_groups]]
name = "web"
protocol = "http"
target = "127.0.0.1:8080"
threads = [0, 1]
connections_per_thread = 4
max_pending_per_connection = 1
[traffic_groups.protocol_config]
method = "GET" # GET, POST or PUT
path = "/" # request target, sent as-is
host = "example.com" # Host header; defaults to "localhost"
body_size = 64 # POST/PUT body size in bytes
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/http-get.json"
Every request is the same: the request line, Host, Connection: keep-alive, and for POST and PUT a Content-Length and a body of
body_size x bytes.
Response Framing
Xylem reads responses on a keep-alive connection, so it has to find where each one ends. It supports these framings (RFC 9112 section 6.3):
Content-Length: the body is exactly that many bytes. RepeatedContent-Lengthheaders must agree.Transfer-Encoding: chunked: the body is a series of chunks (RFC 9112 section 7.1). Chunk sizes are hexadecimal, in upper or lower case. Chunk extensions are ignored, and trailer fields after the last-chunk (0) are skipped. Every chunk line must end in CRLF.- No body: 204 and 304 responses end at the blank line after their headers, whatever their framing headers say.
A response counts as complete only once all of it has arrived, however the bytes are split across reads. Informational (1xx) responses before the final response are consumed with it. The bytes counted as received are the whole response on the wire: interim responses, headers, chunk framing and trailers.
A response with status 400 or above is an error reply: it completes its
request and counts in requests.errors, by its status code ("404",
"503"), and its latency goes to error_latency, not the latency
distribution; see Output Formats. 1xx,
2xx and 3xx responses are successful. Set on_error = "abort" on the traffic
group to stop the run at the first error reply instead.
The following end the run with an error, since xylem cannot frame them on a keep-alive connection:
- a body delimited by closing the connection (neither
Content-LengthnorTransfer-Encoding); - any
Transfer-Encodingother than a singlechunked, such asgzip,gzip, chunkedorchunked, chunked, since xylem does not decode content; - both
Transfer-EncodingandContent-Length: RFC 9112 letsTransfer-Encodingwin but says such a message ought to be handled as an error, since it may be an attempt at response smuggling; - malformed chunked framing: a bad chunk size, a missing CRLF or a malformed trailer field;
- an invalid or conflicting
Content-Length; 101 Switching Protocols;- a response with
Transfer-Encoding: chunked(or headers alone) larger than 64 KiB, the per-read buffer limit.Content-Lengthresponses larger than 64 KiB stream incrementally viaParsed::Absorbedin up to 64 KiB chunks.
Per-Request Key Paths
Add an optional keys section to vary the request target per request instead
of sending a fixed path:
[traffic_groups.protocol_config]
method = "GET"
path = "/obj/"
keys = { strategy = "round-robin", max = 1000, value_size = 64, prefix = "k" }
Each request sends {path}{prefix}{key_num} (for example /obj/k0, /obj/k1,
…). When keys is omitted, xylem prebuilds the request once and sends path
unchanged.
Deterministic Response Body Verification
Set verify = true together with verify_body_size (and optional verify_seed,
default 0) on a GET traffic group to compare every byte of every response
body against a deterministic function of (verify_seed, path, verify_body_size).
Content-Length responses of any size (including 64 KiB, 96 KiB, 128 KiB, and
1 MiB+ multi-segment bodies) are verified incrementally over HTTP/1.1 keep-alive
without raising the 64 KiB receive chunk limit:
[experiment]
name = "http-get-verify"
duration = "10s"
[[traffic_groups]]
name = "web"
protocol = "http"
target = "127.0.0.1:8080"
threads = [0]
connections_per_thread = 4
max_pending_per_connection = 1
[traffic_groups.protocol_config]
method = "GET"
path = "/obj/"
keys = { strategy = "round-robin", max = 64, value_size = 64, prefix = "k" }
verify = true
verify_seed = 42
verify_body_size = 98304
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/http-get-verify.json"
Pattern Formula
A server or synthetic responder can reproduce the exact byte sequence for
(seed: u64, path: &[u8], body_size: usize) as follows, where path is the
exact request target sent on the request line (static path when keys is
omitted, or {path}{prefix}{key_num} when keys is configured):
- Hash
pathwith 64-bit FNV-1a (offset basis0xcbf29ce484222325, prime0x00000100000001b3):h = fnv1a_64(path) - Define
splitmix64(x):x = x.wrapping_add(0x9e3779b97f4a7c15)x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9)x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb)- return
x ^ (x >> 31)
- Compute the per-path base word:
base = splitmix64(seed ^ h ^ (body_size as u64).wrapping_mul(0x9e3779b97f4a7c15)) - For each 64-bit word
w = 0, 1, 2, ...covering body bytes[8*w .. 8*w + 8), emitsplitmix64(base.wrapping_add(w.wrapping_mul(0x9e3779b97f4a7c15))).to_le_bytes(), truncated tobody_sizebytes.
Verification Errors and Run Verdict
When verify = true, any failure is counted as a named error in
requests.errors / requests.errors_by_kind, recorded in
traffic_groups[].verification (verified, failures, and first_mismatch),
and fails the verification validity check (verdict = "invalid_run", exit
code 3). Set on_error = "abort" on the traffic group to exit immediately
with code 1 on the first verification error reply:
BadStatus— HTTP response status code is not200.ContentLengthMismatch—Content-Lengthdoes not equalverify_body_size, or a chunked response decoded to more thanverify_body_sizebytes.BodyMismatch— a byte in the response body differs from the expected pattern (first_mismatch.offset,expected, andactualpinpoint the first mismatched byte).ShortBody— the connection closed before allContent-Lengthbody bytes arrived, or a chunked response decoded to fewer thanverify_body_sizebytes.
HTTP/2 Protocol
protocol = "http2" speaks HTTP/2 over cleartext with prior knowledge
(h2c, RFC 9113 section 3.3): the connection starts with the HTTP/2 preface,
with no TLS and no HTTP/1.1 Upgrade. The server must accept HTTP/2 on a
plain listener, as nginx does with http2 on; and h2o does by default.
Every request is the same, with the knobs of the HTTP/1.1
protocol. gRPC runs on the same HTTP/2 layer.
Configuration
[experiment]
name = "h2c-get"
duration = "30s"
[[traffic_groups]]
name = "web"
protocol = "http2"
target = "127.0.0.1:8080"
threads = [0, 1]
connections_per_thread = 4
# Streams in flight per connection
max_pending_per_connection = 16
[traffic_groups.protocol_config]
method = "GET" # GET, POST or PUT
path = "/" # :path
authority = "example.com" # :authority; defaults to the target
body_size = 64 # POST/PUT body size in bytes
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/h2c-get.json"
authority defaults to the group’s target, or localhost over a Unix
socket. A POST or PUT carries content-type: application/octet-stream, a
content-length and body_size x bytes. HTTP/2 works over tcp, unix
and ntcp; udp fails validation.
Connections and streams
Each connection first sends a setup request: the preface, SETTINGS (server push off, a 1 MiB stream window) and a WINDOW_UPDATE opening the connection window to 16 MiB. The server’s SETTINGS is its reply, so no request goes out before it; none of this is measured. SETTINGS and PING from the server are acknowledged at once.
Every request is a stream, and the stream ID is its request ID. Up to
max_pending_per_connection streams are in flight on a connection, never
more than the server’s SETTINGS_MAX_CONCURRENT_STREAMS. Responses of
different streams may interleave; a stream completes at its END_STREAM.
Header blocks may span CONTINUATION frames, and padded frames, PRIORITY
and unknown frame types are handled.
Request headers use only HPACK static table indices and literals without indexing, so the header block is built once; response headers are decoded with the server’s dynamic table.
Flow control
Received DATA is discarded as it arrives. A WINDOW_UPDATE gives back a
stream’s or the connection’s window once half of it is used, so responses
of any size stream through. Request bodies respect the server’s connection
and stream windows and its SETTINGS_MAX_FRAME_SIZE; what does not fit is
sent when the server opens its windows.
Errors
A response whose :status is not 200 is an error reply whose kind is the
status ("404", "503"), counted per the group’s on_error. Informational
(1xx) responses are skipped. An RST_STREAM from the server ends its stream
as an error reply named after the error code ("REFUSED_STREAM").
A GOAWAY with NO_ERROR stops new streams on its connection while the
streams it accepted complete; xylem does not reconnect, so keep the
server’s per-connection request limit high (nginx: keepalive_requests).
A GOAWAY with another error code or one that refuses streams in flight
fails the run, as does any connection error: malformed frames, a
flow-control violation, an HPACK error, PUSH_PROMISE, or a server that
answers in HTTP/1.1.
Throughput
throughput_mbps counts every byte on the wire both ways, frame headers
and control frames included.
Testing
just test-http2 runs the integration tests against nginx with h2c, over
TCP and a Unix socket.
gRPC Protocol
protocol = "grpc" makes gRPC unary calls of one method over cleartext
HTTP/2 with prior knowledge, as ghz --insecure and grpcurl -plaintext
do. It shares the HTTP/2 protocol’s connections, streams,
flow control and GOAWAY handling. Xylem knows no protobuf schema: the
request message is raw protobuf bytes, built once, and response messages
are not decoded.
Configuration
[experiment]
name = "grpc-echo"
duration = "30s"
[[traffic_groups]]
name = "grpc"
protocol = "grpc"
target = "127.0.0.1:50051"
threads = [0, 1]
connections_per_thread = 4
# Calls in flight per connection
max_pending_per_connection = 4
[traffic_groups.protocol_config]
call = "helloworld.Greeter/SayHello"
# HelloRequest { name: "xylem" }
request_hex = "0a0578796c656d"
metadata = { x-tenant = "bench" }
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/grpc-echo.json"
| Key | Meaning |
|---|---|
call | Full method name, package.Service/Method (a leading / is allowed) |
request_file | File holding the serialized request message |
request_hex | The serialized message in hexadecimal (whitespace allowed) |
request_base64 | The serialized message in standard base64 |
messages_file | Several messages, each with gRPC’s 5-byte prefix (flag 0, big-endian length); each thread sends them in turn |
metadata | Custom metadata sent with every call, by lowercase name |
authority | :authority; defaults to the target, or localhost over a Unix socket |
Set at most one of request_file, request_hex, request_base64 and
messages_file; with none, the message is empty (every field at its
default). Files are read when the profile is validated, relative to the
working directory. Each call is a POST to /<call> with
content-type: application/grpc, te: trailers and
user-agent: grpc-xylem, and the message with gRPC’s length prefix,
uncompressed. Metadata may not set those headers, pseudo-headers or
grpc-* names.
Status
A call succeeds when :status is 200 and grpc-status is 0, from the
trailers or a trailers-only response. Any other grpc-status is an error
reply whose kind is the code ("14") and whose message is its name
(UNAVAILABLE), counted per the group’s on_error; an HTTP status other
than 200 is an error reply named after it, as for HTTP/2. A
response without grpc-status fails the run.
Xylem does not check response messages. Check results in a separate
correctness pass, such as one grpcurl call per input, instead of inside
the load generator.
TensorFlow Serving
TF Serving’s tensorflow.serving.PredictionService/Predict takes a
PredictRequest. tools/tfs-predict-request.py (Python 3, no packages)
turns PredictRequests in protobuf’s JSON mapping, the input of grpcurl and
ghz, into protobuf bytes:
# One request, for request_file
tools/tfs-predict-request.py request.json predict.bin
# Several, each prefixed, for messages_file
tools/tfs-predict-request.py --framed requests.json predict-many.bin
The input is one request object, a list of them, or an object whose
requests list holds {"request": ...} entries, such as the
validation.json of Stackbench’s TF Serving benchmark. It supports
model_spec, output_filter and inputs of TensorProtos with dtype,
tensor_shape, tensor_content and the float, double, int, string, int64
and bool values, and fails on anything else. Its output matches protobuf’s
deterministic serialization byte for byte.
A profile like Stackbench’s ghz load, 8 connections with 32 calls in flight, on TF Serving’s gRPC port:
[experiment]
name = "tfs-predict"
duration = "30s"
[[traffic_groups]]
name = "predict"
protocol = "grpc"
target = "127.0.0.1:8500"
threads = [0, 1, 2, 3]
connections_per_thread = 2
max_pending_per_connection = 4
[traffic_groups.protocol_config]
call = "tensorflow.serving.PredictionService/Predict"
# PredictRequest { model_spec { name: "ranking" } }
request_hex = "0a090a0772616e6b696e67"
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/tfs-predict.json"
Real requests carry inputs: point request_file or messages_file at the
script’s output instead of request_hex.
Testing
just test-grpc runs the integration tests against a grpcio server
(tests/grpc), over TCP and a Unix socket. With XYLEM_TFS_MODEL set to a
SavedModel base directory (served as model ranking) and
XYLEM_TFS_REQUESTS to PredictRequests for it in JSON, one test also calls
Predict on the official tensorflow/serving:2.21.0 image.
Memcached Protocol
xylem speaks memcached’s ASCII (memcached-ascii) and binary
(memcached-binary) protocols over tcp, unix and udp, with GET, SET,
ADD, REPLACE, DELETE, INCR, DECR, TOUCH and multi-key GET.
[[traffic_groups]]
name = "main"
protocol = "memcached-ascii"
target = "127.0.0.1:11211"
threads = [0]
connections_per_thread = 4
max_pending_per_connection = 8
[traffic_groups.protocol_config]
operation = "GET" # every request; or a mix with `operations`, below
[traffic_groups.protocol_config.keys]
strategy = "round-robin"
max = 10000
value_size = 4096
[traffic_groups.protocol_config.insert_phase]
key_count = 10000 # SET every key as warmup before measuring
[traffic_groups.traffic_policy]
type = "closed-loop"
Operations
| Name | ASCII request | Binary request | Parameters |
|---|---|---|---|
get | get <key> | GETK | |
set, add, replace | <name> <key> 0 0 <size> and the value | SET, ADD, REPLACE | |
delete | delete <key> | DELETE | |
incr, decr | <name> <key> <delta> | INCREMENT, DECREMENT; a missing key is not created | delta (default 1) |
touch | touch <key> <exptime> | TOUCH | exptime in seconds (default 0: never expires) |
mget | get <key> <key> ... | a GETKQ per key, then NOOP | count keys (default 10) |
Every key of a request, each key of an mget included, is drawn from the key
distribution. incr and decr need a numeric value; the values xylem writes
are x bytes, so on keys xylem stored they get a CLIENT_ERROR (binary:
DELTA_BADVAL) error reply, and on missing keys a NOT_FOUND result.
operation sends one operation in every request, with default parameters.
operations takes the shape of Redis’s: a fixed operation, or a
weighted random mix whose commands may take params and their own keys
distribution (with the group’s prefix and value size). Set operation or
operations, not both.
[traffic_groups.protocol_config.operations]
strategy = "weighted"
commands = [
{ name = "get", weight = 0.80 },
{ name = "set", weight = 0.10 },
{ name = "mget", weight = 0.05, params = { count = 8 } },
{ name = "delete", weight = 0.03 },
{ name = "touch", weight = 0.02, params = { exptime = 300 } },
]
The value_size section sets the size of SET, ADD and REPLACE values, drawn
per request, in place of keys.value_size; see
Value Size Configuration.
With per_command, set, add and replace take their own sizes.
Insert Phase
insert_phase SETs keys before anything is measured: key_count keys
(default: the keyspace size of keys, required for sequential keys), drawn
like the measured keys. insert_phase.value_size accepts either a fixed byte
count or a value_size distribution; when omitted, it defaults to value_size
if set, and otherwise to keys.value_size. Redis takes the same section
(fixed sizes only), and so does Masstree,
which inserts keys 0 to key_count - 1. Each thread
inserts all of them, and its connections share the work. The inserts are
preload: they go out as fast as the
pipelines allow, and no thread measures until every insert of every thread
has its reply, so a measured request never reaches a key before its SET. An
insert’s error reply fails the run.
Error Replies
An error reply completes its request and counts in requests.errors, with
its latency in error_latency rather than the latency distribution (see
Output Formats):
- ASCII: an
ERROR,CLIENT_ERROR ...orSERVER_ERROR ...line, by that keyword. An error line also ends a GET response after any values before it. - Binary: a non-zero response status, by its name in memcached’s
protocol_binary.h(E2BIG,DELTA_BADVAL,ENOMEM, …;UNKNOWN_STATUSfor others). A multi-get with several reports the first.
A miss or a failed condition is a successful reply, not an error: a GET’s
END without a value, NOT_FOUND, NOT_STORED and EXISTS, and the binary
statuses KEY_ENOENT, NOT_STORED and KEY_EEXISTS.
Error replies are classified the same way over UDP. Set on_error = "abort"
on the traffic group to stop the run at the first error reply instead. A
reply xylem cannot parse still stops the run.
Over UDP
Set transport = "udp" on the group; no other setting changes. memcached 1.5.6
and later disable UDP, so start it with -U <port>, for example
memcached -p 11211 -U 11211.
- Every datagram carries memcached’s 8-byte UDP frame header. xylem numbers each connection’s requests and sends the low 16 bits as the request id.
- Responses are matched by request id, so lost and reordered datagrams are tolerated. memcached splits large responses into 1400-byte datagrams; xylem reassembles them in any arrival order and drops duplicates.
- A request must fit one datagram, so values, every size a
value_sizedistribution can draw included, are limited to 64,987 bytes. mgetis TCP- and Unix-only: memcached answers a multi-get over UDP with a datagram per value, each marked as a whole response, so its end is unknown.- Both ASCII and binary work over UDP; binary was verified against memcached 1.6.45.
- Lost datagrams time out after the group’s
request_timeout(default 1 s) and count inrequests.timed_out.
See Transport Configuration: UDP.
See Also
Benchmarking Masstree with Xylem
When you’re benchmarking Masstree, you’re speaking MessagePack over TCP—a binary serialization format that’s more compact than JSON but still type-safe. Masstree is a research database system designed for high-performance key-value storage with snapshot isolation and multi-version concurrency control. This guide covers the protocol mechanics, supported operations, and how to build workloads that test MVCC behavior and transactional semantics.
Understanding the Protocol
Masstree’s protocol is built on MessagePack, a binary format that’s more compact than text-based protocols like RESP. Everything is strongly typed—strings are strings, integers are integers, maps are maps. There’s no ambiguity about whether “42” is text or a number.
The communication pattern is straightforward: send a request array, get back a response array. Each request carries a sequence number that matches the response, enabling pipelining and response matching even when they arrive out of order (though Masstree typically preserves order per connection).
Masstree uses numeric command codes instead of text strings. GET is 2, REPLACE is 8, HANDSHAKE is 14. Responses use the command code plus one: GET response is 3, REPLACE response is 9. This makes parsing efficient without string comparisons.
Connection Handshake
Every connection must handshake before sending operations. This negotiates connection parameters: which CPU core the connection should use (for thread pinning), maximum key length, and protocol version.
The handshake request looks like:
#![allow(unused)]
fn main() {
[0, 14, {"core": -1, "maxkeylen": 255}]
}
That’s an array with three elements:
- Sequence number 0 (handshakes always use seq 0)
- Command code 14 (CMD_HANDSHAKE)
- A map with parameters: core=-1 (auto-assign), maxkeylen=255
The server responds with:
#![allow(unused)]
fn main() {
[0, 15, true, 0, "Bag"]
}
That’s:
- Sequence number 0
- Response code 15 (CMD_HANDSHAKE + 1)
- Success boolean
- Index of the server thread that serves the connection
- The server’s row type (
Bagby default)
A failed handshake (a maxkeylen above the server’s) is answered with
[0, 15, false, "bad maxkeylen"] and the connection is closed; xylem stops
the run with the server’s reason.
Xylem handles this automatically for each connection. You never see the handshake—it just works.
Message Format
Every Masstree message is a MessagePack array. The structure depends on the command:
GET request: [seq, 2, key_string]
- Three elements: sequence number, command 2, the key
GET response: [seq, 3, column...]
- A hit carries every column of the row (one for a value stored by SET); a
miss echoes the request,
[seq, 3, key_string]
SET (REPLACE) request: [seq, 8, key_string, value_string]
- Four elements: sequence, command 8, key, value
SET (REPLACE) response: [seq, 9, result_code]
- Three elements: sequence, response 9, result (Inserted=1, Updated=2)
PUT request: [seq, 6, key_string, col_idx, value, col_idx, value, ...]
- Variable length: sequence, command 6, key, then pairs of column indices and values
REMOVE request: [seq, 10, key_string]
- Three elements: sequence, command 10, key
SCAN request: [seq, 4, firstkey_string, count, field_idx, field_idx, ...]
- Variable length: sequence, command 4, starting key, count, optional field indices
SCAN response: [seq, 5, key1, value1, key2, value2, ...]
- Variable length: sequence, response 5, then alternating keys and values; a value is a string for a one-column row and an array of columns otherwise
PUT, REMOVE and CHECKPOINT responses: [seq, 7, result_code],
[seq, 11, removed_bool] and [seq, 13]
A request the server does not run is answered [seq, -1]. Stackbench’s mtd
answers CHECKPOINT so on backends without blocking calls and keeps the
connection; xylem counts it as an Unsupported error reply.
MessagePack handles the binary encoding. Strings are length-prefixed (so they’re binary-safe like RESP bulk strings), integers use the most compact representation (1-5 bytes depending on size), and arrays/maps have efficient headers. This makes the wire format more compact than RESP for numeric-heavy workloads.
Sequence Numbers and Pipelining
Each request has a 16-bit sequence number. The client picks the sequence, the server echoes it back. This enables pipelining—send multiple requests without waiting, then match responses by sequence number.
Xylem manages sequences per-connection automatically: the handshake uses 0, and the requests after it count from 0 again, wrapping at 2^16. The server answers a connection’s requests in order.
The Operations
Each operation serves specific benchmarking purposes.
GET retrieves a value by key. It’s your basic read operation. Benchmark GET to measure read latency, snapshot isolation behavior, and how Masstree handles concurrent readers. If the key doesn’t exist, the server echoes the key instead of the row’s columns.
SET (REPLACE) stores or updates a value. Masstree calls it REPLACE because it replaces any existing value atomically. This isn’t an upsert in the SQL sense—it’s a blind write that doesn’t check the old value. Benchmark SET to test write throughput, MVCC overhead, and how concurrent writes interact with readers.
PUT updates specific columns within a value. Instead of reading the entire record, modifying a field, and writing it back (read-modify-write), you send only the column updates. For example, updating a user’s last login timestamp without touching their profile data. The format is [seq, 6, key, col0, val0, col1, val1, ...]. Use this to benchmark partial updates and column-based storage performance.
REMOVE deletes a key. Unlike some systems, Masstree removal is immediate (within the current snapshot)—it doesn’t wait for garbage collection. Benchmark this to test deletion throughput and how removed keys affect memory and performance.
SCAN performs range queries. Each scan starts at a key drawn from the key distribution (inclusive), and returns up to count rows with the listed fields. The response alternates keys and values: [seq, 5, "user:1000", value, "user:1001", value, ...]. This tests ordered access patterns like leaderboards, time-series queries, and scenarios where sorted iteration matters.
CHECKPOINT triggers a database snapshot. Masstree persists state by checkpointing to disk periodically. Calling CHECKPOINT explicitly forces this, which is useful for testing recovery time, checkpoint overhead, and consistency guarantees. The response is immediate, but the actual checkpoint happens asynchronously. A server started without logging (mtd -n) has nothing to checkpoint.
Result Codes
Masstree responses include result codes that tell you what happened:
- NotFound (-2): GET couldn’t find the key
- Retry (-1): Transient error, try again
- OutOfDate (0): Version conflict (rare in basic workloads)
- Inserted (1): SET created a new key
- Updated (2): SET replaced an existing value
- Found (3): GET succeeded
- ScanDone (4): SCAN completed
These codes matter for correctness testing. If you’re doing a read-your-writes test, you want to verify that SET returns Inserted or Updated, then GET returns Found with the same value.
Xylem counts a PUT or REPLACE response with result code Retry or OutOfDate, or a code outside the list above, as an error reply named by the code (Retry, OutOfDate, UnknownResult): it completes its request, counts in requests.errors, and its latency goes to error_latency (see Output Formats). A missing key is not an error: the server answers a GET miss with the key itself in place of a value, NotFound is a successful result, and so is a REMOVE that removed nothing. Set on_error = "abort" on the traffic group to stop the run at the first error reply instead. A failed handshake always stops the run.
Building Realistic Workloads
Real database workloads exhibit patterns: read-heavy vs write-heavy ratios, hot keys vs uniform access, point queries vs range scans. Xylem provides configuration options to model these patterns.
Operation Mixes
Start with pure operations. A GET-only workload tests read performance under snapshot isolation:
[traffic_groups.protocol_config]
operation = "get"
But production databases handle mixed workloads. operations takes the shape of Redis’s: a fixed operation, or a weighted random mix. A typical application with 60% reads, 30% updates, 10% deletes:
[traffic_groups.protocol_config.operations]
strategy = "weighted"
commands = [
{ name = "get", weight = 0.6 },
{ name = "set", weight = 0.3 },
{ name = "remove", weight = 0.1 },
]
Set operation or operations, not both. In a mix, scan takes the parameters count and fields (column indices) and put takes columns; without them a command uses the top-level scan and put_columns. A command may also draw its keys from its own keys distribution, with the group’s prefix and value size.
Add column-based updates to model partial record modifications. put_columns sets how many columns each PUT writes, starting at column 0; each column is a value of the value size:
[traffic_groups.protocol_config]
operation = "put"
put_columns = 2 # Update columns 0 and 1 (e.g., timestamp and counter)
Include range queries for analytics workloads. Each SCAN starts at a key drawn from the key distribution and returns up to count records with the listed column indices, or every column if fields is empty:
[traffic_groups.protocol_config]
operation = "scan"
scan = { count = 100, fields = ["0", "1"] }
Trigger periodic checkpoints to test persistence overhead from a group of their own at a low rate:
[[traffic_groups]]
name = "checkpoints"
protocol = "masstree"
target = "127.0.0.1:2117"
threads = [0]
connections_per_thread = 1
traffic_policy = { type = "fixed-rate", rate = 1.0 } # One checkpoint per second
protocol_config = { operation = "checkpoint" }
Now you’re testing a realistic mix: mostly reads, some writes, occasional range scans, and periodic checkpoints.
Key Distributions
Uniform random keys rarely reflect production workloads. Real systems exhibit skew—some records are hot, others are cold.
Zipfian distribution models skewed access. With exponent 0.99, a small fraction of keys receive most of the traffic:
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 256
This models user databases where active users dominate, e-commerce where bestsellers get most queries, or social networks where popular content drives traffic.
Gaussian (normal) distribution clusters keys around a center, modeling temporal locality where recent records are hot:
[traffic_groups.protocol_config.keys]
strategy = "gaussian"
mean_pct = 0.5 # Center of key space
std_dev_pct = 0.1
max = 10000
value_size = 256
Use this for time-series data where recent timestamps matter, or any sliding-window workload.
Sequential access walks through keys in order. Perfect for testing SCAN performance or bulk imports:
[traffic_groups.protocol_config.keys]
strategy = "sequential"
start = 0
value_size = 256
This is also how you test worst-case behavior in trees—sequential inserts can stress rebalancing.
Value Sizes
The value_size in keys configuration sets a fixed size. For variable sizes, use the value_size section:
[traffic_groups.protocol_config.value_size]
strategy = "fixed"
size = 256 # All values are 256 bytes
But real databases have variation. Some records are small (user preferences), others are large (document content):
[traffic_groups.protocol_config.value_size]
strategy = "normal"
mean = 1024.0
std_dev = 256.0
min = 128
max = 8192
Or use uniform distribution for evenly spread sizes:
[traffic_groups.protocol_config.value_size]
strategy = "uniform"
min = 512
max = 4096
Or a weighted list of sizes, such as a measured histogram:
[traffic_groups.protocol_config.value_size]
strategy = "weighted"
sizes = [{ size = 64, weight = 0.9 }, { size = 4096, weight = 0.1 }]
Each SET value and each PUT column draws its own size; per_command gives set and put different sizes. This models caching patterns where reads are metadata lookups and writes are full document stores.
MVCC and Snapshot Isolation
Masstree’s key differentiator is MVCC. Every read sees a consistent snapshot—a point-in-time view of the database. Even if concurrent transactions are modifying data, reads see the version that existed when the transaction started.
GET operations never block on writes, and writes never block reads. This provides true concurrency without read locks. The tradeoff is version maintenance: Masstree maintains multiple versions of each value, and garbage collection cleans up old versions periodically.
Benchmarking MVCC Workloads
To test snapshot isolation, run concurrent readers and writers on the same keys, as two traffic groups with the same key distribution:
[[traffic_groups]]
name = "mvcc-readers"
protocol = "masstree"
target = "127.0.0.1:2117"
threads = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
connections_per_thread = 10
max_pending_per_connection = 1
traffic_policy = { type = "closed-loop" }
[traffic_groups.protocol_config]
operation = "get"
keys = { strategy = "zipfian", n = 1000, theta = 1.2, value_size = 256 } # Very hot keys
[[traffic_groups]]
name = "mvcc-writers"
protocol = "masstree"
target = "127.0.0.1:2117"
threads = [11, 12, 13, 14, 15]
connections_per_thread = 10
max_pending_per_connection = 1
traffic_policy = { type = "closed-loop" }
[traffic_groups.protocol_config]
operation = "set"
keys = { strategy = "zipfian", n = 1000, theta = 1.2, value_size = 256 }
This creates contention on hot keys. Measure:
- GET latency distribution: Does P99 stay low even under write pressure?
- SET throughput: How many concurrent updates can Masstree handle?
- Version chain length: Are old versions accumulating?
You should see GET latencies remain stable even as SET rate increases, because readers don’t block. If P99 GET latency spikes, you might be hitting garbage collection pauses or version chain traversal overhead.
Read-Your-Writes Testing
Read-your-writes consistency means a GET always sees the value of an earlier SET to the same key, even while other clients modify that key. xylem frames GET responses but does not compare the returned value with the one it wrote, so it cannot check this property itself. Use it to load the server with a mixed GET/SET workload on hot keys, as above, and check consistency with a separate client.
Common Workload Patterns
Here are typical workload patterns and how to model them.
User Session Store: 70% GET (check sessions), 20% SET (create/update), 10% REMOVE (logout/expire). Gaussian distribution (active users cluster), small uniform values (256-512B for session tokens). Use PUT to update just the “last_seen” timestamp without rewriting the entire session. Measure P99 latency and verify MVCC keeps reads fast during write spikes.
E-Commerce Inventory: 80% GET (check stock), 15% PUT (update counts), 5% SCAN (query ranges). Zipfian (popular products dominate), fixed value sizes (structured inventory records). Use PUT with column 0 for stock count. Test throughput under concurrent updates to the same SKU—MVCC should prevent read stalls.
Time-Series Metrics: 30% GET (recent values), 60% SET (new datapoints), 10% SCAN (range queries). Sequential or Gaussian keys (recent timestamps are hot), fixed sizes (metric tuples). High write rate with periodic SCAN to fetch time windows. Measure checkpoint overhead and verify SCAN performance with large result sets.
Analytics Query Engine: 20% GET (metadata), 10% SET (cache results), 70% SCAN (aggregations). Uniform distribution (analytics queries hit many keys), variable value sizes (small metadata, large aggregated results). Focus on SCAN throughput and latency, especially with large counts (1000+ records per SCAN).
Transactional Workload (YCSB-style): Mix of GET, SET, REMOVE with Zipfian distribution, hot keys creating contention. This tests MVCC’s core value proposition: can you sustain high throughput with strong isolation guarantees? Measure throughput vs latency tradeoff and compare with Redis’s single-threaded model.
Comparing Masstree to Redis
Choosing between Masstree and Redis for benchmarking depends on your consistency requirements.
Use Masstree when:
- You need snapshot isolation and MVCC semantics
- Your workload has concurrent readers and writers on the same keys
- You want to test column-based updates (partial record modifications)
- Range queries (SCAN) are a significant part of your workload
- You’re benchmarking transaction processing systems
Use Redis when:
- You need raw speed above all else (single-threaded execution)
- Your workload is primarily read-heavy with occasional writes
- You want to test caching layers where eventual consistency is fine
- You need pub/sub, Lua scripting, or Redis modules
- You’re benchmarking web session stores, rate limiters, or CDN caches
Key differences:
| Feature | Masstree | Redis |
|---|---|---|
| Concurrency | Multi-threaded MVCC | Single-threaded (per core) |
| Isolation | Snapshot isolation | No isolation guarantees |
| Protocol | MessagePack (binary) | RESP (text-based) |
| Updates | Column-based PUT | Full-value SET only |
| Range queries | Native SCAN | Requires sorted sets |
| Use case | Transactional systems | Caching, pub/sub |
Masstree trades peak throughput for stronger consistency guarantees. Applications requiring “read committed” or “snapshot isolation” semantics should benchmark against Masstree rather than Redis.
Advanced Patterns
Range Query Tuning
SCAN performance depends on how much data you’re fetching. With operation = "scan", the scan table sets it:
[traffic_groups.protocol_config]
operation = "scan"
scan = { count = 10, fields = ["0", "1"] } # 10 records, columns 0 and 1
# scan = { count = 1000 } returns 1000 records with every column
Measure:
- Latency vs count: Does P99 grow linearly or worse?
- Throughput impact: Do large SCANs starve other operations?
- Network overhead: Are you transfer-bound with large counts?
Tuning SCAN is about balancing batch size (larger = more efficient) vs latency (larger = longer per-operation time).
Checkpoint Overhead
Checkpoints serialize the database to disk, consuming time and I/O resources. The rate of the checkpoint group sets how often they run:
[[traffic_groups]]
protocol_config = { operation = "checkpoint" }
traffic_policy = { type = "fixed-rate", rate = 0.1 } # one every 10 seconds; 10.0 is ten a second
Measure:
- Latency during checkpoint: Do other operations slow down?
- Throughput degradation: What’s the sustained write rate with frequent checkpoints?
- Recovery time: How long to load a checkpoint on restart?
This helps you understand the durability vs performance tradeoff.
Column-Based Update Efficiency
PUT operations are more efficient than read-modify-write cycles:
# Inefficient: GET + SET (read full record, modify, write back)
# This requires two network round-trips and full value transfer
# Efficient: PUT (update specific columns)
[traffic_groups.protocol_config]
operation = "put"
put_columns = 1 # Only update column 0
Benchmark the difference:
- Latency: PUT should be ~2x faster (one round-trip vs two)
- Bandwidth: PUT uses less network (only changed columns vs full record)
- Contention: PUT reduces lock time (Masstree only locks affected columns)
For structured data with frequent partial updates, PUT is the right model.
Deterministic Value Verification
Set verify = true (and optional verify_seed, default 0) to check every GET response byte-for-byte against a deterministic function of (verify_seed, key_bytes, value_size, col_idx). When enabled, SET (REPLACE), PUT, and insert_phase write that exact byte pattern, and verification requires a fixed value size (if insert_phase is configured, its resolved value_size must match):
[traffic_groups.protocol_config]
keys = { strategy = "round-robin", max = 1000, value_size = 512 }
insert_phase = {}
verify = true
verify_seed = 42
operations = { strategy = "weighted", commands = [
{ name = "get", weight = 0.8 },
{ name = "set", weight = 0.2 },
] }
Pattern Formula
An external or synthetic responder can reproduce the exact byte sequence for (seed: u64, key: &[u8], value_size: usize, col_idx: u32) as follows:
- Hash
keywith 64-bit FNV-1a (offset basis0xcbf29ce484222325, prime0x00000100000001b3):h = fnv1a_64(key) - Define
splitmix64(x):x = x.wrapping_add(0x9e3779b97f4a7c15)x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9)x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb)- return
x ^ (x >> 31)
- Compute the per-key base word:
base = splitmix64(seed ^ h ^ (value_size as u64).wrapping_mul(0x9e3779b97f4a7c15) ^ (col_idx as u64).wrapping_mul(0xbf58476d1ce4e5b9)) - For each 8-byte chunk
w = 0, 1, 2, ..., emitsplitmix64(base.wrapping_add(w.wrapping_mul(0x9e3779b97f4a7c15))).to_le_bytes(), truncated tovalue_sizebytes.SET(REPLACE),insert_phase, andGETcolumn 0 usecol_idx = 0; multi-columnPUTuses each column’s index0..columns.
Verification Errors and Run Verdict
Any GET mismatch is counted as a named error in requests.errors / requests.errors_by_kind, recorded in traffic_groups[].verification (including verified, failures, and first_mismatch with kind, key, offset, expected, actual, expected_len, actual_len, detail), and fails the verification validity check (verdict = "invalid_run", exit code 3):
ValueMismatch— a byte differs from the expected pattern, the column is longer thanvalue_size, or the first GET column is not a MessagePack string/binary value.ShortValue— the returned value is shorter thanvalue_size.UnexpectedMiss— the server echoed[seq, 3, key](Masstreemtdmiss response).
Wrapping Up
Masstree benchmarking focuses on MVCC behavior and transactional semantics. Xylem provides the configuration primitives: operation mixes, key distributions, value sizes, column-based updates, range queries. The goal is modeling your actual database workload.
Start with baseline measurements. Benchmark pure GET and SET with uniform keys to understand Masstree’s baseline performance. Then add realistic complexity: hot keys with Zipfian distribution, mixed operations with production ratios, column updates with PUT, range queries with SCAN. Pipeline aggressively since Masstree handles concurrency well, and watch for MVCC overhead—version chains, garbage collection, checkpoint pauses.
Your benchmarks should provide concrete insights. Not just “Masstree can do 50K QPS,” but “our transactional system can handle 10K concurrent users with snapshot isolation, P99 latency under 5ms, and checkpoint every 10 seconds without stalling operations.” This data determines whether MVCC overhead is justified for your use case.
See Also
- Workload Configuration - Detailed configuration guide
- Configuration Schema - Complete reference
- Masstree Paper - Original research paper
- MessagePack Format - Wire format specification
DNS Protocol
protocol = "dns" sends standard DNS queries (RFC 1035) for load against
authoritative or recursive servers, over tcp, unix, ntcp and udp.
Each query asks one question in class IN; its name and type are drawn
independently from weighted mixes, or together from a weighted list of pairs.
[experiment]
name = "knot-tcp"
duration = "30s"
seed = 1
[[traffic_groups]]
name = "knot"
protocol = "dns"
target = "127.0.0.1:5353"
threads = [0]
connections_per_thread = 4
max_pending_per_connection = 16
[traffic_groups.protocol_config]
recursion_desired = false # RD flag; default true
edns = { udp_size = 1232, dnssec_ok = false } # OPT record; default none
nxdomain = "success" # or "error" (default)
qtypes = [
{ qtype = "A", weight = 8 },
{ qtype = "AAAA", weight = 2 },
{ qtype = "TXT" }, # weight defaults to 1
]
names = [
{ name = "www.example.test.", weight = 4 },
{ name = "absent.example.test." },
{ pattern = "h{key}.wild.example.test.", keys = { strategy = "zipfian", n = 10000, theta = 0.99 } },
]
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/knot-tcp.json"
Queries
-
names(required withoutqueries): each entry is either a fixednameor apatternwith one{key}, which each query replaces with a decimal key fromkeys.keystakes the strategies of the key-value protocols without their value size and prefix:sequential(start),random(max),round-robin(max),zipfian(n,theta) andgaussian(mean_pct,std_dev_pct,max). Names are plain ASCII labels of up to 63 bytes, 255 bytes in all; the final dot is optional. A pattern must leave room for a 20-digit key. -
qtypes: A, NS, CNAME, SOA, PTR, MX, TXT, AAAA, SRV, NAPTR, DS, RRSIG, NSEC, DNSKEY, SVCB, HTTPS, CAA, ANY, or any other type asTYPE<n>(RFC 3597). Default: A only. -
recursion_desired: the RD flag, default true as with dig and dnspython. -
queries: (name, qtype) pairs instead ofnamesandqtypes, which it excludes. Each entry is anameor apatternwithkeys, as innames, aqtype, and aweight(default 1):[traffic_groups.protocol_config] queries = [ { name = "www.example.test.", qtype = "A", weight = 4 }, { name = "www.example.test.", qtype = "AAAA" }, { pattern = "h{key}.wild.example.test.", qtype = "A", keys = { strategy = "random", max = 1000 } }, ] -
edns: adds an EDNS(0) OPT record (RFC 6891) with the UDP payload sizeudp_size(512 to 65535, default 1232) and the DO bitdnssec_ok.
Every weight must be finite and non-negative, and at least one per mix
positive. seed in [experiment] makes the draws reproducible.
Message IDs and Pipelining
The 16-bit message ID is the request ID. Over a stream each connection hands
out IDs in turn and skips those still in flight, so up to
max_pending_per_connection queries (at most 65536) are pipelined on a
connection. Responses may come back in any order (RFC 7766) and are matched
by ID.
Over UDP a lost response never frees its ID, so IDs are handed out in turn
without skipping: a query reuses the ID of the query sent 65536 queries
before it on that connection, which has long timed out at any realistic
rate and request_timeout.
Framing
Over tcp, unix and ntcp each message is preceded by its length as a
2-byte big-endian integer (RFC 1035 section 4.2.2, RFC 7766). Over udp
each query and each response is one bare datagram.
Responses and Error Replies
A response must have the QR bit, opcode QUERY and the ID of a query in flight, echo that query’s question (names compare case-insensitively), and be well formed to its last record. A response without a question is accepted only with an RCODE other than NOERROR, as servers send for FORMERR. Over a stream anything else stops the run. Over UDP a response for no query in flight, or for a different question, is dropped as a duplicate or late response, and malformed datagrams stop the run.
An error reply completes its query and counts in requests.errors by kind
(see Output Formats):
- A response with the TC (truncated) bit counts as kind
TC. It is common over UDP when an answer exceeds 512 bytes, or theedns.udp_size. - Otherwise a non-zero RCODE, including the extended bits of an OPT record,
counts by its name:
FORMERR,SERVFAIL,NXDOMAIN,NOTIMP,REFUSED,BADVERS, … (UNASSIGNEDfor unassigned codes). - NXDOMAIN counts as success with
nxdomain = "success", for a load that includes absent names on purpose.
Set on_error = "abort" on the traffic group to stop the run at the first
error reply instead.
Out of Scope
Zone transfers (AXFR, IXFR), NOTIFY, UPDATE, TSIG and TKEY are not supported: such qtypes fail validation, and every query has opcode QUERY. DNS over TLS, HTTPS or QUIC is not supported either.
Testing
The dns_integration tests run xylem against Knot DNS 3.6
(cznic/knot:3.6) with the zones of Stackbench’s knot benchmark, in
tests/knot, over TCP and UDP:
cargo nextest run --profile integration -E 'binary(dns_integration)'
See Also
NVMe/TCP Protocol
protocol = "nvme-tcp" puts NVM read and write load on an NVMe over Fabrics
target over TCP (NVMe/TCP 1.0), such as SPDK’s nvmf_tgt or the Linux
kernel target. It speaks to one namespace of one subsystem, over tcp,
unix or ntcp.
[experiment]
name = "spdk-4k-randread"
duration = "10s"
seed = 1
[[traffic_groups]]
name = "nvme"
protocol = "nvme-tcp"
target = "127.0.0.1:4420"
threads = [0]
connections_per_thread = 4 # I/O queues per thread
max_pending_per_connection = 32 # queue depth of each I/O queue
[traffic_groups.protocol_config]
subnqn = "nqn.2016-06.io.spdk:cnode1" # required
nsid = 1 # default 1
block_size = 4096 # bytes per command; default 4096
read_percent = 70 # the rest are writes; default 100
access = "random" # or "sequential"; default "random"
lba_start = 0 # first LBA of the range; default 0
lba_count = 262144 # LBAs in the range; default: to the end of the namespace
io_queues_per_controller = 2 # default: all of a thread's connections
verify = false # readback-compare mode; default false
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/nvme.json"
hostnqn sets the host NQN, which defaults to a fixed
nqn.2014-08.org.nvmexpress:uuid: NQN.
Controllers and queues
connections_per_thread counts I/O queues. Each thread connects one
controller per io_queues_per_controller of them, and each controller adds
one admin queue connection of its own, so the example opens 2 admin and 4
I/O queue connections per thread. Every connection exchanges ICReq and
ICResp first. The admin queue then connects (Fabrics Connect, QID 0) and
gets the controller ID, reads CAP, enables the controller, waits for
CSTS.RDY, and identifies the controller (in-capsule data size, MDTS) and the
namespace (LBA size and count). Only then do the controller’s I/O queues
connect, with its controller ID and max_pending_per_connection entries.
All of that is connection setup: none of it is measured, and an open-loop
schedule starts once a queue has connected. Admin queues never carry load,
and with dispatch = "group" no arrival goes to one. Statistics come only
from I/O queue commands. A target that rejects a step, such as more I/O
queues than its max_io_qpairs_per_ctrlr or a queue depth beyond its
CAP.MQES, fails the run with the step and status.
Connect sets no keep alive timeout (KATO 0). SPDK’s target then runs no keep alive timer, nor does the Linux target, so no Keep Alive commands are sent.
Commands
Each command reads or writes block_size bytes, which must be a whole
number of the namespace’s LBAs, at a block of the range picked by access:
blocks in turn from lba_start, wrapping at the end of the range, or
uniformly random ones. The command ID is the request ID.
- A write of up to the target’s in-capsule data size (IOCCSZ; SPDK’s
in_capsule_data_size, 4096 by default) carries its data in the command capsule. A larger one waits for the target’s R2Ts and answers each with H2CData PDUs of at most the MAXH2CDATA the target granted. Those PDUs are protocol-driven sends: they are no requests and carry no latency. - A read gets its data in C2HData PDUs, which are parsed as they arrive however large they are. A C2HData PDU with the SUCCESS flag completes the read; otherwise its CapsuleResp does.
A command that fails is an error reply named after its status, such as
LBA_OUT_OF_RANGE or INVALID_FIELD, counted per the group’s on_error.
Header and data digests are off; a target that turns them on fails the run.
Throughput
throughput_rps is IOPS. throughput_mbps counts megabits per second of
every byte on the wire both ways, PDU headers included (a 4 KiB read is a
72-byte capsule out and a 4120-byte C2HData PDU in), so payload MiB/s is
throughput_rps × block_size / 2^20.
Readback-compare mode
With verify = true every write carries a pattern fixed by its LBA alone,
and every read must return the pattern of its LBAs, or the run fails naming
the first LBA and byte that differ. Before any measured command each thread
writes the whole range once (warmup writes, not measured), as
preload: no thread measures until every
thread’s prefill writes have completed. Writes of the mix
rewrite the same pattern, so reads and writes can share the range. Prefer a
small lba_count: every thread writes all of it, and checking the data
costs CPU.
Testing against SPDK
cargo nextest run --profile integration -E 'binary(nvme_tcp_integration)'
(or just test-nvme) starts SPDK’s nvmf_tgt with a Malloc bdev on a free
loopback port: unprivileged, without hugepages (--no-huge -s 512), on one
core (the last CPU, or XYLEM_NVMF_CORE). The binary is XYLEM_NVMF_TGT,
which the flake’s devShell (nix develop) sets to the nvmf_tgt of its
nixpkgs’ SPDK.
ClickHouse Protocol
protocol = "clickhouse" sends SQL queries over ClickHouse’s native TCP
protocol (port 9000), the protocol clickhouse-client and
clickhouse-benchmark speak. Each connection logs in once, then runs one
query at a time and reads its whole result.
[experiment]
name = "clickhouse"
duration = "30s"
seed = 1
[[traffic_groups]]
name = "queries"
protocol = "clickhouse"
target = "127.0.0.1:9000"
threads = [1]
connections_per_thread = 4
max_pending_per_connection = 1 # required: one query at a time
[traffic_groups.protocol_config]
database = "bench" # default: the user's default database
user = "xylem" # default: "default"
password = "xylem-test" # or password_env = "VAR"; default: empty
settings = { max_threads = 1 } # sent with every query; default: none
queries = [
{ sql = "SELECT name, price FROM items WHERE id = 4242", weight = 8 },
{ sql = "SELECT category, count(), avg(price) FROM items GROUP BY category" },
{ sql = "SELECT * FROM items" }, # weight defaults to 1
]
[traffic_groups.traffic_policy]
type = "closed-loop"
[output]
format = "json"
file = "results/clickhouse.json"
Queries
query: the SQL text of every query, orqueries: a weighted mix, each entry ansqltext and aweight(default 1), drawn per query with probability weight / total weight by the shared weighted selector;seedin[experiment]makes the draws reproducible. Set exactly one ofqueryandqueries.database,user(defaultdefault) andpasswordlog in; setpassword_envto the name of an environment variable instead ofpasswordto keep the password out of the profile. Logs and errors never show it.settings: query settings such asmax_threadsormax_block_size, as strings, integers, floats or booleans (sent as 1 and 0). They are marked important, so a server that does not know one fails each query with an error reply instead of ignoring it.
The SQL text goes to the server as it is. A FORMAT clause changes
nothing: over the native protocol the server always sends Native blocks. An
INSERT must carry its rows in the query (INSERT ... VALUES or
INSERT ... SELECT); one that waits for data blocks from the client fails
the run, since xylem sends none.
Connection Setup
Each connection first sends a Hello with the database, user and password,
and waits for the server’s Hello. This setup request is not measured, and a
connection’s schedule starts once it is done. A failed login fails the run
with the server’s message, such as ClickHouse refused the connection: DB::Exception: xylem: Authentication failed: ... (code 516).
Xylem speaks protocol revision 54453, and both sides use the lower of it and the server’s revision. 54453 is the last revision before custom serializations (54454), so the server sends every column in its default layout and never sparse; Stackbench’s ClickHouse 26.8.29.10 speaks 54492. Servers older than revision 54429 (ClickHouse 20.x) are refused. Compression stays off: the client chooses it in each query, so a server cannot turn it on. There is no TLS, and no keepalive Ping: connections stay busy.
Results
The server answers a query with packets until EndOfStream: an empty header
block that names the result’s columns, the result blocks, Progress,
ProfileInfo, Totals, Extremes, Log and ProfileEvents packets. Xylem reads the
type name of each column and steps over its data without decoding it: the
numeric, date and time, decimal, enum, UUID and IP types, String,
FixedString, Nullable, Array, Tuple, Map, Nested,
LowCardinality, SimpleAggregateFunction and the geo types. A result
with another type (Dynamic, Variant, JSON, AggregateFunction, …)
fails the run naming the type. Results stream through the 64 KiB receive
buffer, so a query may return any number of rows; the latency is the time
to the last byte of EndOfStream.
Errors
An Exception packet completes its query as an error reply whose kind is the
ClickHouse error code, counted in errors_by_kind: 60 for
UNKNOWN_TABLE, 62 for a syntax error, 395 for throwIf, and so on. The
connection then goes on with its next query. The traffic group’s on_error
setting decides whether error replies are counted or fail the run.
Transports
Over the stream transports tcp, unix and ntcp; udp fails
validation. ClickHouse has no Unix socket listener for the native protocol,
so unix needs a proxy that offers one. The integration tests run over
tcp against clickhouse/clickhouse-server 26.8.29.10.
Bulk Stream Protocol
protocol = "stream" measures unidirectional bulk byte throughput (a TCP/ntcp
“sink” or reverse stream) with optional deterministic payload verification.
Unlike request/response protocols, "stream" transfers raw byte streams
without request framing or per-request latency tracking, reporting exact
tx_bytes, rx_bytes, tx_mbps, and rx_mbps in the JSON and console
outputs.
Supported transports: stream transports (tcp, unix, ntcp). Datagram
transports (udp) are rejected at profile load.
Configuration
| Key | Type | Default | Description |
|---|---|---|---|
direction | "send" | "recv" | "send" | "send" streams client → server (one-way TX). "recv" reads an unsolicited server → client stream (RX). |
chunk_size | integer (>= 1) | 65536 | Chunk size in bytes generated per one-way write in "send" mode. |
bytes | integer (>= 1, optional) | unset | Measurement byte limit. When set, measurement stops once this many bytes have transferred (or experiment.duration elapses first). When every traffic group is a "stream" group with bytes set, experiment.duration may be omitted. |
seed | integer (u64) | 0 | Deterministic byte-pattern seed shared between client and server. |
verify | boolean | true | Verify received bytes against the deterministic pattern in "recv" mode. Mismatches fail the verification validity check (exit status 3, verdict = "invalid_run"). |
Experiment Lifecycle Keys
Two [experiment] keys pair naturally with bulk streams and connection
lifecycle testing:
experiment.warmup(default"0s"): time-based warm-up before the measurement window starts. Traffic during warm-up is excluded from statistics, while wire stream offsets remain continuous from byte0across the warm-up/measurement boundary so peers verify one unbroken stream.experiment.idle_hold(default"0s"): quiescent hold after draining responses and before closing connections. Keeps sockets open while polling the transport and discarding any inbound bytes without recording late responses.
Deterministic Byte Pattern
Every 8-byte word w covering 0-based stream byte offsets [w * 8 .. w * 8 + 8)
in little-endian byte order is computed from seed and w via SplitMix64:
word(seed, w) = splitmix64(seed ^ (w * 0x9e3779b97f4a7c15))
where splitmix64(x) is:
#![allow(unused)]
fn main() {
fn splitmix64(mut x: u64) -> u64 {
x = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
x ^ (x >> 31)
}
fn stream_pattern_word(seed: u64, word_index: u64) -> u64 {
splitmix64(seed ^ word_index.wrapping_mul(0x9e37_79b9_7f4a_7c15))
}
}
Equivalent C reference implementation for external servers:
#include <stdint.h>
static inline uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15ULL;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return x ^ (x >> 31);
}
static inline uint64_t stream_pattern_word(uint64_t seed, uint64_t word_index) {
return splitmix64(seed ^ (word_index * 0x9e3779b97f4a7c15ULL));
}
For seed = 0, stream_pattern_word(0, 0) == 0xe220a8397b1dcdaf (first 8 wire
bytes: af cd 1d 7b 39 a8 20 e2).
Examples
Send by Exact Byte Limit with Warm-Up
experiment.duration is omitted; the run warms up for 1s, then sends
exactly 1 GiB of measured bytes and exits once all bytes are handed to the
transport:
[experiment]
name = "stream-send-bytes"
warmup = "1s"
idle_hold = "500ms"
[[traffic_groups]]
name = "sink"
protocol = "stream"
target = "127.0.0.1:9000"
transport = "tcp"
threads = [0]
connections_per_thread = 1
max_pending_per_connection = 1
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.protocol_config]
direction = "send"
chunk_size = 65536
bytes = 1073741824
seed = 0
[output]
format = "json"
file = "stream-send-bytes.json"
Send by Duration with Warm-Up
Stream continuously for 10s after a 1s warm-up:
[experiment]
name = "stream-send-duration"
warmup = "1s"
duration = "10s"
[[traffic_groups]]
name = "sink"
protocol = "stream"
target = "127.0.0.1:9000"
transport = "tcp"
threads = [0]
connections_per_thread = 1
max_pending_per_connection = 1
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.protocol_config]
direction = "send"
chunk_size = 65536
seed = 42
[output]
format = "json"
file = "stream-send-duration.json"
Reverse Stream Receive with Payload Verification
Receive 64 MiB from a server and verify every byte from stream offset 0:
[experiment]
name = "stream-recv-verify"
[[traffic_groups]]
name = "reverse-stream"
protocol = "stream"
target = "127.0.0.1:9000"
transport = "tcp"
threads = [0]
connections_per_thread = 1
max_pending_per_connection = 1
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.protocol_config]
direction = "recv"
bytes = 67108864
seed = 42
verify = true
[output]
format = "json"
file = "stream-recv-verify.json"
See Also
Xylem Echo Protocol
protocol = "xylem-echo" loads xylem-echo-server, to test Xylem’s own
measurement. A request is 16 bytes, [request_id: u64][delay_us: u64]
(little-endian), and the server echoes it after delay_us microseconds.
Xylem always sends a delay of 0. protocol_config takes no keys and may be
left out.
Transports and the echo server
xylem-echo-server listens on TCP and UDP at the same --bind address and
--port, or on a Unix socket with --unix. The protocol works over tcp,
udp, unix and ntcp. Over UDP each request is one datagram and the server
answers each with one datagram after the request’s delay; replies may arrive
out of order and match their requests by request ID. See the server’s
README.md and the UDP transport.
Error Replies
An echo is never an error reply, so requests.errors is always zero.
See Also
Transports
Xylem supports multiple transport layers for network communication.
Supported Transports
- TCP - Reliable byte stream transport
- UDP - Unreliable datagram transport
- Unix Domain Sockets - Local inter-process communication
- ntcp - User-space TCP over a TUN device, a DPDK port or AF_XDP sockets (Linux,
ntcp,ntcp-dpdkandntcp-af-xdpbuild features)
Transport Selection
Specify transport in each [[traffic_groups]] section of your TOML profile. It defaults to "tcp". Groups sharing a thread must use the same transport:
[[traffic_groups]]
transport = "tcp"
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
# ...
For Unix sockets:
[[traffic_groups]]
transport = "unix"
name = "main"
protocol = "redis"
target = "/var/run/redis.sock"
# ...
For ntcp, which also needs a top-level [ntcp] section with one TUN device and address per thread:
[[traffic_groups]]
transport = "ntcp"
name = "main"
protocol = "redis"
target = "10.73.0.1:6379"
# ...
[ntcp]
endpoints = [{ ifname = "ntcp0", local_ip = "10.73.0.2" }]
See Also
TCP Transport
transport = "tcp" (the default) opens each connection to the numeric
"ip:port" or "[ipv6]:port" in target.
Socket options
Every TCP connection sets TCP_NODELAY. With pipelined requests, Nagle’s
algorithm would otherwise hold a small request back until the previous one is
acknowledged, which inflates the measured latency. There is no option to turn
it off.
Timestamps
On Linux, timestamps = "kernel" or { hardware = "<interface>" } adds
kernel or NIC TX and RX timestamps; see
Transport Configuration: Timestamps.
A TCP TX timestamp covers every byte sent up to the one it reports, so
requests the kernel transmits together share one.
UDP Transport
transport = "udp" sends each request as one datagram from its own socket per
connection, and reads each reply datagram on its own. It works with
memcached-ascii, memcached-binary, dns and xylem-echo.
See Transport Configuration: UDP for
the supported protocols, memcached’s frame header, and the request_timeout
that recovers from lost datagrams.
On Linux, timestamps = "kernel" or { hardware = "<interface>" } adds
kernel or NIC TX and RX timestamps, one TX timestamp per datagram; see
Transport Configuration: Timestamps.
Unix Domain Sockets
transport = "unix" opens each connection to the stream socket at the path in
target, such as "/var/run/redis/redis.sock". Any protocol that runs over
tcp runs over it.
Unix sockets have no kernel or NIC timestamps, so timestamps must be
"user", the default.
ntcp (User-Space TCP)
The ntcp transport runs TCP in user space with ntcp, a caller-driven TCP/IP stack, instead of the kernel’s TCP. Each worker thread runs its own ntcp stack, which sends and receives packets through a packet backend: a Linux TUN device (raw IP packets), a DPDK port, or AF_XDP sockets on a network interface (Ethernet frames, with ARP).
The target server sees an ordinary TCP client. Only the client side changes, so you can compare the kernel stack with a user-space stack against the same server.
Building
ntcp is opt-in and Linux-only. Build xylem with the ntcp feature for the TUN backend:
cargo build --release --features ntcp
The DPDK backend needs the ntcp-dpdk feature, which links DPDK statically. Build it inside the nix dev shell, which provides the DPDK SDK (pkg-config libdpdk, with the mlx5 drivers) from ntcp’s flake, on x86_64 Linux:
nix develop --command cargo build --release --features xylem-cli/ntcp-dpdk
Build and run DPDK binaries with nix’s toolchain only: a binary linked against the host’s glibc fails to load nix’s rdma-core when EAL starts.
The AF_XDP backend needs the ntcp-af-xdp feature. It links libbpf and compiles an XDP program for the BPF target; the nix dev shell provides libbpf, a BPF-capable clang (NTCP_BPF_CLANG) and the Linux UAPI headers (NTCP_BPF_CFLAGS):
nix develop --command cargo build --release --features xylem-cli/ntcp-af-xdp
A build without the feature rejects transport = "ntcp" (or backend = "dpdk" or "af_xdp") with an error saying that xylem was built without that support.
TUN setup
Every worker thread that runs ntcp traffic needs its own TUN device and its own IP address. That address belongs to ntcp, not to the kernel: the kernel holds a different address on the same link and routes the replies to ntcp through the device.
# One device per ntcp thread; plain `ip tuntap add` creates IFF_NO_PI, which ntcp requires
sudo ip tuntap add dev ntcp0 mode tun user "$USER"
sudo ip addr add 10.73.0.1/24 dev ntcp0 # the kernel's side of the link
sudo ip link set ntcp0 mtu 1500 up
# ntcp then uses 10.73.0.2, which nothing else may use
The device must exist before xylem starts; xylem attaches to it and never creates, configures or removes it. The kernel side sees ntcp’s packets arrive on ntcp0. To reach a server elsewhere, the kernel has to forward them (IP forwarding plus NAT, or routes back to 10.73.0.0/24 on the server’s side). A server running on the same host can listen on 10.73.0.1 directly.
DPDK setup
The DPDK backend drives one Ethernet port. Each worker thread that runs ntcp traffic gets one queue pair of the port and its own IPv4 address on the port’s network; a flow rule steers that address to the thread’s queue. The threads share one ARP table: ntcp resolves its next hops and answers ARP requests for its addresses itself.
- The device. EAL probes only the device you name (
-a). With NVIDIA/Mellanox mlx5 NICs the port stays bound tomlx5_core(bifurcated driver) and needsib_uverbsandmlx5_ibloaded; other NICs must be bound tovfio-pci. Name PMD arguments in the device string:0000:05:00.0,dv_flow_en=1. - Hugepages. EAL needs hugepages, e.g. 1 GiB pages reserved at boot.
--in-memorykeeps EAL’s files out of/dev/hugepagesand/var/run. Besides EAL’s own, each queue’s mbuf pool takes hugepage memory on the device’s NUMA socket, allocated when the port starts: 2368 bytes an mbuf plus about 1.1 MB, so 40.0 MB a queue with ntcp’s default of 16383 mbufs (10.8 MB at 4095), 160 MB for four threads; with--no-huge, 68.3 MB a queue.dpdk.mbufs_per_queuechanges the pool size. - Received mbufs. ntcp holds each received mbuf by reference until the data it carries is read, charging the connection the mbuf’s 2368 bytes, up to a frame budget per queue: F =
mbufs_per_queue− RX descriptors − 2 × TX descriptors − 1.5 × the pool’s cache (256) × queues, 12,927 mbufs with the defaults and one thread (11,775 with four). Past ¾ F mbufs out, ntcp collapses held mbufs into copies and copies arrivals instead of holding them, so readers that stop cannot empty the pool the NIC receives into. xylem logs each queue’s F when its thread attaches the queue, and warns there if it is too small to hold any mbuf (for examplembufs_per_queue = 4095with four threads), in which case every received frame is copied; the run still starts. When a run ends, xylem warns for each thread whose stack copied arrivals or collapsed held mbufs (rx_frames_copied,rx_frames_collapsed). - Buffer shortage. When a run ends, xylem logs a warning for each thread whose port ran short of mbufs: transmits that found the thread’s pool empty and waited (
tx_nombuf), and the port’s receive buffer allocation failures (rx_nombuf) and packets the device dropped for want of a posted buffer (rx_missed). The two receive counts are the port’s totals since it started, the same in every thread’s warning; do not add them up. - Privileges. Run xylem as root (or with the capabilities DPDK needs for the device).
- Addresses. ntcp’s addresses must be unused on the network, and must not be the kernel’s address on that device.
- The port takes the device’s traffic. The port is not isolated (on mlx5, an isolated port cannot read the NIC’s clock, which NIC timestamps need), so while xylem runs, the kernel no longer receives the device’s traffic. Keep management traffic on another interface.
- CPUs. xylem pins worker thread N to CPU N, and attaches the thread’s queue after pinning it. Unless
eal_argsname lcores, EAL’s main lcore is the first CPU xylem may run on, and EAL starts no threads of its own. Busy-polling keeps each ntcp thread’s CPU at 100%.
AF_XDP setup
The AF_XDP backend shares a network interface with the kernel. xylem attaches an XDP program to the interface; it hands IPv4 packets addressed to ntcp’s addresses, and ARP for them, to an AF_XDP socket per worker thread, and passes all other traffic to the kernel, which keeps its own address and connections on the interface.
- Privileges. Run xylem as root (it needs
CAP_BPF,CAP_NET_ADMINandCAP_NET_RAW). Hosts withkernel.unprivileged_bpf_disabledstill allow root. - UMEM. Each thread’s socket registers a 32 MiB UMEM (ntcp’s default of 16384 frames of 2048 bytes), so a port of four threads takes 128 MiB. ntcp holds each received frame by reference until its data is read, up to 14,336 frames a socket (the rest fill the RX and TX rings), and copies arrivals past ¾ of that, with the same warning at the end of a run as DPDK’s. Unless xylem has
CAP_IPC_LOCK(root has it, a container’s or user namespace’s root does not), the kernel charges every UMEM to the user’s locked memory and refuses one pastRLIMIT_MEMLOCK, often 8 MiB. xylem then fails to start with an error naming the limit and the size the port needs: raise the memlock limit (ulimit -l,LimitMEMLOCK=of a systemd unit,/etc/security/limits.conf) to at least 32 MiB a thread, or grantCAP_IPC_LOCK. Other AF_XDP sockets of the same user count against the same limit. - Buffer shortage. When a run ends, xylem warns for each thread whose socket the kernel found without a posted fill-ring frame (
rx_nombuf) or dropped packets for want of one or with its RX ring full (rx_missed), the socket’s own counts (XDP_STATISTICS). - Mode.
mode = "native"(default) runs the program in the driver and fails on a driver without native XDP;"generic"works on any interface, veth included, but is slower. - Queues. With several threads, xylem installs ntuple rules (
ethtool -N) that steer each thread’s address to its queue, and ARP to one queue; the interface needs that many combined queues and ntuple filtering. One thread needs neither. - Addresses. ntcp’s addresses must be unused on the network and must not be the kernel’s addresses.
- veth. A veth pair works in generic mode, with two requirements:
-
One RX queue per end. A veth has no ntuple filters, so xylem can steer nothing to a queue. With one enabled RX queue it needs no rules: every frame arrives on queue 0, which the only ntcp thread takes. A veth created with more (
numrxqueues 2) fails at start withsteer 10.80.0.20 -> queue 0: ETHTOOL_GRXCLSRLCNT: Operation not supported.ip link add x0 type veth peer name x1enables one queue per end; else create the pair withnumtxqueues 1 numrxqueues 1on both ends, or setethtool -L <dev> rx 1 tx 1on each end. Run one ntcp thread per veth. -
TX checksum offload off on the peer. veth turns TX checksum offload on by default. The kernel on the peer end then sends its TCP segments with only a partial checksum, and generic XDP hands them to ntcp that way, so ntcp discards every SYN-ACK as a bad TCP checksum and no connection opens. Turn it off on the peer end (the kernel’s side, where the server runs) with
ethtool -K x1 tx off. When a connection does not open within the connect timeout, xylem’s error names every reason the stack discarded packets for, and for TCP checksums adds this hint:Error: Connection error: Traffic group 0: cannot open a connection to 10.80.0.1:9999: Connection timeout; ntcp (10.80.0.20) discarded 4 packets: TCP_CSUM 4; TCP checksums failed: likely TX checksum offload on the peer side of a veth or other virtual link, which leaves partial checksums; turn it off there with `ethtool -K <dev> tx off`
-
- Cleanup. xylem removes the program, its addresses and its rules when the run ends.
- Timestamps. Copy mode, user-space timestamps only: no NIC timestamps, so
timestampsmust be"user".
Configuration
Set transport = "ntcp" in the traffic groups and add a top-level [ntcp] section. With the TUN backend:
[[traffic_groups]]
name = "echo"
protocol = "xylem-echo"
target = "10.73.0.1:9999" # an ordinary socket address
transport = "ntcp"
threads = [0, 1]
connections_per_thread = 4
traffic_policy = { type = "closed-loop" }
[ntcp]
backend = "tun" # the default
mtu = 1500 # IP MTU of the links (default 1500)
endpoints = [
{ ifname = "ntcp0", local_ip = "10.73.0.2" }, # thread 0
{ ifname = "ntcp1", local_ip = "10.74.0.2" }, # thread 1
]
With the DPDK backend:
[[traffic_groups]]
name = "echo"
protocol = "xylem-echo"
target = "10.80.0.1:9999"
transport = "ntcp"
threads = [2, 3]
connections_per_thread = 1
traffic_policy = { type = "closed-loop" }
timestamps = "nic" # optional: NIC timestamps, see below
[ntcp]
backend = "dpdk"
mtu = 1500
[ntcp.dpdk]
device = "0000:05:00.0,dv_flow_en=1"
eal_args = ["--in-memory", "--file-prefix=xylem"]
local_ips = ["10.80.0.12", "10.80.0.13"] # thread 2, thread 3
prefix_len = 24
# gateway = "10.80.0.254" # for targets outside 10.80.0.0/24
With the AF_XDP backend, the [ntcp] section is:
[ntcp]
backend = "af_xdp"
[ntcp.af_xdp]
ifname = "enp5s0"
mode = "native" # or "generic"
local_ips = ["10.80.0.20", "10.80.0.21"]
prefix_len = 24
| Field | Description |
|---|---|
backend | Packet backend: "tun" (default), an existing Linux TUN device without packet information headers per thread; or "dpdk", one DPDK port shared by the threads. |
mtu | IP MTU that ntcp uses on every link, 68 to 65535. Match the device’s MTU. |
endpoints | TUN: one { ifname, local_ip } per worker thread that runs ntcp traffic groups. They map to those threads in ascending thread-ID order: with threads = [4, 2], the first endpoint goes to thread 2 and the second to thread 4. |
endpoints[].ifname | Name of that thread’s TUN device. |
endpoints[].local_ip | ntcp’s own address on that device: unicast, not one of the kernel’s addresses. |
dpdk.device | DPDK: EAL devargs of the port, a PCI address (optionally with PMD arguments) or a virtual device. |
dpdk.eal_args | More EAL arguments, after -a DEVICE (a virtual device: --vdev DEVICE --no-pci). |
dpdk.local_ips | ntcp’s IPv4 address for each worker thread that runs ntcp traffic groups, in ascending thread-ID order like endpoints. |
dpdk.prefix_len | Prefix length of the on-link network of local_ips, 1 to 32. |
dpdk.gateway | Router for targets outside that network (optional): another address on it. |
dpdk.mbufs_per_queue | Mbufs in each queue’s pool (optional; ntcp’s default, 16383, when left out). It must be more than the queue’s RX and TX descriptors together (1024 each by default): xylem refuses 0, and the port refuses to start with fewer. A power of two less one (4095, 16383) fills the pool’s ring exactly. Each mbuf takes 2368 bytes of hugepage memory (4096 with --no-huge), and the pool sets how many received mbufs ntcp may hold, see DPDK setup. |
af_xdp.ifname | AF_XDP: the network interface. |
af_xdp.mode | "native" (default) or "generic" XDP. |
af_xdp.local_ips, af_xdp.prefix_len, af_xdp.gateway | As for DPDK: one address per ntcp thread, the on-link prefix and an optional router. |
Validation requires the [ntcp] section whenever a group uses ntcp, and checks the selected backend’s settings: exactly one endpoint (TUN) or address (DPDK) per ntcp thread, each address used once, and for TUN a different device per endpoint. The other backend’s settings are ignored, so a profile can keep both and switch with --set ntcp.backend=dpdk. Groups sharing a thread share its endpoint or address. Groups on a thread must all use the same transport, as with every transport.
Buffer memory
ntcp sizes buffers as Linux does: each connection starts with a 64 KiB receive window and a 64 KiB send limit, the receive buffer grows with what the application reads per round trip (up to 32 MiB, window scale 10), and the send limit grows with the congestion window (up to 4 MiB). A connection is charged only what it has allocated: about 1.6 KB when it opens, a send ring at its first write (6 KB for a small request), which grows with the data it holds queued, and the data it receives while that is held unread or beyond a gap (each frame’s length plus its queue slot; on DPDK and AF_XDP, where ntcp holds the device’s frame itself, the frame’s size in the device’s pool), returned as it is read.
Each worker thread’s stack caps its buffer memory with the thresholds Linux’s tcp_mem takes at boot, computed from the host’s memory: MemTotal less the huge page reservation (Hugetlb) in /proc/meminfo, of which about 4.7% (low), 6.25% (pressure) and 9.4% (max, the hard cap). Above pressure, buffers stop growing until the charge falls back to low. xylem fails at startup with a configuration error, naming both numbers, if the cap is below what the thread’s connections take when they open. There is no setting to override the cap.
A write refused memory waits, as on Linux: xylem keeps the unsent bytes and sends them once ntcp reports the connection writable again. A blocking send gives up after 5 s, and a connection that cannot open for lack of memory fails with an out-of-memory error. Received data is held up to each connection’s receive limit, and only while the cap has room; past either, ntcp collapses the receive queue, prunes out-of-order data and drops segments, as Linux does. When a run ends, xylem logs a warning for each stack that had writes waiting for memory, refused opens, or memory pressure, and for each that pruned, collapsed or dropped received data for memory.
NIC timestamps (DPDK)
With the DPDK backend, timestamps = "nic" on a traffic group timestamps its requests with the NIC’s clock:
- RX: the NIC’s hardware timestamp of the packet that carried a response’s last byte.
- TX: the time ntcp handed the request’s last byte to the NIC’s transmit queue (ntcp’s Scheduled stage). The NIC sends it soon after; this backend has no hardware TX timestamps.
Each worker thread converts the NIC’s clock to xylem’s clock with a calibration fitted from paired readings of both clocks, taken about every 100 ms over a sliding window of 32 (and 8 readings when the thread starts). The latency breakdown then splits each round trip as with kernel timestamps, with the clock nic_calibrated: network_server_us is the time from the request being queued to the NIC to the response reaching the NIC, host_stack_us the rest of the user-space round trip, and user_round_trip_us the whole of it. The JSON results list each thread’s calibration under nic_clock_calibration, with its residuals (the typical conversion error, about 0.1–0.2 µs on a ConnectX-5 VF) and the number of receives without a usable timestamp. See Output Formats.
Testing without root
just test-ntcp runs an end-to-end test in an unprivileged user and network namespace (unshare -rn), with TUN devices that exist only inside it. It runs xylem-echo-server on the kernel side and compares ntcp with kernel TCP over the same devices, for one thread and for two. See tests/ntcp/tun_netns.sh. The DPDK backend needs a real NIC (or a virtual device) and root; its unit tests run the same code over a simulated NIC.
Current limitations
- TCP only. There is no user-space UDP.
- Timestamps. With TUN and AF_XDP, user-space timestamps only: latencies use the CPU timestamp counter read when the send was accepted by ntcp and when a receive completed, and
poll_tx_timestampsreports nothing. With DPDK,timestamps = "nic"adds the NIC timestamps above; there are no kernel timestamps. - One endpoint per thread. Threads never share a stack.
- Polling. Each send pushes its connection’s output onto the wire as it returns, as Linux’s
sendmsgdoes, and a group drives its stack whenever xylem polls. On DPDK, whose device completes transmits later, a push autocorks (as Linux’stcp_autocorking) a small write while the connection’s previous one is still in the device; the next poll’s first drive sends it, together with what later writes added, before the stack may wait. With TUN it sleeps on the device’s file descriptor when the stack has nothing left to do; with DPDK and AF_XDP it busy-polls its queue. With busy polling on, xylem’s polls do not wait, so TUN drives its stack on each one instead of sleeping; DPDK and AF_XDP spin as before. Each connection’s stack work costs CPU time on the worker thread, and that time is part of the measured latency. - No startup wait. Like Linux after a reboot, ntcp opens connections as soon as a run starts. It does not wait out the 2×MSL (240 s) TIME-WAIT state of a previous run. A run that reuses an ntcp address and port against the same server within 4 minutes of an earlier run could in principle meet that run’s old segments; ntcp’s per-run secret and TCP timestamps make this very unlikely.
See Also
Output Formats
Set format and file in the profile’s [output] section:
[output]
format = "both"
file = "results"
json(default): Experiment metadata, the verdict with its thresholds and validity checks (see Thresholds and Validity), global statistics, and per-group statistics.html: A report with latency and throughput charts.both: JSON and HTML files.human: Console statistics only.
The CLI sets the file extension to .json or .html as appropriate. file is
required even for human. All formats also print a human-readable summary.
Run phases
Every thread first opens its connections. Once all threads have, the run starts at one time they share, shortly after the last one is ready; every rate-driven schedule counts from it (see traffic policy). Then a run has three phases:
-
Warmup: connection setup (such as Redis AUTH or the Masstree handshake) and requests a protocol marks as warmup, such as an insert phase. They are excluded from every statistic and count. A connection the server closes during setup, or whose setup has not finished
experiment.setup_timeout(default 10 s) after its connect started or when the run ends, fails the run at once (exit status 1, no result files) with an error naming its traffic group, connection and protocol, such asTraffic group 0, connection 0 (clickhouse): connection closed during setup: Connection closed by peerorTraffic group 0, connection 0 (redis): connection setup did not finish within the setup timeout (10s).Preload (an
insert_phase, NVMe/TCPverify) is warmup that must be done before anything is measured. If any traffic group has some, every thread first sends its setup and preload requests as fast as its pipeline allows, off every schedule, and holds every other request. Once a thread has no setup or preload left and every reply has arrived, it waits for the others; the measurement phase starts shortly after the last thread finished, at one time all threads share, so no measured request reaches the server before the data the preload wrote. The connections of a thread share its insert phase: one connection’s measured requests wait for the replies to the others’ inserts. An error reply to a preload request (whateveron_errorsays), a connection the server closes, or a request that times out during preload fails the run like a setup failure, such asTraffic group 0, connection 1 (redis): connection closed during preload: Connection closed by peerorTraffic group 0, connection 1 (memcached-ascii): error reply SERVER_ERROR during preload: .... Preload takes as long as its data takes to write, so it has no time limit of its own; but a thread that receives nothing forexperiment.setup_timeoutwhile it preloads fails the run (preload received nothing within the setup timeout (10s)). -
Measurement: from the first measured request to
experiment.durationafter the start, or after the end of preload if there is one. Every rate-driven schedule and the stats’ time buckets count from that start too. Only responses that arrive in this window count toward throughput. -
Drain: sending stops, and the run waits up to
experiment.drain_timeout(default 1 s) until no request is pending. Requests completed during the drain contribute their latency to the percentiles and statistics, but not to throughput. Requests still pending when the drain ends count astimed_outand have no latency.
Throughput and the measured window
experiment.duration_secs is the configured duration. Throughput
(throughput_rps, throughput_mbps) is computed over
experiment.measured_duration_secs: from the first measured request, after
connection setup and any protocol warmup (such as the Masstree insert phase),
to the end of the measurement phase. total_requests counts the requests
completed inside that window, error replies included, which is what
throughput divides; requests
completed during the drain are excluded from it and from the bytes behind
throughput_mbps. Their latencies are recorded in the window’s last time
bucket. With stats.include_records = true, every record’s rate divides by
the part of its time bucket inside the measured window, so the first and last
buckets are not understated. All threads’ time buckets count from the
shared start.
The JSON experiment object may also contain
actual_load_loop_start_unix_us and actual_load_loop_end_unix_us: wall-clock
microseconds since the Unix epoch on the machine running xylem. They give the
earliest worker load-loop start and latest end, including gaps between worker
loops. Each worker’s sampling starts after the shared start wait, or after
preload when there is one, and ends before the drain; connection setup
inside the loop may be included when nothing preloads.
These readings do not imply synchronization between guest and host clocks.
Both fields are omitted if no interval was recorded or any worker’s samples
are missing, reversed, or above 2^53 - 1.
experiment.busy_poll_us is the profile’s busy-poll budget in microseconds,
or null when the worker threads did not busy-poll (see
busy polling).
Request accounting
Each requests object in JSON (global and per group) counts measurement
requests; warmup requests are excluded:
sent: requests sent.completed: requests whose response arrived, in the window or the drain, successful or an error reply.completed - errorsequals the latencysample_countunless the sampling policy isnoneor alimitedrate drops latencies.errors: completed requests whose response was an error reply. The console prints a warning when this is nonzero.errors_by_kind:errorsby kind, such as{"WRONGTYPE": 12, "OOM": 3}.timed_out: no response within the group’srequest_timeout(UDP groups, default 1 s; see UDP), or still pending when the drain timeout passed. Their latency is unknown, so they are not in the latency statistics (it is censored, not recorded as the timeout); the console prints a warning when this is nonzero.late_responses: responses that arrived after their request timed out. They are dropped, identified by request ID, and add no latency; their requests stay intimed_out. Only UDP groups time out requests, so this is zero for the other transports.failed: pending on a connection that closed or failed.late_sends: requests whose send lag exceeded 100 µs.unsent: sends a rate-driven schedule intended before the end of the measurement window that never went out, because the sender could not keep up. Counting walks each connection’s schedule from its next intended time to the end of the window, at most 10,000,000 requests per connection; Poisson schedules are sampled forward with the policy’s own generator. Connections that failed keep counting their schedule. A connection’s schedule starts once it can send after setup, so a connection still setting up at the end counts none, and the slots before a connection’s start are not unsent. Requests already queued but not yet written in full, behind a socket that took no more bytes, count as unsent too when the window ends or their connection fails. They stay unsent if they go out during the drain, and their responses are not counted.unsent_capped: whether that walk stopped at its cap on some connection, sounsentis a lower bound.
Under group dispatch a thread’s
connections share one schedule: an arrival that waits for an idle connection
counts in late_sends, and unsent counts the thread’s schedule, not each
connection’s. Each entry of traffic_groups reports its mode in dispatch:
"connection" or "group".
After a run, sent = completed + timed_out + failed.
Error replies
An error reply is a complete response that says its request failed: a Redis
error such as -WRONGTYPE, an HTTP status of 400 or above, a memcached
SERVER_ERROR line or non-zero binary status, a Masstree Retry result.
Each protocol page lists what it counts and how it names the kind. Nil
replies and misses are successful replies.
By default (on_error = "count" on the traffic group), an error reply
completes its request:
- It counts in
completed,errorsanderrors_by_kind, and towardtotal_requests, throughput and received bytes like any response. - Its latency goes to
error_latency, which has the same fields aslatency: the global summary uses the global sampling policy, and each group summary uses that group’s policy. It is not included inlatencyor the latency breakdown. Fast rejections would otherwise pull the percentiles down, solatencyand itssample_countcover successful responses only. - It is not fed back to an adaptive traffic policy, which would otherwise speed up on fast rejections.
- Warmup requests and connection setup are excluded, as from every count.
errors_by_kind names at most 32 kinds; error replies of later kinds count
under "other", and a kind is cut to 64 bytes. The bound holds per thread and
after merging threads, so with more than 32 kinds in a run a kind may be split
between its own entry and other.
"latency": { "mean_us": 52.7, "p50_us": 50.1, "p99_us": 96.3, "sample_count": 39000, ... },
"error_latency": { "mean_us": 41.2, "p50_us": 39.1, "p99_us": 88.0, "sample_count": 13000, ... },
"requests": {
"sent": 52000,
"completed": 52000,
"errors": 13000,
"errors_by_kind": { "WRONGTYPE": 13000 },
"timed_out": 0,
...
}
With on_error = "abort", the first error reply fails the run, warmup
included, with an error naming the traffic group, the connection and the
reply, and no results are written. Malformed responses and failed connection
setup (a rejected Redis AUTH, a failed Masstree handshake) fail the run
either way.
Send lag
With a rate-driven traffic policy, every request has an intended send time
(see traffic policies), and its
latency is measured from it: the send lag (actual minus intended send time,
measured on xylem’s cycle clock when the send completes) plus the service
latency (from the send, or its kernel TX timestamp, to the response). Each
send_lag object reports, in microseconds:
sample_count: open-loop requests sent.mean_us,max_us: exact.p99_us: from an HDR histogram with three significant digits.late_threshold_us: the threshold oflate_sends, 100 µs. An on-time send lags by a loop iteration and a send call, a few microseconds; a lag above 100 µs means the generator could not keep its schedule.
Closed-loop requests have no intended time: their values are null and their
latency is the service latency alone.
Either way a request counts as sent when the transport takes its last byte. The requests a worker’s send round queues on one connection go out together, in one write when the round ends (the round’s first connection’s as soon as the round moves on to another connection), and share that write’s timestamp. A connection whose socket takes only part of its bytes sends the rest once it becomes writable, and its later requests wait behind them.
Latency breakdown
Each latency_breakdown object in JSON (global and per group) says where the
latency of the completed measurement requests went. The send lag is not
repeated there; it stays in send_lag. It covers exactly the requests in
latency: successful responses, including those completed during the drain.
Warmup and setup requests are excluded, and so are
error replies, whose latency goes to error_latency alone,
so service_us.sample_count equals the latency sample_count when the
sampling policy records every latency.
"latency_breakdown": {
"clock": "kernel_software",
"kernel_split_count": 41230,
"kernel_split_missing": { "tx": 0, "rx": 0, "clock_mismatch": 0 },
"service_us": {
"sample_count": 41230, "mean_us": 14.1, "p50_us": 13.9,
"p99_us": 19.8, "p999_us": 31.2, "max_us": 212.4
},
"host_stack_us": {
"sample_count": 41230, "mean_us": 9.8, "p50_us": 9.6,
"p99_us": 14.3, "p999_us": 22.0, "max_us": 190.2
},
"network_server_us": {
"sample_count": 41230, "mean_us": 14.1, "p50_us": 13.9,
"p99_us": 19.8, "p999_us": 31.2, "max_us": 212.4
},
"user_round_trip_us": {
"sample_count": 41230, "mean_us": 23.9, "p50_us": 23.4,
"p99_us": 31.6, "p999_us": 47.9, "max_us": 398.1
}
}
The parts of one request are:
service_us: actual receive minus actual send, in the clock the latency uses. A request’s latency is its send lag plus this. Always present.network_server_us: present when the send and the receive both carry a kernel timestamp from the same clock, which needs kernel or NIC timestamps (see timestamps). It is the kernel round trip: the response’s kernel RX timestamp minus the request’s kernel TX timestamp. With kernel software timestamps, that is from the request leaving the kernel’s stack for the driver to the response entering it, so it covers the NICs, the network and the server; with NIC timestamps, from the request leaving the client NIC to the response arriving at it. Such a request’s latency uses this round trip, so itsservice_usequals it.host_stack_us: for the same requests, the user-space round trip (cycles read when the send call and the receive call returned) minus the kernel round trip, or zero if that is negative. That is the time from the response’s kernel RX timestamp to the receive call’s return (the client’s receive stack, wakeup and syscall) minus the time from the request’s kernel TX timestamp to the send call’s return. A kernel software TX timestamp is taken inside the send call, so this subtracts the end of that call; a NIC usually transmits after the call returned, so with NIC timestamps this adds the send path through the stack, driver and NIC queue.user_round_trip_us: for the same requests, the user-space round trip itself: cycles from the send call’s return to the receive call’s return. Per request it isnetwork_server_us + host_stack_us, except wherehost_stack_ussaturated at zero, where it is less (the kernel round trip was the longer). Its percentiles are those of that sum per request, which the two parts’ percentiles cannot give.
Each part’s two terms are measured in one clock; xylem subtracts durations,
never times from different clocks. host_stack_us, network_server_us and
user_round_trip_us are null when no request had a kernel split. Requests
whose TX or RX timestamp did not arrive, or came from different clocks, count
in service_us alone.
clock: the clock of the service latencies:user_space(no kernel split),kernel_software,nic_hardware,nic_calibrated, ormixedwhen the scope’s requests used different ones.nullwhen no request completed.nic_calibratedcomes fromntcpgroups withtimestamps = "nic": the RX timestamp is the NIC’s, converted to xylem’s clock, and the TX timestamp is the time ntcp queued the request’s last byte to the NIC, before the NIC sends it.network_server_usthen includes the NIC’s transmit delay, andhost_stack_usis the user-space stack’s own time.kernel_split_count: requests with a kernel split. Belowservice_us.sample_count, some requests lacked a usable kernel timestamp.kernel_split_missing: the requests without a kernel split, by what they lacked:tx, no kernel TX timestamp (none arrived on the socket’s error queue withinexperiment.tx_timestamp_timeoutof the response; see timestamps);rx, no kernel RX timestamp on the response;clock_mismatch, both, from different clocks. A request with neither timestamp counts in bothtxandrx. Present only for traffic groups withtimestamps = "kernel"or{ hardware = ... }, and in the global breakdown when any group has them. A group with these timestamps that completed requests but split none makes the run invalid (thekernel_splitvalidity check); one that split only some logs a warning with these counts.
Every part reports sample_count, an exact mean_us and max_us, and
p50_us, p99_us and p999_us from an HDR histogram with three significant
digits; the values are null without samples. Each part’s percentiles are
taken over that part alone, so they do not add up: the p99 of
host_stack_us plus the p99 of network_server_us is not the p99 of the
latency, and the slowest requests of one part need not be the slowest of
another. For the percentiles of the host stack and the network and server
together, read user_round_trip_us, which records each split request’s sum
(see above for where host_stack_us saturated).
The console prints the same parts in one row each, and the HTML report in a
table per scope; both add the kernel_split_missing counts when present.
NIC clock calibration
Runs with timestamps = "nic" add a top-level nic_clock_calibration list,
one entry per worker thread with such groups, saying how well the thread’s
NIC clock was converted to xylem’s clock:
"nic_clock_calibration": [
{
"thread_id": 2,
"ns_per_tick": 12.800118,
"residual_rms_ns": 131.2,
"max_residual_ns": 402.7,
"inliers": 31,
"outliers": 1,
"rejected_samples": 0,
"converted_rx_stamps": 351204,
"unconverted_rx_stamps": 0
}
]
ns_per_tick,residual_rms_ns,inliers,outliers: the last fit, over the last 32 paired clock readings (about 3 s).residual_rms_nsis the typical error of a converted RX timestamp; null fields mean no fit existed.max_residual_ns: the largest residual of any fit during the run.rejected_samples: readings refused because a clock did not move forward.converted_rx_stamps,unconverted_rx_stamps: receives whose RX hardware timestamp was converted, and receives without one (or before the first fit), whose requests have no kernel split.
Worker threads
The top-level worker_threads list has one entry per worker thread, by
thread ID, with the NUMA memory policy the thread had before it built its
worker:
"worker_threads": [
{ "thread_id": 15, "memory_policy": "bind", "memory_nodes": [1] }
]
memory_policy:"bind"with NUMA memory binding;"none"for the kernel’s default, which places memory on the node of the CPU that first touches it; otherwise the policy the process was started with, such as numactl’s ("preferred","interleave","local","preferred_many"or"weighted_interleave").memory_nodes: the nodes the policy allocates from, ascending; empty for"none"and"local".
Results written before this field existed read as an empty list.
Latency fields
Each latency object in JSON (global and per group) holds these fields;
durations are in microseconds:
p50_us…p99999_us: percentiles from the applicable sampling policy.mean_us,min_us,max_us: exact, from every recorded latency.std_dev_us: sample standard deviation.confidence_interval_us: half-width of the 95% confidence interval of the mean,1.96 * std_dev / sqrt(sample_count).sample_count: number of latencies recorded, after anylimitedrate.latencyrecords successful responses only;error_latency, with the same fields, records error replies.percentile_sample_count: samples retained for percentiles by a reservoir, or observations represented by a histogram or sketch, after aggregation. Absent in legacy JSON, where the count is unknown.clamped_samples: present only for an HDR histogram withmax_value_us; the number of latencies above that bound, recorded as the bound.
Console and HTML latency and error-latency summaries show both the recorded
sample count and the percentile sample count. A zero percentile count means no
observations were retained or represented; n/a means the count is unknown in
legacy data. A zero-capacity reservoir can therefore show a mean and recorded
samples while its percentile count is zero and its percentiles are n/a.
Without recorded latencies (for example with type = "none"), newly generated
JSON has null for min_us and max_us; std_dev_us and
confidence_interval_us are null with fewer than two latencies. Legacy JSON
can contain numeric placeholders in those fields. Some older files report a
zero sample_count even when observations existed, so that count is not always
trustworthy. Console and HTML conservatively display values as n/a when the
count does not establish availability; the stored JSON values remain unchanged.
JSON uses numeric zero placeholders for mean_us without recorded latencies
and for percentiles when their estimator has no samples. See
threshold availability for how these
values are checked.
For raw per-time-bucket, per-connection records in JSON, use:
[stats]
include_records = true
bucket_duration = "1s"
Records cost memory for every bucket of every connection for the whole run;
with the default HDR histogram an entry keeps only the histogram bins it
recorded (60 s at 1000 connections and 4000 req/s: about 90 MB). Without
records, a group whose sampling_policy is hdr-histogram, unlimited or
none keeps one total per worker thread instead, so its memory does not grow
with the number of buckets or connections (unlimited still keeps every
latency). Other policies keep an entry per bucket
and connection either way: their merged estimate depends on how the latencies
were split.
Each record names its connection by group_id, thread_id and
connection_id. Connection IDs restart at 0 on every worker thread, so
thread_id (the thread’s entry in threads) is needed to tell connections
apart.
Whatever include_records is, each entry of traffic_groups lists its
connections in connection_addrs, by the same thread_id and
connection_id, with the local socket address each had once open:
"connection_addrs": [
{ "thread_id": 0, "connection_id": 0, "local_addr": "10.0.0.2:40112" }
]
local_addr is null on Unix sockets. A UDP socket is not connected, so its
IP is the unspecified address it is bound to, 0.0.0.0 or ::; its port is
the source port the server sees.
Each record covers one (bucket, group_id, thread_id, connection_id) and has
its own latency_sample_count: the number of successful latencies recorded for
that tuple after any limited rate. Its percentile_sample_count is the number
retained by that record’s reservoir, or represented by its histogram or sketch.
A group or global reservoir aggregates separately and has its own capacity, so
its retained count need not equal the sum of record counts. The global policy
can also differ from group policies. These counts can differ from request_count,
which includes error replies and excludes drain completions. A zero-capacity
reservoir, for example, can record latencies for its mean while retaining none
for percentiles. The numeric latency_mean_us and
latency_p50_us/latency_p99_us/latency_p999_us fields use zero placeholders
when their values are unavailable; use the corresponding count to distinguish a
placeholder from an observed zero. The console sample-record preview shows
p99=n/a when either count is zero or unknown. Both count fields are absent in
legacy JSON, where their values are unknown and the preview also shows n/a.
HTML uses Chart.js (loaded from a CDN) and the light theme. Only
output.html.library = "chartjs" and output.html.theme = "light" are supported.
output.real_time must remain false; the feature is not implemented by the CLI
and validation rejects it.
The obsolete detailed-json format has been replaced by json.
Request CSV dumps are configured separately through [request_dump]; see the
configuration schema reference.
Thresholds and Validity
A run can gate CI or a regression benchmark. After the run, xylem checks two things against the final results:
- Validity: did the run apply the load it was configured with? If not, the run is invalid: its statistics describe some other load.
- Thresholds: did the metrics stay within the limits in
[thresholds]?
The outcome is the run’s verdict: in the results file, the console summary, the HTML report, and the exit status.
[experiment]
name = "api-regression"
duration = "30s"
[[traffic_groups]]
name = "latency-agent"
protocol = "xylem-echo"
target = "127.0.0.1:9999"
threads = [0]
connections_per_thread = 4
traffic_policy = { type = "poisson", rate = 20000.0 }
[[traffic_groups]]
name = "load"
protocol = "xylem-echo"
target = "127.0.0.1:9999"
threads = [1, 2]
connections_per_thread = 16
max_pending_per_connection = 8
traffic_policy = { type = "fixed-rate", rate = 80000.0 }
[output]
format = "json"
file = "results.json"
[thresholds]
"latency" = ["p99 < 250us", "p99.9 < 1ms"] # global
"latency{group=latency-agent}" = ["p50 < 80us"] # one traffic group
"send_lag" = ["p99 < 20us"]
"requests.timed_out" = ["rate < 0.001"] # fraction of requests.sent
"requests.errors" = ["rate < 0.01"] # error replies
"requests.failed" = ["== 0"]
"throughput" = ["> 90000"]
[validity]
max_unsent_ratio = 0.001 # the defaults
max_late_send_ratio = 0.01
Exit status
| Status | Verdict | Meaning |
|---|---|---|
| 0 | pass | Every validity check and threshold passed, or none applied (no [thresholds], closed-loop groups only) |
| 1 | Error: the profile is invalid (including any threshold), the run failed, or a result file could not be written | |
| 2 | thresholds_failed | The run is valid and a threshold failed |
| 3 | invalid_run | A validity check failed. Takes precedence over 2: a threshold of an invalid run says nothing about the configured load |
Every result file is written before xylem exits with 2 or 3, so a CI job can keep the results of a failed run as artifacts.
Thresholds
Each key of [thresholds] names a metric, optionally filtered to a traffic
group; its value is a list of expressions, each a separate threshold. Every
threshold is evaluated once, against the final results.
Metrics
A metric is the path of a field in a stats object of the
JSON results: global by default, or the stats of
the traffic group named by {group=name}. The group’s name must be unique
among the traffic groups; quotes around it are optional
('latency{group="api"}'). Any numeric field there is a metric, including
fields added in later versions:
- Summaries are objects of durations in microseconds:
latency,error_latency(the latencies of error replies),send_lag, and the parts of the latency breakdown,latency_breakdown.service_us,latency_breakdown.host_stack_us,latency_breakdown.network_server_usandlatency_breakdown.user_round_trip_us. An expression on a summary names an aggregation, which picks one of its_usfields. - Single values are the other numbers:
total_requests,throughput_rps(also writtenthroughput),throughput_mbps,requests.sent,requests.completed,requests.errors,requests.timed_out,requests.failed,requests.late_responses,requests.late_sends,requests.unsent,latency.sample_count,latency.percentile_sample_count,error_latency.sample_count,error_latency.percentile_sample_count,send_lag.sample_count,latency_breakdown.kernel_split_count, thesample_countof each breakdown part, and any_usfield written in full, such aslatency.p99_us.
An unknown metric is an error that lists the available ones.
requests.errors_by_kind is not a metric. Its keys are the error kinds the
run meets (WRONGTYPE, 404, …), with at most 32 per run and the rest
under other, so a key cannot be checked when the profile loads, and a kind
the run never meets would have no value rather than zero. A threshold on it,
or on one of its kinds, is rejected at load; put the limit on
requests.errors, which counts every error reply, and read the kinds from
the results.
[thresholds]
"requests.errors" = ["rate < 0.01"] # error replies / requests.sent
"error_latency" = ["p99 < 5ms"]
"latency_breakdown.network_server_us" = ["p99 < 100us"] # needs kernel or NIC timestamps
"latency_breakdown.user_round_trip_us" = ["p99 < 150us"] # host stack + network and server
"latency_breakdown.kernel_split_count" = ["rate > 0.99"] # the split covers the requests
Expressions
An expression is [aggregation] operator value:
| Aggregation | Applies to | Compares |
|---|---|---|
p50, p95, p99, p99.9, p99.99, p99.999 | summaries | the percentile field: p99.9 reads p999_us (p999 works too) |
mean, min, max, std_dev, confidence_interval | summaries | mean_us, min_us, … |
A latency breakdown part holds mean, p50, p99, p99.9 and max only.
| none | single values | the value |
| rate | counts | the count divided by requests.sent of the same stats |
Operators are <, <=, >, >=, == and !=. A duration takes a unit:
ns, us (or µs), ms or s, as in 250us or 1.5ms. Counts, rates
and other values are plain numbers: a rate is a fraction, 0.001, not
0.1%. A summary offers only the percentiles its fields hold; p90 is an
error, as are an unknown aggregation, a missing or extra unit, and a
malformed expression or key.
Every threshold is checked when the profile loads, before any connection
opens: one error lists every invalid threshold, reported together with the
profile’s other errors, and xylem exits with 1. The keys of [thresholds]
are metric names, so the profile’s unknown-key check
accepts any key there and leaves it to this check; [validity] is a table
of fixed keys, and an unknown key in it is an error like anywhere else.
Values the run lacks
A threshold fails when the run has no value for it, and its observed is
null:
- a
nullfield, such assend_lagof a closed loop,latency.min_uswhen no latency was recorded (see latency fields), orlatency_breakdown.host_stack_us,network_server_usanduser_round_trip_uswhen no request had a kernel split (user-space timestamps, or a transport without kernel timestamps); - a duration field of
latencyorerror_latencywhen itssample_countis zero; std_dev_usorconfidence_interval_usof either summary when itssample_countis less than two, even if legacy JSON contains a number;- a percentile of either summary when
percentile_sample_countis missing,nullor zero, even ifsample_countis positive; - a
ratewhen nothing was sent; - a traffic group that recorded no requests, which is not in the results.
These rules apply to summary aggregations and full field paths. JSON uses a
numeric zero placeholder for the mean when no latency was recorded, and for
percentiles when the estimator has no samples; those placeholders do not pass
thresholds. Older files can have a zero sample count even when observations
existed; without a trustworthy positive count, thresholds conservatively treat
the values as unavailable and leave the JSON unchanged. For example, an
error_latency ceiling fails when the run has no error replies. A genuine
measured zero can pass when the required counts are available, and the counts
themselves can be checked even when zero.
--set can set a threshold whose key has no dot, such as
--set 'thresholds.latency=["p99 < 1ms"]'. A dot in the key, as in
requests.unsent, makes --set build nested tables, which do not load; put
such thresholds in the profile.
Validity
A rate-driven traffic policy (every policy except closed-loop) gives each
request an intended send time. Two checks compare each rate-driven traffic
group’s request accounting with that
schedule, and a third checks that a group with kernel or hardware
timestamps measured with them:
| Check | Observed | Default limit |
|---|---|---|
unsent | unsent / (sent + unsent): intended sends that never went out | max_unsent_ratio = 0.001 |
late_sends | late_sends / sent: sends more than 100 µs behind their intended time | max_late_send_ratio = 0.01 |
kernel_split | kernel_split_count / service_us.sample_count of the latency breakdown: completed requests with a kernel split | must be above 0 (fixed) |
A closed-loop group is exempt from unsent and late_sends: it sends
whenever a response frees its pipeline, so it has no schedule to fall behind.
kernel_split applies to every group with timestamps = "kernel" or
{ hardware = ... } that completed a request, closed loops included. It
fails when none of the group’s completed requests had a kernel split: the
latencies were all measured in user-space cycles, not with the configured
timestamps. Its reason gives the group’s kernel_split_missing counts and
the likely fix. A group that split some but not all of its requests passes,
and xylem logs a warning with the counts (also when the check is skipped).
[validity]
enabled = true # false: no checks, the run is never invalid
max_unsent_ratio = 0.001
max_late_send_ratio = 0.01
skip = ["late_sends"] # leave out single checks: "unsent", "late_sends", "kernel_split"
What an invalid run tells you
An invalid run did not apply the configured load. When intended sends never went out, the run offered less than the configured rate, and the requests that would have waited longest are missing from the latency statistics. When sends went out late, their latencies (measured from the intended send time) include that lag, so the generator shaped part of the tail.
It does not tell you why. Both checks fail when the generator is too slow
(too few threads, a busy or preempted CPU) and when the server is: a slow
server keeps each connection’s max_pending_per_connection requests
pending, so the sender waits for a free slot. Look at send_lag, the
generator’s CPU, and the server’s latency; more connections or a deeper
pipeline help when the server has capacity left.
It does not say the recorded latencies are wrong: they are correct for the requests that were sent. To measure a server beyond its capacity on purpose, which leaves requests unsent by design, skip the checks or use a closed loop. A valid run does not say the server behaved well either: timeouts, failures and latency are what thresholds are for.
Why these defaults
unsentat most 0.1%, not zero: the end of the window can cut off an intended send that was due in its last moments, about one per connection in a healthy run (a 2 s run at 2,000 requests per second over four connections showed 0 to 2). 0.1% absorbs that in runs with at least 1,000 intended sends per connection. If the missing requests were the slowest, 0.1% of them shifts a percentile by at most 0.1 points: the reported p99.9 is at worst the true p99.8. Raise the limit for shorter or slower runs.late_sendsat most 1%: an on-time send lags by a few microseconds, and 100 µs means the sender missed its schedule. 1% tolerates an occasional preemption of the sender, but not a schedule kept late throughout.
Results
The JSON results record the verdict and every check, thresholds in key order:
{
"verdict": "invalid_run",
"thresholds": [
{
"metric": "latency",
"group": null,
"expression": "p99 < 1ms",
"field": "latency.p99_us",
"observed": 2325741.567,
"ok": false
}
],
"validity": [
{
"check": "unsent",
"group": "echo",
"observed": 0.7882986861688563,
"limit": 0.001,
"ok": false,
"reason": "472980 of 600001 intended sends never went out (78.83%, limit 0.10%): the pipelines were full or the generator fell behind, so the configured rate was not applied"
},
{
"check": "late_sends",
"group": "echo",
"observed": 0.9999921272860394,
"limit": 0.01,
"ok": false,
"reason": "127020 of 127021 sends lagged their intended time by more than 100 µs (100.00%, limit 1.00%): the pipelines were full or the generator fell behind its schedule"
}
]
}
fieldis the stats field compared; a rate shows its division, as inrequests.timed_out / requests.sent.observedis in the unit of that field (microseconds for durations), a fraction for rates and validity checks, ornullwhen the run lacks it.limitis the largest fraction that passes, but forkernel_split: 0, which the observed fraction must exceed (the console printslimit > 0.00%).groupisnullfor the global stats.reasonis present only for a failed validity check.
The console summary ends with the same checks:
----------------------------------------------------------------------
VERDICT: PASS
----------------------------------------------------------------------
Validity:
ok unsent{group=echo}: 0.00% (limit 0.10%)
ok late_sends{group=echo}: 0.00% (limit 1.00%)
Thresholds:
ok latency: p99 < 1ms (observed 44.90 μs)
ok latency: p99.9 < 5ms (observed 87.36 μs)
ok latency{group=echo}: p50 < 200us (observed 23.46 μs)
ok requests.timed_out: rate < 0.001 (observed 0.000000)
ok send_lag: p99 < 50us (observed 14.26 μs)
ok throughput: > 1900 (observed 2000.01)
The HTML report shows them in a Verdict section above the statistics.
Architecture Overview
Xylem is designed with a modular, layered architecture that separates concerns and enables extensibility.
High-Level Architecture
┌─────────────────────────────────────────┐
│ CLI Interface │
│ (xylem-cli) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Core Engine │
│ (xylem-core) │
│ - Workload Management │
│ - Statistics Collection │
│ - Threading & Event Loop │
└─────────────────────────────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ Protocols - X │ │ Transports - Y │
│(xylem-protocols)│ │ (xylem-transport)│
│ - Redis │ │ - TCP │
│ - HTTP │ │ - UDP │
│ - Memcached │ │ - Unix Socket │
│ - Masstree │ │ │
│ - xylem-echo │ │ │
└─────────────────┘ └──────────────────┘
Design Principles
Xylem’s architecture follows several core design principles. The system employs a modular design where each component has a well-defined responsibility: the CLI layer handles user interaction and TOML configuration parsing, the core engine orchestrates workload generation and statistics collection, protocol implementations handle message encoding/decoding, and the transport layer manages network communication.
The architecture enables composability through clean interfaces. Protocols and transports can be combined freely - Redis can run over TCP, UDP, or Unix domain sockets; HTTP over TCP or Unix sockets; and Memcached over any supported transport. This flexibility allows Xylem to adapt to different testing scenarios without code modifications.
Key Components
Core Engine
The core engine handles workload generation, connection management, statistics collection, and event loop orchestration.
Protocol Layer
Implements application protocols through request encoding, response parsing, and protocol state management.
Transport Layer
Handles network communication including connection establishment, data transmission, and error handling.
Data Flow
The system processes requests through a defined pipeline. Users provide workload configuration via TOML profile files. The core engine reads the configuration during initialization to instantiate the appropriate protocols and transports. During execution, the event loop generates requests according to the configured pattern and collects responses as they arrive. Statistics are gathered throughout the run, tracking latency, throughput, and error rates. Upon completion, results are formatted according to the output configuration and presented to the user.
See Also
Protocol Layer
The protocol layer (xylem-protocols) implements application-level protocols for RPC workload generation and measurement.
Protocol Trait
All protocol implementations conform to the Protocol trait, defined in
xylem-common/src/protocol.rs
and re-exported by xylem-protocols and xylem-core:
#![allow(unused)]
fn main() {
pub trait Protocol: Send {
type RequestId: Eq + Hash + Clone + Copy + Debug;
fn next_request(&mut self, conn_id: usize) -> Request<Self::RequestId>;
fn parse_response<'a>(
&mut self,
conn_id: usize,
data: &'a [u8],
) -> anyhow::Result<Parsed<'a, Self::RequestId>>;
fn can_send(&self, _conn_id: usize) -> bool {
true
}
fn setup_pending(&self, _conn_id: usize) -> bool {
false
}
fn preload_pending(&self, _conn_id: usize) -> bool {
false
}
fn connection_roles(&self, load: usize) -> Vec<ConnectionRole> {
vec![ConnectionRole::Load; load]
}
fn bind_connections(&mut self, _conn_ids: &[usize]) {}
fn drain_outbox(&mut self, _conn_id: usize, _outbox: &mut Outbox) {}
fn name(&self) -> &'static str;
fn reset(&mut self);
}
}
next_requestbuilds the next request for a connection from the protocol’s own workload state (command selection, keys, value sizes, insert phase). The returnedRequestcarries the bytes, the request ID, and metadata that marks warm-up requests, whose latency is not recorded.parse_responsereturnsParsed::Complete { consumed, id, error }for a complete response, orParsed::Incomplete.erroris set for an error reply (a Redis error, an HTTP 4xx or 5xx, …): anErrorReplywith akindby which it is counted and amessage, both borrowed fromdataor static, so reporting one allocates nothing. An error reply completes its request;Erris for bytes that cannot be framed and for failed connection setup, and fails the run.Parsed::Absorbed(n)consumes bytes that complete no request, such as one datagram of a multi-datagram UDP response, an NVMe/TCP R2T, or the leading part of a response longer than the receive buffer; they count toward the next completed response’s bytes.can_sendlets a protocol hold back requests on a connection, for example until the Masstree handshake completes. The worker asks when it schedules the connection, so once true it must stay true until that connection’s next request.setup_pendingreports a connection that is still in connection setup (Redis AUTH, SELECT and HELLO, the Masstree handshake). Its requests go out as soon ascan_sendallows, off the connection’s intended send schedule, which starts once setup is done. A connection error while it is true, or setup still pending at the end of the run, fails the run naming the connection; after setup, a connection error only closes the connection and counts its pending requests asfailed.preload_pendingreports a connection whose next request, after setup, is preload: warmup that fills the server before measurement, such as the memcached, Redis and Masstree insert phase or NVMe/TCP verify mode’s prefill. It may turn false on another connection’s request, so the connections of a group can share one insert phase. If any connection of any thread reports it at the start, the worker preloads first: it sends setup and preload requests off every schedule and holds the others; once a thread has no setup, preload or reply left, it waits for the other threads, and the measured run starts at one time after the last finished. An error reply, a connection error or a timed-out request during preload fails the run.connection_roleslets a session span connections. For a group withloadconnections per thread it returns the connections to open, in order: exactlyloadLoadconnections, which carry the traffic policy and statistics, and anyControlconnections the protocol needs for itself, such as an NVMe/TCP admin queue per controller. A control connection has no policy, takes no group-dispatched arrivals, and may send only setup requests.bind_connectionsreceives the opened IDs in the same order before the run.drain_outboxruns after each read the worker parsed on a connection. The protocol puts inOutbox::databytes to send on that connection that are no requests (an NVMe/TCP H2CData PDU answering an R2T, an HTTP/2 SETTINGS acknowledgement); the worker sends them before the connection’s next request, counts them as sent bytes, and gives them no latency. Bytes the socket does not take at once wait in the connection’s send queue until it is writable, ahead of later requests, while the worker keeps reading. InOutbox::wakeit names connections that data on this one unblocked, such as I/O queues waiting for their admin queue; the worker reschedules just those.namereturns the protocol name, andresetclears per-connection state.
The core engine decides when to send; the protocol decides what to send. The
Redis, Memcached, HTTP, HTTP/2, gRPC, Masstree, DNS, NVMe/TCP and ClickHouse
protocols have a from_config constructor that builds them from their
protocol_config section.
Protocol Design
Protocol implementations are designed to minimize state and memory overhead. Each implementation encodes requests in the appropriate wire format and parses responses into a form suitable for latency measurement. The RequestId mechanism enables request-response correlation, which is required for accurate latency measurement in scenarios involving pipelining or out-of-order responses.
Supported Protocols
The following protocol implementations are available:
- Redis - RESP (Redis Serialization Protocol) for key-value operations
- HTTP - HTTP/1.1 for web service testing
- HTTP/2 and gRPC - Cleartext HTTP/2 with concurrent streams, flow control and HPACK, and gRPC unary calls on top of it
- Memcached - Binary and text protocol variants for cache testing
- Masstree - MessagePack-based protocol for the Masstree key-value store
- DNS - Standard queries with one question, length-prefixed on byte streams and bare in UDP datagrams
- NVMe/TCP - NVM reads and writes on the I/O queues of NVMe over Fabrics controllers
- ClickHouse - SQL queries over the native TCP protocol, one at a time per connection, with results streamed by column type without decoding
- Xylem Echo - Echo protocol for testing xylem itself
Detailed documentation for each protocol is available in the Protocols section of the User Guide.
Request-Response Correlation
The protocol layer maintains state necessary for correlating responses with their originating requests. This is required for protocols supporting pipelining or scenarios where multiple requests are in flight concurrently. Each protocol defines an appropriate RequestId type for its correlation semantics.
See Also
Transport Layer
The transport layer (xylem-transport) provides network I/O for Xylem: TCP, UDP and Unix domain sockets, driven through one API for groups of connections.
Connection Groups
A worker thread owns one ConnectionGroup, created by a TransportFactory (TcpTransportFactory, UdpTransportFactory or UnixTransportFactory). All I/O goes through the group by connection ID:
add_connection(target)opens a connection and returns its ID (add_connection_pathfor Unix sockets).send(conn, data)writes every byte, waiting while the socket is full, and returns aSendReceipt: the send timestamp and, when TX timestamps are on, the TX range of the send.try_send(conn, data)writes what the socket takes now, possibly nothing, and returns how many bytes with theirSendReceipt. The worker sends this way: it keeps the rest queued and setsset_write_interest(conn, true)until the connection can take more.poll(timeout, &mut ready)waits once for all connections and fillsreadywith readable connection IDs, and those with write interest that can take more bytes (level-triggered).recv(conn, buf)reads what is available and returns aRecvOutcome:Datawith its receive timestamp,WouldBlockorEof.poll_tx_timestamps(&mut out)collects kernel TX timestamps that arrived since the last call.
Each group has one readiness multiplexer, fixed at compile time: epoll on Linux, mio (kqueue) elsewhere. So one syscall checks every connection of a thread. Connection pooling, pipelining and request tracking live in xylem-core (ConnectionPool), on top of this API. Groups need not be Send, so a user-space network stack can implement the trait too.
See the crate documentation for the full API.
Timestamps
Every timestamp holds the CPU cycle counter (RDTSC on x86_64) read when the send or receive call completed. By default these user-space timestamps are all Xylem uses.
On Linux, TCP and UDP groups can also use kernel timestamps (SO_TIMESTAMPING), configured through TimestampConfig:
- Hardware timestamps from the NIC, when an interface is configured and has hardware timestamping switched on (checked with
SIOCGHWTSTAMP). Withrequire_hardware, a group that cannot get them fails instead of falling back. - Kernel software timestamps, when requested explicitly.
A profile chooses the source per traffic group with timestamps; { hardware = "..." } always requires hardware timestamps.
Each group logs the source in effect once, at info level. A latency uses kernel timestamps only when the send and the receive both have one from the same clock (the system clock for software stamps, the NIC’s clock for hardware stamps). Otherwise it uses the cycle counts of both events. The cycles of both events are kept either way, so the latency breakdown can subtract the kernel round trip from the user-space one.
TX timestamps arrive later than the send that caused them, and are matched to sends by a per-connection counter: bytes for TCP and datagrams for UDP. A TCP stamp covers every send up to the byte it reports. A UDP stamp covers exactly one datagram. The correlation contract is documented in the crate.
Supported Transports
- TCP - Connection-oriented byte streams using TCP sockets. Every
connection sets
TCP_NODELAY, so Nagle’s algorithm never holds back a small or pipelined request and inflates its latency. - UDP - Connectionless datagram communication
- Unix Domain Sockets - Local inter-process communication
- ntcp - User-space TCP (ntcp), one
stack per worker thread, over a TUN device, a DPDK port or AF_XDP sockets
(Linux,
ntcp,ntcp-dpdkandntcp-af-xdpbuild features). With DPDK, NIC RX timestamps are converted to xylem’s clock by a per-thread calibration, and TX timestamps are the time the stack queued a request to the NIC.
Detailed documentation for each transport is available in the Transports section of the User Guide.
See Also
Configuration Schema
Xylem uses TOML configuration files to define experiments. This reference documents the complete schema for experiment profiles.
Overview
A complete Xylem configuration file contains the following sections:
[experiment] # Experiment metadata and duration
[[traffic_groups]] # One or more traffic generation groups with protocol_config
[output] # Output format and destination
[stats] # Optional statistics settings
[request_dump] # Optional request CSV dump settings
[thresholds] # Optional pass/fail limits on the results
[validity] # Optional checks that the run applied its load
Every section, and every table inside one, rejects unknown keys, except that
the keys of [thresholds] are metric names; see
unknown and removed keys.
Experiment Section
The [experiment] section defines metadata and experiment-wide settings.
[experiment]
name = "redis-bench"
description = "Redis benchmark with latency/throughput agent separation"
duration = "30s"
seed = 42
Fields
name(string, required): Name of the experimentdescription(string, optional): Description of the experimentduration(string, required): Duration in format “Ns”, “Nm”, “Nh” (seconds, minutes, hours)seed(integer, optional): Random seed for reproducibility. Each traffic group’s protocol on each thread draws its keys, values and sizes from its own seed derived from this one, so threads do not repeat each other’s keys, and each connection of apoissongroup draws its arrivals from its own derived seed. Without a seed, both come from OS entropy. Earlier versions gave every thread this seed itself, so a given seed now generates different keys than it did there.drain_timeout(string, default"1s"): after the measurement window, how long to wait for responses that are still pending. Nothing is sent during the drain. Requests still pending when it ends count astimed_out; see run phases.setup_timeout(string, default"10s", more than zero): how long a connection may take to set up, counted from the start of its connect, so it includes the connect and the wait for the other threads to open theirs. A connection whose protocol setup (such as Redis AUTH, the ClickHouse Hello or the HTTP/2 preface) has not finished by then fails the run. It also bounds preload (such as aninsert_phase): a thread that receives nothing for this long while it preloads fails the run, however long the whole preload takes; see run phases.tx_timestamp_timeout(string, default"10ms", more than zero): withtimestamps = "kernel"or{ hardware = ... }, how long the latency sample of a response that arrived before its request’s TX timestamp waits for the stamp, counted from the receive. The request completes at once; a sample whose stamp did not arrive by then is measured in cycles and counts inkernel_split_missing.tx; see timestamps.busy_poll_us(integer, optional, at least 1): turn on busy polling with this budget in microseconds; see busy polling. Off when unset.numa_membind(boolean, defaulttrue): bind each worker thread’s memory to the NUMA node of the CPU it is pinned to; see NUMA memory binding.
Busy polling
By default a worker thread that has nothing to send waits in its transport’s
poll (epoll_wait for the kernel transports) until a connection is ready or
its next deadline comes, so the kernel has to wake it for each response.
With busy_poll_us = N, for N microseconds after each send and after each
poll that finds a ready connection, the thread polls with a zero timeout
instead, and sees a response without that wakeup. Once N microseconds pass
with neither, it waits in its poll as without busy polling, until the next
send or event. The budget counts from the start of the run too.
[experiment]
name = "nvme-qd1"
duration = "30s"
busy_poll_us = 1000
CPU cost: every worker thread keeps its core at 100% while it spins. With
a budget longer than the gaps between a thread’s sends and responses, which
is the usual case under load, that is the whole run. A smaller budget bounds
the burn when a thread is idle, such as between widely spaced open-loop
sends; a request whose response takes longer than the budget waits in a
poll. Pin each thread to a core of its own (threads) and keep that core
free of other work.
Busy polling helps where the wakeup is a large part of the latency: one
request in flight on a fast target, such as NVMe/TCP at queue depth 1. It
works the same for every transport and protocol, and changes neither where
timestamps are taken nor when sends, timeouts, the end of the window and the
drain happen. ntcp’s DPDK and AF_XDP backends already spin in their polls,
so it changes nothing there; with TUN, ntcp drives its stack on each poll
instead of sleeping on the device. The JSON results record the budget as
experiment.busy_poll_us, null without busy polling.
NUMA memory binding
Each worker thread is pinned to the CPU of its thread ID (threads). On a
host with more than one NUMA node, xylem also binds each worker thread’s
memory to its CPU’s node (set_mempolicy(MPOL_BIND)), from the thread’s
first allocation on: its stack, its malloc arena, and everything its worker
builds, such as connections, buffers and statistics. The kernel’s NUMA
balancing then neither moves that memory nor pauses the thread about once a
second to scan it for misplaced pages, which otherwise delays sends by a few
hundred microseconds.
[experiment]
name = "no-binding"
duration = "30s"
numa_membind = false
- Memory the main thread allocated before the worker threads started, such as the parsed profile, stays where it is.
- The binding replaces any memory policy the process started with, such as
numactl --membind’s, for the worker threads. Setnuma_membind = falseto keep it. - A bound thread allocates only from its node. If that node runs out of memory, the kernel’s OOM killer acts rather than take memory from another node.
- On a single-node host, or when the threads are not pinned, xylem logs that
it binds nothing and runs as with
numa_membind = false. - If the kernel refuses the binding (a container or a seccomp filter may),
the run fails before it starts, with the errno; set
numa_membind = falseto run without it. Xylem never changes host settings such askernel.numa_balancing.
The JSON results record each worker thread’s memory policy as the thread reported it before it built its worker; see worker threads.
Transport and Target
Each traffic group specifies its own transport ("tcp", "udp", "unix", or
"ntcp" in builds with the ntcp feature)
and target. Transport defaults to "tcp"; there is no global [target] section.
Groups sharing a thread must use the same transport. TCP and UDP targets must be
numeric socket addresses, such as "127.0.0.1:6379" or "[::1]:6379"; hostname
resolution is not supported. Unix targets are filesystem paths.
Traffic Groups
Traffic groups define how workload is distributed across threads and connections. Each group has its own protocol, target, and configuration. You can define multiple [[traffic_groups]] sections.
[[traffic_groups]]
name = "main"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0, 1, 2, 3]
connections_per_thread = 25
max_pending_per_connection = 10
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "fixed-rate"
rate = 100.0
[traffic_groups.sampling_policy]
type = "unlimited"
Traffic Group Fields
name(string, required): Name for this traffic groupprotocol(string, required): Application protocol for this group. Supported values:"redis""http""memcached-binary""memcached-ascii""xylem-echo"(testing only)
target(string, required): Target address for this group. Format depends on transport:- TCP/UDP: numeric
"ip:port"or"[ipv6]:port" - Unix socket:
"/path/to/socket"
- TCP/UDP: numeric
transport(string, default"tcp"):"tcp","udp","unix", or"ntcp"(user-space TCP, needs the top-level[ntcp]section)timestamps(default"user"): timestamp source,"user","kernel",{ hardware = "<interface>" }(tcpandudpon Linux only), or"nic"(ntcpwith the DPDK backend only); the same for groups sharing a thread. See timestamps.threads(array of integers, required): Thread IDs to use for this groupconnections_per_thread(integer, required): Number of connections per threadmax_pending_per_connection(integer, required): Maximum pending requests per connection1= no pipelining (accurate latency measurement)- Higher values = pipelining enabled
on_error(string, default"count"): what an error reply (a Redis error, an HTTP 4xx or 5xx, a memcachedSERVER_ERROR, …) does"count"= it completes its request and counts inrequests.errors; see error replies"abort"= the run fails at the first one, naming the group, connection and reply; no results are written
Protocol Configuration
[traffic_groups.protocol_config.keys] - Key distribution for KV protocols:
strategy(string, required): Distribution strategy"sequential": Sequential keys starting fromstart"random": Uniform random distribution"round-robin": Cycle through keys"zipfian": Zipfian distribution (power law, hot keys)"gaussian": Normal distribution (temporal locality)
n(integer, required for zipfian): Key space sizemax(integer, required for random/round-robin): Maximum key valuestart(integer, optional for sequential): Starting key (default: 0)theta(float, required for zipfian): Skew parameter (0.99 = high skew)mean_pct(float, required for gaussian): Mean as percentage of keyspace (0.0-1.0)std_dev_pct(float, required for gaussian): Standard deviation as percentage (0.0-1.0)value_size(integer, required): Size of values in bytes
[traffic_groups.protocol_config.operations] - Operation configuration:
Fixed operation:
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get" # or "set", "incr"
Weighted operations:
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.8
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.2
[traffic_groups.protocol_config.value_size] - Optional value size configuration:
[traffic_groups.protocol_config.value_size]
strategy = "fixed"
size = 128
Or variable sizes:
[traffic_groups.protocol_config.value_size]
strategy = "uniform"
min = 64
max = 4096
Redis connection setup - Optional fields directly in [traffic_groups.protocol_config], sent once by every connection before any other request:
auth(table, optional): Authenticate withAUTH. Set exactly one ofpasswordandpassword_env.username(string, optional): ACL user (Redis 6+); without it,AUTH <password>checksrequirepasspassword(string): Passwordpassword_env(string): Environment variable holding the password, read when the run starts; an unset variable fails validation
db(integer, optional): Database toSELECT, 0 to 2147483647 (default: none, so database 0)resp(integer, optional):2(default, no HELLO) or3(sendsHELLO 3)
[traffic_groups.protocol_config]
auth = { username = "bench", password_env = "REDIS_PASSWORD" }
db = 3
resp = 3
Setup requests are not measured, counted or dumped, and an error reply to one fails the run. See Redis connection setup.
Traffic Policy
[traffic_groups.traffic_policy] - Rate control:
type(string, required):"closed-loop": Send as fast as possible (max throughput)"fixed-rate": Evenly spaced sends at a fixed rate"poisson": Poisson arrival process (open-loop)
rate(float, required for fixed-rate/poisson): Requests per second of the whole group, across all its threads and connectionsdispatch(string, rate-driven policies only): how the arrivals reach the connections,"connection"(default) or"group"; see group dispatch
Every policy except closed-loop is rate-driven, including adaptive and the
time-varying sinusoidal, ramp, spike and sawtooth patterns. Each
connection of a rate-driven group follows an intended schedule: every
request is due one inter-arrival time after the previous request’s intended
time, not after its actual send.
The rates are the group’s, shared by its N connections
(connections_per_thread times the length of threads), numbered
c = 0 .. N-1 across its threads. Every connection of every thread and group
counts its schedule from one start time that all threads share, set once every
thread has connected. fixed-rate interleaves the connections into one stream:
connection c sends its k-th request (c + k·N)/rate seconds after the
start (to the nanosecond, rounded down, without accumulating error), so the
group sends one request every 1/rate seconds and no two connections share a
send time. A poisson connection is a Poisson process at rate/N, its first
arrival one exponential inter-arrival after the start. adaptive and the
patterns run each connection at 1/N of the configured rates, connection c
starting c/N of a request into its schedule, and a pattern’s time counts from
the start. A connection that can first send after the start, because it was
still connecting or setting up, begins at its first intended time from then
on; the sends it missed are not counted as unsent.
Inter-arrival times are fixed (fixed-rate), exponential samples (poisson),
one interval at the current rate (adaptive), or, for patterns, the time until
the pattern’s rate, held constant over 10 ms steps, accumulates one request.
A pattern that drops to zero schedules nothing, so a pause leaves no backlog.
A connection sends when its next intended time has arrived, its pipeline has
room and its protocol is ready. When the sender falls behind (a full pipeline,
a slow server, preemption), the overdue requests go out back to back as soon as
it can send again; none is skipped. A request’s latency is measured from its
intended send time: the send lag (actual minus intended send time) plus the
service latency from the send to the response. Without this, the delay of
requests that could not be sent on time would be omitted from the results
(coordinated omission). adaptive adjusts its rate from these latencies, so a
growing backlog backs its rate off. closed-loop requests have no intended time
and no send lag. See request accounting.
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.traffic_policy]
type = "fixed-rate"
rate = 100.0 # 100 req/s for the group, evenly spaced
[traffic_groups.traffic_policy]
type = "poisson"
rate = 50.0 # Mean 50 req/s for the group
Group dispatch
By default every connection runs its own schedule, so a request due on a
connection whose pipeline is full waits for that connection even while others
are idle. With max_pending_per_connection = 1, which protocols without
pipelining such as HTTP/1.1 need, the arrivals then wait for responses: their
sends go out late, and the load is no longer open-loop.
With dispatch = "group", each thread of the group runs one schedule, its
1/T share of the group’s rates for T threads, by the rules above with
thread t (its position in threads) in place of connection c:
fixed-rate threads interleave into one evenly spaced stream, and each
poisson thread is a Poisson process at rate/T, seeded per thread from
experiment.seed. Each arrival goes to the thread’s connection of the group
that has been idle longest: set up, its protocol ready, and its pipeline not
full. An arrival due while none is idle waits for the first to free up, with
its send lag and latency counted from its intended time, so it counts in
late_sends; arrivals still waiting at the end of the window count in
unsent. The schedule starts when the first connection is set up. Give the
group enough connections to cover the rate times the latency, plus bursts.
closed-loop takes no dispatch.
[traffic_groups.traffic_policy]
type = "poisson"
rate = 20000.0
dispatch = "group" # one arrival process per thread, sent on idle connections
Sampling Policy
[traffic_groups.sampling_policy] - Latency storage. If the section is
omitted, the group uses an auto-resizing HDR histogram with 3 significant
figures, which records every latency and merges independently of order.
type(string, required):"hdr-histogram"(default): HDR histogram of every latency.sigfigs(integer 1-5, default 3): precision of each value.max_value_us(integer, optional): upper bound in microseconds. Unset, the histogram grows to fit every value. Set, larger values are recorded as the bound and counted in theclamped_samplesoutput field.
"unlimited": store every latency; exact nearest-rank percentiles, memory grows with the request count."limited": keep a uniform random sample (reservoir) of at mostmax_sampleslatencies per bucket and connection. Merging weights each part by the number of latencies it saw, so percentiles describe the whole run, not its first requests.rate(float, default 1.0): fraction of latencies offered to the sample.max_samples(integer, default 131072).
"dd-sketch"(alpha,max_bins) and"t-digest"(compression): mergeable quantile sketches. T-digestcompressionmust be a positive integer; it defaults to 1000. Higher values use more memory and generally improve accuracy. This requirement applies to both group and global policies."none": Disable latency sampling (throughput/bytes still recorded)
For every type except none, the mean, min, max, standard deviation and
sample count are computed exactly from every recorded latency; only the
percentiles depend on the storage type.
DDSketch 0.4.2 uses floor-based value-to-bin mapping and corresponding bin
representatives; 0.3.x used ceiling-based mapping. Approximate percentiles,
and therefore percentile threshold results, can change for the same samples
and alpha. max_bins limits the number of logarithmic bins, not a numeric
latency range. When the observed values require more than that many bins, the
lowest bins collapse and their estimates can exceed the configured relative
error. Xylem places values up to and including 1 ns in the zero bucket and
truncates estimated values to whole nanoseconds; these can also prevent a
strict relative error bound, especially near zero.
The dependency’s public count saturates at usize::MAX on 32-bit targets;
Xylem’s independently tracked u64 sample count preserves the recorded count.
[traffic_groups.sampling_policy]
type = "unlimited"
[traffic_groups.sampling_policy]
type = "limited"
rate = 0.01 # 1% sampling
max_samples = 10000
# Disable latency sampling for this group
[traffic_groups.sampling_policy]
type = "none"
Stats Config
Top-level stats configuration ([stats]).
bucket_duration(string, default"1s"): time bucket for per-connection recordsinclude_records(bool, default false)sampling_policy(optional): global latency sampling policy; set totype = "none"to disable global latency recording; if omitted, the first traffic group’s policy is used
Other keys are rejected. The former streaming (Parquet) section was removed, so profiles that still set it fail to load.
Output Section
The [output] section configures where and how results are written.
[output]
format = "json"
file = "/tmp/results.json"
real_time = false
Fields
format(string, default"json"): Output format"json": Detailed JSON with experiment metadata, global and per-group statistics"human": Human-readable console output"html": HTML report with charts"both": Both JSON and HTML
file(string, required): Output file pathreal_time(boolean, default false): Must be false; real-time updates are not supported.html.library(string, default"chartjs"): Only"chartjs"is supported.html.theme(string, default"light"): Only"light"is supported.
Thresholds and Validity
[thresholds] maps a metric, optionally filtered to a traffic group, to a
list of expressions; [validity] tunes the checks that a run applied its
configured load:
[thresholds]
"latency" = ["p99 < 250us", "p99.9 < 1ms"]
"latency{group=latency-agent}" = ["p50 < 80us"]
"requests.timed_out" = ["rate < 0.001"]
"requests.errors" = ["rate < 0.01"]
[validity]
enabled = true
max_unsent_ratio = 0.001
max_late_send_ratio = 0.01
skip = []
thresholds(table of string lists, default empty): see Thresholds and Validity for metrics (includingrequests.errors,error_latencyand thelatency_breakdownparts), aggregations, units and evaluation. Its keys are checked as metrics, not as profile keys.validity.enabled(bool, default true): false disables every check.validity.max_unsent_ratio(number from 0 to 1, default 0.001)validity.max_late_send_ratio(number from 0 to 1, default 0.01)validity.skip(list of"unsent","late_sends", default empty)
Other [validity] keys are rejected.
Request Dump
Use [request_dump] to record outgoing requests as CSV files:
[request_dump]
directory = "/tmp/xylem-requests"
prefix = "requests"
rotation = "hourly"
encoding = "hex"
The directory is required. Rotation defaults to "never"; other values are
"minutely", "hourly", "daily", or { size = 1048576 } for a byte limit.
Encoding defaults to "hex"; "base64", "utf8", "escaped", and "none" are
also available. max_files optionally limits retained dump files.
Generated JSON Schema
The checked-in profile schema is generated directly from the Rust configuration types. Regenerate it with:
cargo run --quiet --bin xylem -- schema > schema/profile.schema.json
Keep stdout separate from Cargo diagnostics on stderr. CI checks JSON validity
and compares the committed schema to the command’s output. The schema describes
the configuration’s shape; runtime validation also checks supported options,
addresses, and protocol settings. detailed-json is obsolete; use json.
Complete Example
[experiment]
name = "redis-bench"
description = "Redis benchmark with latency/throughput separation"
duration = "30s"
seed = 42
# Latency agent - accurate latency measurement
[[traffic_groups]]
transport = "tcp"
name = "latency-agent"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [0]
connections_per_thread = 10
max_pending_per_connection = 1
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "fixed"
operation = "get"
[traffic_groups.traffic_policy]
type = "poisson"
rate = 100.0
[traffic_groups.sampling_policy]
type = "unlimited"
# Throughput agent - high throughput generation
[[traffic_groups]]
name = "throughput-agent"
protocol = "redis"
target = "127.0.0.1:6379"
threads = [1, 2, 3]
connections_per_thread = 25
max_pending_per_connection = 32
[traffic_groups.protocol_config.keys]
strategy = "zipfian"
n = 1000000
theta = 0.99
value_size = 64
[traffic_groups.protocol_config.operations]
strategy = "weighted"
[[traffic_groups.protocol_config.operations.commands]]
name = "get"
weight = 0.8
[[traffic_groups.protocol_config.operations.commands]]
name = "set"
weight = 0.2
[traffic_groups.traffic_policy]
type = "closed-loop"
[traffic_groups.sampling_policy]
type = "limited"
rate = 0.01
max_samples = 10000
[output]
format = "json"
file = "/tmp/redis-bench-results.json"
real_time = false