
Recall first from Testing and hardening EdgeHub
- Dependency files keep the build from linking stale objects after a header changes
- Unit tests isolate each module; the integration test exercises the assembled pipeline with deterministic input
- valgrind and AddressSanitizer catch overlapping error classes at very different costs and must not run together
Generating load and measuring it
3 min readEdgeHub is built, tested and hardened. This lesson pushes it hard with many clients and a high message rate, then finds bottlenecks with perf and vmstat.
A single message, sent once and checked, proves the pipeline works. It does not show how the hub behaves when fifty subscribers read at once while the sensor side runs at a high rate. A load test measures two quantities under contention: The rate at which the hub completes work, measured in messages (or bytes) per second. and The time between EdgeHub stamping a sample and a subscriber reading its frame, measured per message..
Measure at two levels. First find the transport ceiling with iperf3, which moves raw bytes over a socket and never enters EdgeHub's pipeline:
iperf3 -s # server side, in one terminal
iperf3 -c 127.0.0.1 -t 10 -P 4 # four parallel streams for ten seconds, in another
iperf3 reports the bandwidth in Mbit/s that the kernel and socket layer can push. That is the ceiling: EdgeHub can never complete more bytes of message traffic per second than the transport carries. If EdgeHub's measured throughput is far below the iperf3 number, the bottleneck is inside EdgeHub, not in the network stack. The loopback run isolates the application; run over a real link to a board when you want the wire included.
The second tool is a custom client that speaks EdgeHub's own framing, the 28-byte sample frame you implemented in the pipeline lesson (an 8-byte header and a 20-byte payload). It is the load client from the testing lesson: it connects to EdgeHub's subscriber port (sink.subscribers in the config, 9001 in the design lesson) and reads real frames, so its numbers include everything the pipeline does. For a high message rate, run EdgeHub with a fake sensor that produces samples at a fixed high rate, for example 1000 per second. This client is one subscriber that counts the frames it receives:
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
static int read_full(int fd, uint8_t *p, size_t n) {
while (n > 0) {
ssize_t r = read(fd, p, n);
if (r <= 0) return -1; /* error or EdgeHub closed */
p += r; n -= (size_t)r;
}
return 0;
}
int main(int argc, char **argv) {
if (argc != 4) { fprintf(stderr, "usage: %s host port frames\n", argv[0]); return EXIT_FAILURE; }
struct sockaddr_in a = {0};
a.sin_family = AF_INET;
a.sin_port = htons((uint16_t)atoi(argv[2]));
if (inet_pton(AF_INET, argv[1], &a.sin_addr) != 1) { fprintf(stderr, "bad address\n"); return EXIT_FAILURE; }
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0 || connect(fd, (struct sockaddr *)&a, sizeof a) < 0) { perror("socket/connect"); return EXIT_FAILURE; }
long n = atol(argv[3]);
uint8_t f[28]; /* one sample frame */
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (long i = 0; i < n; i++)
if (read_full(fd, f, sizeof f) < 0) { perror("read"); return EXIT_FAILURE; }
clock_gettime(CLOCK_MONOTONIC, &t1);
close(fd);
double el = (double)(t1.tv_sec - t0.tv_sec) + (double)(t1.tv_nsec - t0.tv_nsec) / 1e9;
printf("frames=%ld elapsed=%.2fs rate=%.0f frames/s\n", n, el, (double)n / el);
return EXIT_SUCCESS;
}
The timer uses clock_gettime(CLOCK_MONOTONIC), a monotonic clock that never jumps backwards, unlike the wall clock. This program is a single subscriber, so it measures one connection. Real concurrency needs one thread (or process) per connection; the lab extends this client with pthread_create. The -P 4 flag on iperf3 is the same idea applied to raw sockets.
This program reports throughput only: it never records the age of one frame. To get latency percentiles, read each frame's ts_ns field (payload bytes 8 to 15, that is frame bytes 16 to 23, big-endian, converted with be64toh), store now - ts_ns for every frame in an array, then sort it. The lab does exactly that and prints p50 and p99. Throughput and latency are different measurements: a hub can push many messages per second while each message is slow, because many messages are in flight at once.
{{< callout type="note" >}}This latency is only valid with the client on the same machine as EdgeHub: ts_ns comes from EdgeHub's CLOCK_MONOTONIC, and monotonic clock values can be compared only within one boot of one machine. To include the network between a board and the VM, both sides would need synchronized wall clocks (NTP or PTP) and a wall-clock timestamp in the frame.{{< /callout >}}
Compile with gcc -Wall -Wextra -std=c17 -O2 -o loadtest loadtest.c. On glibc 2.39, clock_gettime lives in libc, so no extra library flag is needed.
Finding where the time goes
4 min readWith throughput and p99 in hand, the question is where the time actually goes. There are only a few places: a CPU-bound thread, kernel time spent on syscalls and context switches, waiting on I/O, or contention on a lock. Each leaves a different signature in the system counters.
Start with top -H, which lists threads rather than processes (replace edgehub with your binary's actual name):
top -H -p $(pgrep -n edgehub)
Read the CPU column. One thread pinned at 100% while the others idle means a single serial code path is the limit. Every worker near 100% means the work is parallel and CPU-bound. Most threads asleep means the hub is waiting, not computing.
vmstat 1 samples the whole system every second and shows the columns that classify the wait. With the procps 4.0.4 shipped in Ubuntu 24.04 the header is:
procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r b swpd free buff cache si so bi bo in cs us sy id wa st gu
The values differ on every machine. Read four columns. r is the run queue, the count of tasks running or waiting to run: if r stays above your core count, tasks are queueing for CPU. sy is time in the kernel: high sy under a message-rate test points at syscalls and context switches, not your algorithm. wa is time waiting for I/O: high wa means the hub is blocked on a device. cs is context switches per second: a jump in cs while throughput plateaus is the fingerprint of lock contention or too many threads waking each other.
/proc/loadavg summarizes the same picture in one line:
cat /proc/loadavg
The three leading numbers are the one-, five- and fifteen-minute load averages. A load average is the exponentially damped average of tasks that are runnable plus tasks in uninterruptible sleep (usually waiting on I/O). Compare the one-minute value with your core count (nproc). A load of 8 on a 4-core board means the last minute averaged four tasks queued beyond the cores. The fourth field is running/total, the currently runnable threads over the total thread count; the last field is the most recent PID.
ss -s checks the socket side, which a CPU-only view misses:
ss -s
This prints a summary with total sockets and, for TCP, how many are established, closed, in time-wait and so on. Run it during the load test to confirm your N connections are actually open, and to spot a leak, for example a rising closed or time-wait count that never drains. A hub that caps at some connection count or fills its socket table fails here even when the CPU is idle.
Only now point perf at the problem. You met perf in the profiling lesson; here you use it to name the function that costs the time:
sudo perf top -p $(pgrep -n edgehub) # live view of the hottest symbols
sudo perf record -g -p $(pgrep -n edgehub) -- sleep 10
sudo perf report # then read the call-graph report
{{< callout type="warning" >}}On Ubuntu, perf often needs /proc/sys/kernel/perf_event_paranoid lowered to 1 or -1, or membership in a group granted perf events, before a non-root user can profile. Adjust it for the test and restore it afterwards.{{< /callout >}}
In the report, read the top entries. If pthread_mutex_lock or a futex appears near the top, the hub is lock-bound. If a parser or memcpy dominates, the CPU is spent there. If send or write dominates, the hub is spending its time copying out. The symbol names the fix, and the next lesson (stress scenarios and fixes) acts on these findings.
Percentiles and Amdahl scaling
3 min readThe mean hides the tail. If 99 messages take 1 ms and one takes 101 ms, the mean is 2 ms and says nothing about the slow message. A A percentile reports the value that a given fraction of samples fall at or below, for example p99 is the value 99% of requests beat. To compute one, record every latency sample, sort the array ascending, and read the entry at the right index: p50 is the median, the entry half the requests beat; p99 is the entry that 99% of requests are at or below, so 1% are slower. You must keep every sample until you sort, because averaging as you go destroys the percentile.
Why care about the 1%? Because real requests rarely depend on a single call. If one call in a hundred is slow, a request that needs a hundred independent calls has roughly a 63% chance (1 minus 0.99 to the hundredth power) of hitting at least one slow call, and its own latency inherits that tail. When you budget capacity, budget the percentile a realistic client actually experiences, which for a fanning-out client is p99 or p99.9, not the mean.
This connects to capacity planning. Below saturation, latency is roughly flat plus a small queueing delay. As offered load climbs toward the hub's capacity, the queue grows and latency bends upward steeply. Little's law states the relationship: the average number of in-flight messages L equals the arrival rate lambda times the average latency W, written L = lambda * W. As the arrival rate approaches the service rate, W climbs without bound. Load test at increasing N and find the knee, the client count where your target percentile crosses its budget. Plan to operate below that knee with headroom, because real traffic bursts.
Amdahl's law explains why the knee is where it is. The pipeline has serial stages (the accept loop, any state guarded by one lock, a stage that must be single-threaded) and parallel stages (per-connection parsing and forwarding). If a fraction p of the work can run in parallel across n threads and the remaining fraction 1 - p cannot, the maximum speedup over one thread is:
S = 1 / ((1 - p) + p / n)
As n grows, S approaches 1 / (1 - p). The serial fraction sets a hard ceiling no number of threads can cross. A stage that holds a global lock for 10% of the pipeline caps the whole hub at 10x, even with a thousand threads. This is why perf matters: the time perf attributes to the lock or the single-threaded stage is your 1 - p, and it predicts how much any thread count can ever buy. To scale beyond the ceiling you must shrink the serial fraction, by sharding state or using the lock-free structures from the ring-buffer lesson, not by adding threads. The lab measures the throughput curve against EdgeHub's worker-thread count and reads the serial fraction off where the curve flattens.
The next lesson takes these findings and turns them into fixes: EPOLLEXCLUSIVE, socket buffer tuning, thread-pool sizing and queue bounds, and hardening the hub against the failure modes a heavy load exposes.
Key takeaways
- iperf3 measures the transport ceiling; a custom client measures EdgeHub's per-message latency and throughput.
- vmstat's r, sy, wa and cs columns classify CPU, kernel, I/O and context-switch pressure.
- p99 shows the slow tail that the mean hides, and it matters when clients fan out.
- Amdahl's law caps speedup at 1/(1-p): the serial fraction, not the thread count, sets the ceiling.
Reflect
- Explain to a colleague, in two sentences: generate concurrent load against EdgeHub with a custom client and measure throughput and p99 latency.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageperf(1): performance analysis tools
- Man pagevmstat(8): report virtual memory statistics
- Man pagetop(1): display Linux processes
- Man pagess(8): another utility to investigate sockets
- Man pageproc(5): process information pseudo-filesystem
Official documentation first. Links checked when the lesson was published.