In previous articles, I explained how the Linux kernel implements IPv4 and
IPv6 routing tables, and I showed the performance improvement of route
lookups from Linux 2.6.32 to 4.16 for IPv4 including the impact of
the Meltdown and Spectre mitigations as well as from Linux 2.6.39 to 4.18
for IPv6. This article updates the numbers through Linux 7.3 and
investigates the perpetrator responsible for the performance regressions!
I ran the following benchmarks on an AMD EPYC 8024P, a Zen 4c
CPU, rented from Scaleway, running at 2.4 GHz with CPU boost disabled. I
compiled the kernels with GCC 10.2: this version can compile older kernels as
well as the current ones.
IPv6
Performance evolution of IPv6 route lookups. Versions with an asterisk have SRSO mitigation disabled.
I tested four scenarios:
a recent full view with about 260,000 prefixes,
a full view from 2017 with about 40,000 prefixes,
a set of 40,000 /48 prefixes, such that 2 lookups out of 3 match, and
a set of 40,000 random /128 prefixes, such that 1 lookup out of 400 matches.
In Linux 4.15, Wei Wang improved the lookup performance by replacing the
read-write lock with an RCU and a spinlock in commit 66f5d6ce53e6. In Linux
4.18, David Ahern improved the data structures used by route lookup. In
Linux 5.9, Brian Vazquez removed expensive indirect calls in commit
55cced4f813b.
The major 200 ns regression introduced in Linux 6.5 wiped out all these
improvements. This version implements a mitigation for "Speculative Return
Stack Overflow," a vulnerability affecting AMD processors, in commit
fb3bd914b3ec. This mitigation adds about 20 cycles on each function return.
It was backported to older kernels (5.10, 5.15, 6.1, and 6.4). To keep the
results legible, I disabled the mitigation for these versions with
spec_rstack_overflow=off on the kernel command-line.
You can check the vulnerabilities impacting your CPU and their mitigations with
lscpu. Some mitigations may depend on the microcode or on the
firmware.1
$ lscpugrep'^Vuln'Vulnerability Gather data sampling: Not affectedVulnerability Indirect target selection: Not affectedVulnerability Itlb multihit: Not affectedVulnerability L1tf: Not affectedVulnerability Mds: Not affectedVulnerability Meltdown: Not affectedVulnerability Mmio stale data: Not affectedVulnerability Reg file data sampling: Not affectedVulnerability Retbleed: Not affectedVulnerability Spec rstack overflow: Mitigation; Safe RETVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctlVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitizationVulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affectedVulnerability Srbds: Not affectedVulnerability Tsa: Vulnerable: Clear CPU buffers attempted, no microcodeVulnerability Tsx async abort: Not affectedVulnerability Vmscape: Mitigation; IBPB before exit to userspace
IPv4
Performance evolution of IPv4 route lookups. Versions with an asterisk have SRSO mitigation disabled.
I tested three scenarios:
a recent full view with more than 1,000,000 prefixes,
a subset of a full view from 2017 with 500,000 prefixes, and
a set of 500,000 contiguous /32 prefixes.
The 30 ns impact of the mitigation for SRSO in Linux 6.5 is smaller than for
IPv6 because IPv4 route lookups traverse fewer functions: around 4 function
calls for IPv4 compared to 25 for IPv6.
In Linux 5.11, I introduced a regression in commit c0c5a60f0f13 after
fixing the behavior of net.ipv4.conf.all.ignore_routes_with_linkdown!2
As a result, the ip_ignore_linkdown() function spends
around 5 additional cycles to return a result as it needs to follow three
additional pointers. fib_lookup() eventually calls it in the
following code:
Impact of mitigations
To reduce the impact of mitigations, you can disable all of them with
mitigations=off, disable only a specific one like with
spec_rstack_overflow=off, or protect against only some attack vectors with
mitigations=auto,no_user_kernel, starting from Linux 6.17.
The impact is also quite different depending on the CPU. For example, on a Xeon
W-2295, an Intel desktop CPU from 2020, the impact of the mitigations is only
a few cycles for IPv4, and less than 3% for IPv6. The main contributor is the
mitigation for the Indirect Target Selection vulnerability, which is fixed
since the Sapphire Rapids architecture.
If we set aside the regressions introduced by the mitigations against CPU
attacks, the performance of IPv4 is declining slowly over time while IPv6 has
improved in the past and is currently stable. If routing performance is
important, you have several options: choose a different CPU like an AMD Zen 5
CPU, a fourth generation Xeon CPU, or maybe an ARM Neoverse V2;
disable some or all the mitigations; bypass routing with XDP/eBPF;5 or
offload routing to the network card.
Note
Maytham Alsudany reviewed a first draft of this article. Any errors are still mine!
The microcode was out of date on my machine as I forgot to install the
amd64-microcode package. As it only impacts TSA, our benchmark is
unaffected. Spectre v2 mitigation did not enable automatic IBRS, because
of SEV-SNP being enabled in the firmware. With automatic IBRS, the
impact of SRSO should be smaller.
Despite ipvX in its title, the commit only changes the behavior of the
IPv4 code. The IPv6 version overwrites the value of each device in
addrconf_fixup_linkdown().
Linux 7.5 will be the first stable release including this fix.
At 2.4 GHz, one cycle is about 0.42 ns.
This requires avoiding bpf_fib_lookup(), which relies on
the same kernel lookup.
Bunny CDN
Bunny.net started as BunnyCDN in 2015. They added IPv6
support in 2017. Switching was uneventful. I don't bring a custom domain: I
serve the content from the b-cdn.net domain. As I depend on content
negotiation to serve AVIF and WebP images, I configure the CDN to cache
each image format separately.
I disable logging to avoid collecting personal
information. While the bunny.net GDPR page promises they anonymize data, it
is unclear what CloudFront keeps in its own logs when logging is disabled.
The only downside of the bunny.net CDN offering is the lack of HTTP/3. I asked
their support: two minutes later, they answered they are working on it but have
no ETA to share.
Bunny DNS
Bunny.net introduced their DNS offering in 2022 and recently reduced its
cost to almost zero. They support geographical routing, but a
very cool feature is the scriptable DNS: it runs a piece of user-supplied
JavaScript on each query to compute the answer.
I run seven small NixOS virtual machines to host this blog around the world:
Paris, Nuremberg, Ashburn, Singapore, San Jose, S o Paulo, and Sydney. Bunny's
scriptable DNS lets me return the IP addresses of the two nearest servers.
The browser falls back to the second server if the first one is down.
constservers=[ipv4:"45.90.160.60",ipv6:"2a0c:8881:5:100::1",latitude:48.88,longitude:2.22, ,/* [ ] */ipv4:"139.180.162.114",ipv6:"2001:19f0:5800:1855:5400:6ff:fef0:4c0a",latitude:-33.87,longitude:151.21, ,];constfamilies=A:"ipv4",AAAA:"ipv6" ;constrecords=A:ARecord,AAAA:AaaaRecord ;exportdefaultfunctionhandleQuery(query)consttype=String(query.request.queryType).toUpperCase();constfamily=families[type];if(!family)return[];// Get user locationconstlocation=query.request.geoLocation;// Build a list of candidatesletcandidates=servers.map((s)=>newServer(s[family],s.latitude,s.longitude,100),);// Select the two closest alive serversconstselected=[];while(selected.length<2)constserver=RoutingEngine.getClosestServer(candidates,location,true);selected.push(server);candidates=candidates.filter((s)=>s.ip!==server.ip);// Return their IP addressesreturnselected.map((s)=>newrecords[type](s.ip,3600));
The above script relies on the
RoutingEngine.getClosestServer() helper, which returns the
closest alive3 server to the user.4 Thanks to Doggo, we can
check it works as expected, at least for A:5
$ doggo--gp-from="Amsterdam"Avincent.bernat.ch
LOCATION NAME TYPE TTL ADDRESSAmsterdam, NL vincent.bernat.ch. A 3600s 45.90.160.60 vincent.bernat.ch. A 3600s 116.203.18.48$ doggo--gp-from="Texas"Avincent.bernat.ch
LOCATION NAME TYPE TTL ADDRESSHouston (TX), US vincent.bernat.ch. A 3600s 5.161.44.145 vincent.bernat.ch. A 3600s 149.28.219.155
The most annoying drawback of this method is that a user from Buenos Aires gets
both S o Paulo (1000 mi, 30 ms RTT) and Ashburn (5200 mi, 140 ms RTT). Most
resolvers randomize the order, so the user may pull the web page from Ashburn.
We could return only the nearest server and swap the scripted record with the
built-in geographic routing instead. But if the server becomes unavailable, the
browser has no alternative until the DNS cache expires. It leaves a short window
of unavailability, even with a short TTL.
The HTTPS record solution
The HTTPS DNS record, defined in RFC 9460, solves both the availability
and the latency issues. Modern browsers query this record to get additional
information to reach an HTTP server, including an alternative port and the
application layer protocol HTTP/2 or HTTP/3. Each record has a priority. We
can ask browsers to contact the nearest server first and fall back to the next
one if the first is unavailable:
vincentHTTPS1first.geoalpn="h3,h2"vincentHTTPS2second.geoalpn="h3,h2"vincentHTTPS3.alpn="h3,h2"; Bunny DNS must provide the two closest servers as "first.geo"; and "second.geo" with geographic or latency routing.first.geoA45.90.160.60first.geoAAAA2a0c:8881:5:100::1second.geoA116.203.18.48second.geoAAAA2a01:4f8:1c0c:5eb5::1vincentA45.90.160.60vincentA116.203.18.48vincentAAAA2a0c:8881:5:100::1vincentAAAA2a01:4f8:1c0c:5eb5::1
This looks like the ideal solution! Unfortunately, Chrome ignores any record
whose target is not ., hence the last record at priority 3.
Moreover, unlike with a CNAME, Bunny DNS does not return the IP addresses for
first.geo and second.geo in the additional section. The resolver needs to
send a first request to get the HTTPS record, and a second to resolve
first.geo.
HTTPS records are still too new for this use case. Back to the drawing board!
The hybrid solution
As a compromise, the script returns the two nearest servers if they are at a
similar distance from the user. Otherwise, it returns only the nearest one with
a lower TTL of 2 minutes.
exportdefaultfunctionhandleQuery(query)constlocation=query.request.geoLocation;letcandidates=servers.map((s)=>newServer(s.ipv4,s.latitude,s.longitude,100),);// Select the two closest serversconstselected=[];while(selected.length<2)constserver=RoutingEngine.getClosestServer(candidates,location,true);selected.push(server);candidates=candidates.filter((s)=>s.ip!==server.ip);// Compute the distance to the user for each of themconst[first,second]=selected.map((s)=>GeoDistance.calculate(s,location),);// If the second one is at twice the distance and at more than 1000 miles// from the first, return only the first one with a TTL of 2 minutes.if(second>2*first&&second-first>1000)return[newARecord(selected[0].ip,120)];// Otherwise, return both with a TTL of 1 hour.returnselected.map((s)=>newARecord(s.ip,3600));
We can check it with Doggo. From Chicago, we get only the Ashburn server
with a TTL of 2 minutes, while from Mexico, we get both Ashburn and San Jose.
$ doggo--gp-from="Chicago"Avincent.bernat.ch
LOCATION NAME TYPE TTL ADDRESSChicago (IL), US vincent.bernat.ch. A 120s 5.161.44.145$ doggo--gp-from="Mexico"Avincent.bernat.ch
LOCATION NAME TYPE TTL ADDRESSQueretaro, MX vincent.bernat.ch. A 3600s 5.161.44.145 vincent.bernat.ch. A 3600s 149.28.219.155$ doggo--reverse5.161.44.145149.28.219.155
NAME TYPE TTL ADDRESS145.44.161.5.in-addr.arpa. PTR 7187s web05.luffy.cx.155.219.28.149.in-addr.arpa. PTR 3600s web07.luffy.cx.
Note
On the live page, the map below is interactive: point at a
location to get the DNS answer, or disable servers to see how the answers
change.
The complete code is a bit more complex. It works around
RoutingEngine.getClosestServer() supporting only IPv4, and it handles the case
where there are not enough alive servers to build an answer.
Bunny.net has a comprehensive Terraform provider. I leverage CDK
Terrain to build the target state in TypeScript and OpenTofu to deploy
it. Have a look at "Managing infrastructure with Terraform, CDKTF, and
NixOS" for more details.6
ACME DNS with Hickory DNS
Route 53 covered one additional use case of mine: serving acme.luffy.cx to
solve DNS-01 ACME challenges. Unlike Route 53, Bunny DNS cannot
restrict access to a single zone with a fine-grained access policy. As this
usage requires neither high availability nor low latency, I replaced Route 53
with Hickory, a memory-safe DNS server written in Rust. It supports
automatic DNSSEC signatures and dynamic updates. Its
configuration is simple:
[[zones]]zone="acme.luffy.cx"zone_type="Primary"[zones.stores]allow_update=truetype="sqlite"journal_path="acme.luffy.cx.sqlite"zone_path="acme.luffy.cx.zone"# Private key to sign the zone with DNSSEC. Generated with:# openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256[[zones.keys]]algorithm="ECDSAP256SHA256"key_path="/etc/hickory-dns.acme.luffy.cx.pem"# TSIG key to sign zone updates. Generated with:# openssl rand 32[[zones.stores.tsig_keys]]algorithm="hmac-sha256"key_file="/etc/hickory-dns.acme.luffy.cx.update.acme.luffy.cx.tsig"name="update.acme.luffy.cx."
The provided zone file only seeds the database on first start. I delegate
DNS-01 challenges to this zone with CNAME records:
Lego, the ACME client I use to get certificates from Let's Encrypt,
answers the DNS-01 challenge by pushing entries with the DNS UPDATE protocol.
Unfortunately, Bunny DNS cannot publish a DS record in a zone.7 I need one
to secure the acme.luffy.cx zone and certificate delivery. Therefore, I host
the luffy.cx zone on deSEC,8 a free DNS hosting service run by a
non-profit organization based in Berlin. I derive the DS record to publish in
luffy.cx from the DNSKEY record of acme.luffy.cx:
Overall, I am quite happy with the switch to bunny.net. There are still a few
rough edges, like the inability to publish DS records, the lack of HTTP/3, and
the IPv4-only RoutingEngine.getClosestServer() helper. The bill went from US$5
per month to US$1. So far, performance is on par with AWS, but I
only finalized the current setup, including the server in Sydney, in late
October. I need a bit more time to gather more data, and I'll post a short update.
Update (2026-11)
This post was briefly discussed on Hacker News and Lobsters.
I had been hosting media assets on CloudFront since 2011.
Route 53 had served bernat.ch since December 2021. I didn't use healthchecks as
they were too expensive. I didn't host most of my zones there either, as queries
for haproxy.debian.net alone would have cost me around US$10 per month.
A server is alive if it answers an ICMP ping. The bunny.net
documentation gives more details about the checks.
The user queries Bunny DNS through a resolver. Usually, either the resolver
is close to the user, or it exposes the user's subnet through EDNS client
subnet.
Don't use this script as is: RoutingEngine.getClosestServer() only works
with IPv4. The final script works around this limitation.
The article is a bit outdated. CDK Terrain replaces CDKTF, OpenTofu
replaces Terraform, and I now use Colmena instead of NixOps.
I contacted bunny.net support to ask when they will support publishing a
DS record and got an answer seven minutes later: they don't know.
This is a bummer, as they support automatic CDS, a DNS record to advertise
a DS record to the parent zone. They handle one side of the delegation,
not the other.
I also reported a bug with the proof of non-existence, and they replied a
day later with a detailed answer.
Why not use deSEC for ACME challenges? You can limit its tokens to a
single RRset. I could say I prefer to self-host, but the
truth is I only discovered this while writing this article.
To experiment with network stuff, I was using
UML-based network labs. Many alternatives exist, like
GNS3, Netkit, Marionnet or Cloonix. All of them are
great viable solutions but I still prefer to stick to my minimal
home-made solution with UML virtual machines. Here is why:
I didn t want to use disk images. They take a lot of space and
they have to be maintained. They also become cluttered, especially
if you try to reuse them across several labs. They are also
difficult to share.
I want to be able to access my home directory. It contains the
important configuration files related to the lab and I can put them
in the right place thanks to symbolic links when the lab starts. It
also makes exchanging files with the lab quite easy.
I don t want to boot a complete system. This allows me to be
cheap on memory and each virtual system should boot in a few
seconds.
The use of UML had some drawbacks:
It may be buggy. For example, it is currently not possible to use
gdbserver inside UML without a patch. Sometimes, the kernel
won t even compile.
It is slow.
However, UML features HostFS, a filesystem providing access to any
part of the host filesystem. This is the killer feature which allows
me to not use any virtual disk image and to get access to my home
directory right from the guest.
I discovered recently that QEMU provided 9P, a similar filesystem
on top of VirtIO, the paravirtualized IO framework.
Booting QEMU with a minimal kernel
My initial goal was to experiment with
Nicolas Dichtel s IPv6 ECMP patch. Therefore, I needed to
configure a custom kernel. I have started from make defconfig,
removed everything that was not necessary, added what I needed for my
lab (mostly network stuff) and added the appropriate options for VirtIO
drivers:
No modules. Grab the complete configuration if you want to
have a look.
From here, you can start your kernel with the following command
($LINUX is the appropriate bzImage):
Since there is no disk to boot from, the kernel will panic when trying
to mount the root filesystem. QEMU is configured to not display video
output (-display none). A serial port is defined and uses stdio as
a backend.1 The kernel is configured to use this serial port
as a console (console=ttyS0). A VirtIO console could have been used
instead but it seems it is not possible to make it work early in the
boot process.
The QEMU monitor is setup to listen on a Unix socket. It is possible
to connect to it with socat UNIX:$TMP/vm-$name-console.pipe -.
Initial ramdisk
Update (2012-10)
I was initially unable to mount the host filesystem as the root filesystem
for the guest directly by the kernel. In a comment, Josh
Triplett told me to use /dev/root as the mount
tag to solve this problem. I keep using an initrd in this post but the lab
on GitHub has been updated to not use one.
The copy_exec function is stolen from the initramfs-tools package
in Debian. It will ensure that the appropriate libraries are also
copied. Another solution would have been to use a static busybox.
The setup script is copied as /init in the initial ramdisk. It will
detect it has been invoked as such. If it were omitted, a shell would
be spawned instead. Remove the cp call if you want to experiment
manually.
The flag -initrd allows QEMU to use this initial ramdisk.
Root filesystem
Let s mount our root filesystem using 9P. This is quite easy. First
QEMU needs to be configured to export the host filesystem to
the guest:
You should find a complete root filesystem inside /target/ro. I have
used version=9p2000.u instead of version=9p2000.L because the
latter does not allow a program to mount() a host mount
point.2
Now, you have a read-only root filesystem (because you do not want to
mess with your existing root filesystem and moreover, you did not run
this lab as root, did you?). Let s use a union filesystem. Debian
comes with AUFS while Ubuntu and OpenWRT have migrated to
overlayfs. I was previously using AUFS but got errors on some
specific cases. It is still not clear
which one will end up in the kernel. So, let s try
overlayfs.
I didn t find any patchset ready to be applied on top of my kernel
tree. I was working with David Miller s net-next tree. Here
is how I have applied the overlayfs patch on top of it:
Don t forget to enable CONFIG_OVERLAYFS_FS in .config. Here is how
I configured the whole root filesystem:
info"Setup overlayfs"
mkdir/target
mkdir/target/ro
mkdir/target/rw
mkdir/target/overlay
# Version 9p2000.u allows one to access /dev, /sys and mount new# partitions over them. This is not the case for 9p2000.L.
mount-t9prootshare/target/ro-otrans=virtio,version=9p2000.u
mount-ttmpfstmpfs/target/rw-orw
mount-toverlayfsoverlayfs/target/overlay-olowerdir=/target/ro,upperdir=/target/rw
mount-n-tprocproc/target/overlay/proc
mount-n-tsysfssys/target/overlay/sys
info"Mount home directory on /root"
mount-t9phomeshare/target/overlay/root-otrans=virtio,version=9p2000.L,access=0,rw
info"Mount lab directory on /lab"
mkdir/target/overlay/lab
mount-t9plabshare/target/overlay/lab-otrans=virtio,version=9p2000.L,access=0,rw
info"Chroot"exportSTATE=1
cp"$PROGNAME"/target/overlay
execchroot/target/overlay"$PROGNAME"
You have to export your $ HOME and the lab directory from host:
The use of a VDE switch allows me to run the lab as a non-root
user. It is possible to give Internet access to each VM, either by
using the -net user flag or using slirpvde on a special switch. I
prefer the latter solution since it will allow the VMs to speak to each
other.
Debugging
This lab was mostly done to debug both the kernel and Quagga. Each of
them can be debugged remotely.
Kernel debugging
While the kernel features KGDB, its own debugger, compatible with
GDB, it is easier to use the remote GDB server built inside
QEMU.
To connect to the remote GDB server from the host, first locate the
vmlinux file at the root of the source tree and run GDB on it. The
kernel has to be compiled with CONFIG_DEBUG_INFO=y to get the
appropriate debugging symbols. Then, use socat with the Unix socket
to attach to the remote debugger:
$ gdbvmlinux
GNU gdb (GDB) 7.4.1-debianReading symbols from /home/bernat/src/linux/vmlinux...done.(gdb)target remote socat UNIX:$TMP/vm-r1-gdb.pipe -Remote debugging using socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-gdb.pipe -native_safe_halt () at /home/bernat/src/linux/arch/x86/include/asm/irqflags.h:5050 (gdb)
You can now set breakpoints and resume the execution of the kernel.
It is easier to debug the kernel if optimizations are not
enabled. However, it is not possible to
disable them globally. You can however disable them
for some files. For example, to debug net/ipv6/route.c, add
CFLAGS_route.o = -O0 to net/ipv6/Makefile, remove
net/ipv6/route.o and type make.
Userland debugging
To debug a program inside QEMU, you can just use gdb as usual. Your
$HOME directory is available and it should therefore be
straightforward. However, if you want to perform some remote
debugging, that s quite easy. Add a new serial port to QEMU:
$ libtoolexecutegdbserver/dev/ttyS1zebra/zebra
Process /root/code/orange/quagga/build/zebra/.libs/lt-zebra created; pid = 800Remote debugging using /dev/ttyS1
And from the host, you can attach to the remote process:
$ libtoolexecutegdbzebra/zebra
GNU gdb (GDB) 7.4.1-debianReading symbols from /home/bernat/code/orange/quagga/build/zebra/.libs/lt-zebra...done.(gdb)target remote socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-serial.pipe -Remote debugging using socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-serial.pipe -Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.Loaded symbols for /lib64/ld-linux-x86-64.so.20x00007ffff7dddaf0 in ?? () from /lib64/ld-linux-x86-64.so.2(gdb)
Demo
For a demo, have a look at the following video:
stdio is configured such that signals are not
enabled. QEMU will not stop when receiving SIGINT. This is
important for the usage we want to have.
Therefore, it is not possible to mount a fresh /proc
on top of the existing one. I have searched a bit but
did not find why. Any comments on this are welcome.
netip.Addr features an Unmap()
method returning the unwrapped IPv4 contained in an IPv4-mapped IPv6
address: from ::ffff:203.0.113.10 or ::ffff:cb00:710a, it returns
203.0.113.10.1 There is no Map() or To6() method for the reverse
direction. Such a method is trivial to implement, but Go maintainers have
rejected it on the grounds that users should write
netip.AddrFrom16(ip.As16()) and let the compiler optimize it.2 Today,
this pattern is eight times slower than a native method. How can we teach the
compiler to optimize this sequence?
The alternatives
Let s explore three ways to implement the map semantics for netip.Addr. My
favorite is to add it to the Go standard library. Go maintainers prefer a small
external helper chaining netip.AddrFrom16() and netip.Addr.As16(), hoping
the compiler eventually optimizes it. The unsafe package
opens a third path, with the same performance as the first solution.
Modifying the Go standard library
Internally, netip.Addr stores any IP address as a
128-bit value with an extra field z to encode the family and the zone:
typeAddrstructaddruint128zunique.Handle[addrDetail]typeaddrDetailstructisV6bool// IPv4 is false, IPv6 is true.zoneV6string// != "" only if IsV6 is true.var(z0unique.Handle[addrDetail]z4=unique.Make(addrDetail )z6noz=unique.Make(addrDetailisV6:true ))
AddrFrom4() encodes an IPv4 address as an
IPv4-mapped IPv6 address and sets z to the unique value z4:
// AddrFrom4 returns the address of the IPv4 address given by the bytes in addr.funcAddrFrom4(addr[4]byte)AddrreturnAddraddr:uint1280,0xffff00000000uint64(addr[0])<<24uint64(addr[1])<<16uint64(addr[2])<<8uint64(addr[3]) ,z:z4,
Unmap() turns an IPv4-mapped IPv6 address into an
IPv4 address by setting the z field to z4:
Implementing the reverse direction inside the Go standard library is trivial: we
set the z field to z6noz if the address is IPv4.
// To6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.func(ipAddr)To6()Addrifip.Is4()ip.z=z6nozreturnip
As a helper
We can t access the z field from outside the net/netip package. Instead, we
build a small helper around the netip.AddrFrom16(ip.As16()) pattern:
// AddrTo6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.funcAddrTo6(ipnetip.Addr)netip.Addrifip.Is4()ip=netip.AddrFrom16(ip.As16())returnip
As an unsafe function
Another solution uses the unsafe package to alter the Addr struct through
a proxy with the same memory layout:3
// addrProxy has the same memory layout as netip.Addr.typeaddrProxystructaddr[2]uint64// netip.uint128zunsafe.Pointer// unique.Handle[netip.addrDetail]var(anyIPv6=netip.IPv6Unspecified()netipZ6noz=(*addrProxy)(unsafe.Pointer(&anyIPv6)).z)// AddrTo6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.funcAddrTo6(ipnetip.Addr)netip.Addrif!ip.Is4()returnip(*addrProxy)(unsafe.Pointer(&ip)).z=netipZ6nozreturnip
Benchmarks
On my computer, with Go 1.27.1, the standard library solution costs 0.88 ns per
operation, while the solution favored by Go maintainers costs 7.14 ns. The
unsafe solution matches the performance of the first one.
Assembly code
Let s check the assembly code the compiler generates for each solution.4
The one built into the standard library looks like this:5
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Go s assembly language is not a direct representation of the underlying
machine language: it operates on a semi-abstract instruction set derived from
Plan 9 s assembler. It has four pseudo-registers: FP (frame pointer
for function arguments), PC (program counter), SB (static base pointer for
global symbols), and SP (stack pointer). It also has architecture-specific
registers like AX, CX, DX, BX, SI, DI, and R8 to R15.
Instructions storing data use their last argument as the destination.
Instructions can carry an explicit size suffix: MOVB moves a byte, MOVW 16
bits, MOVL 32 bits, and MOVQ 64 bits. In the example above, the first
instruction compares the 64-bit value z4 with the CX register.
The unsafe solution looks almost the same:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnetipZ6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
The helper solution has far more instructions. To understand why, let s look at
the code for As16() and
AddrFrom16(). They are short enough for the compiler
to inline them.
We can already guess the pattern to optimize: the code packs the IP address into
an array, copies it, then unpacks it. If we inline the Go code by hand, we get:
Unfortunately, as of Go 1.26.8, the compiler is not smart enough to do the same:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z; Push the stack (32 bytes):; 0(SP) addr netip.uint128; 16(SP) a16 [16]bytePUSHQBPMOVQSP,BPSUBQ$32,SPCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop here; Pack: byteorder.BEPutUint64(a16[:8], input.addr.hi); byteorder.BEPutUint64(a16[8:], input.addr.lo)MOVBEQAX,net/netip a16+16(SP)MOVBEQBX,net/netip a16+24(SP); addr = a16, 16 bytes at once through the vector register X0MOVUPSnet/netip a16+16(SP),X0MOVUPSX0,net/netip addr(SP); CX = netip.z6nozMOVQnet/netip z6noz(SB),CX; Unpack: output.addr.hi = byteorder.BEUint64(addr[:8]); output.addr.lo = byteorder.BEUint64(addr[8:])MOVBEQnet/netip addr(SP),AXMOVBEQnet/netip addr+8(SP),BXend:ADDQ$32,SPPOPQBPRET// return value = Addr hi: AX, lo: BX, z: CX
The compiler does a decent job on the byte shuffling: the eight byte stores of
BEPutUint64() become a single MOVBEQ, which stores a register byte-swapped.
The eight byte loads of BEUint64() become a single MOVBEQ the other way
round.6 Three groups of instructions remain: a pack, a copy, and an
unpack.
Hacking the Go compiler
The Go compiler has several phases:
The compiler converts the syntax tree and its types into its own intermediate
representation (IR). This process, called noding, goes through
a serialization format named unified IR.
This phase runs two steps: order of evaluation decomposes complex
statements into simpler ones, and desugaring transforms higher-level Go
constructs, like switch or channels, into more primitive instructions or
calls to the runtime.
The compiler rewrites the SSA form into machine-specific variants,
allocates registers, and applies more optimization passes. At the end, the
assembler turns the generated instructions into machine code.
The hammer
My first idea is to replace occurrences of netip.AddrFrom16(ip.As16()) with
netip.Addr addr: ip.addr, z: netip.z6noz as early as possible, during the
noding process. Before that, the type checking phase prevents
us from accessing unexported struct fields.
Go 1.27 introduced a convenient debug option to dump the IR of a function at
interesting points during compilation:
$ GOTOOLCHAIN=go1.27.1GOAMD64=v3gobuild-a-gcflags="-d=astdump=AddrTo6Safe".
Writing text ast output for AddrTo6Safe to AddrTo6Safe.astWriting html ast output for AddrTo6Safe to AddrTo6Safe.htmlWriting html syntax output for AddrTo6Safe to AddrTo6Safe.syntax.html
In the HTML file, the first column shows the IR as it comes out of noding:
In the body of the if statement, we spot the calls to the method
netip.Addr.As16() and to the function netip.AddrFrom16(). Our goal is to
patch them with a struct literal:
In noder s reader.go, the expr() method builds the IR tree for
an expression. At the end of the exprCall case, we add a call to a
rewriteAddrFrom16As16() function. It takes the current node and returns the
struct literal on success, or nil if the rewrite is not possible. First, we
check that we have the expected pattern: a call to the netip.AddrFrom16()
function with a call to the netip.Addr.As16() method as its only argument:
Have a look at the complete patch.7 We can test it
with the following commands:
$ cdsrc
$ ./make.bash
Building Go cmd/dist using /usr/lib/go-1.27. (go1.27.1 linux/amd64)Building Go toolchain1 and bootstrap cmd/go (go_bootstrap) using /usr/lib/go-1.27.Building Go toolchain2 using go_bootstrap and Go toolchain1.Building Go toolchain3 and commands using go_bootstrap and Go toolchain2.Checking command staleness for linux/amd64.---Installed Go for linux/amd64 in /home/bernat/code/free/goInstalled commands in /home/bernat/code/free/go/bin*** You need to add /home/bernat/code/free/go/bin to your PATH.$ exportPATH=$PWD/../bin:$PATH$ goversion
go version go1.28-devel_9834516e20 Sat Sep 12 08:23:11 2026 -0700 linux/amd64$ gotestnet/netip/...
ok net/netip 0.224s$ cd../../go-netip-addrto6
$ gotest.
ok github.com/vincentbernat/go-netip-addrto6 0.062s
The generated code for the helper is now the shortest possible version!
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Go maintainers are unlikely to accept this change. It relies on the internal
structure of net/netip.Addr. It s an ugly hack in the noder, whose job is to
faithfully translate the type-checked AST into the IR. And it s harder to
maintain than adding a To6() method.
The screwdriver
The right place for such an optimization is the generic SSA phase. One of
the last machine-independent passes is memcombine. With the appropriate debug
flag, the compiler dumps the SSA form after this pass:8
The result of the memcombine pass follows the same structure as the assembly
code for AddrTo6Safe()we looked at earlier: two stores,
one move, and two loads we would like to optimize away.
Each line features a value identifier (v442), an operation with its type
(Bswap64 <uint64>), and its arguments (v490).9 Values are the basic
building blocks of SSA and are defined exactly once. Square brackets enclose
integer parameters ([8]) and curly braces contain auxiliary arguments
( netip.addr ). Operations writing to memory produce a new memory state. Every
memory operation takes the current state as its last argument, which keeps them
in order.
To simplify this code, we could apply three rewriting rules:
The first one adds a shortcut when loading through a move: (Load (OffPtr
[o] p) (Move p src mem)) => (Load (OffPtr [o] src) mem). This matches v174
with its arguments v415 and v286 and creates a new value v600:
The second one simplifies a load following a store: (Load p (Store p x
_)) => x. The load is forwarded: the stored value replaces it and no memory
access remains. It matches v174. It notices that v600 and v173 are the
same address and replaces v174 with a copy of v442:
To optimize it away, we also apply three rewriting rules:
The first one also adds a shortcut when loading through a move, but
without an offset: (Load p (Move p src mem)) => (Load src mem). This rewrites v416
to use arguments from v286:
The second rule forwards a value stored one step earlier, skipping over a
store to another address: (Load p (Store q _ (Store p x _))) => x. This
matches v416: x is v542, p is v22 (&a16), q is v173
(&a16[8]), and p and q do not overlap for uint64.
In practice
Most of these rules already exist in generic.rules. They use
conditions to validate their context: ssa.IsSamePtr() for the same address,
ssa.Disjoint() for addresses that do not overlap. The rule forwarding a stored
value to a load already exists with three variants looking through several other
stores. Here are the two we need:
There is no generic rule to cancel two byte swaps, but the AMD64 lowering
pass includes this rule:
(BSWAP(Q L)(BSWAP(Q L)p))=>p
After switching to Go s development branch and adding the missing
rule, the generated assembly code is worse than with Go 1.26.8,
even though our additional rule slightly improves the situation at the end:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z; Push the stack (16 bytes):; 0(SP) a16 [16]bytePUSHQBPMOVQSP,BPSUBQ$16,SPCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop here; The four forwarded bytes: the low half of input.addr.lo is taken apart and; put back together in registersMOVQBX,DX; DX = input.addr.loSHRQ$24,BX; BX = input.addr.lo >> 24MOVQDX,SI; SI = input.addr.loSHRQ$16,DX; DX = input.addr.lo >> 16MOVQSI,DI; DI = input.addr.lo, kept for the packSHRQ$8,SI; SI = input.addr.lo >> 8MOVBLZXDIB,R8; R8 = byte(input.addr.lo)MOVBLZXSIB,SI; SI = byte(input.addr.lo >> 8)SHLQ$8,SIORQR8,SI; SI = two low bytes of input.addr.loMOVBLZXDL,DX; DX = byte(input.addr.lo >> 16)SHLQ$16,DXORQSI,DXMOVBLZXBL,BX; BX = byte(input.addr.lo >> 24)SHLQ$24,BXORQDX,BX; BX = input.addr.lo & 0xffffffff; Pack: byteorder.BEPutUint64(a16[:8], input.addr.hi); byteorder.BEPutUint64(a16[8:], input.addr.lo)MOVBEQAX,net/netip a16(SP)MOVBEQDI,net/netip a16+8(SP); The four other bytes of input.addr.lo, read one by one from a16MOVBLZXnet/netip a16+11(SP),DX; a16[11]SHLQ$32,DXORQDX,BXMOVBLZXnet/netip a16+10(SP),DX; a16[10]SHLQ$40,DXORQDX,BXMOVBLZXnet/netip a16+9(SP),DX; a16[9]SHLQ$48,DXORQDX,BXMOVBLZXnet/netip a16+8(SP),DX; a16[8]SHLQ$56,DX; output.z = netip.z6nozMOVQnet/netip z6noz(SB),CX; output.addr.hi = byteorder.BEUint64(a16[:8])MOVBEQnet/netip a16(SP),AX; output.addr.lo assembled from the previous stepsORQDX,BXend:LEAVEQRET// return value = Addr hi: AX, lo: BX, z: CX
The rule loading through a move, added in Go 1.27, introduced this regression.
Out of order
Let s not give up now! In reality, the rewriting rules run before memcombine,
notably in the late opt pass. At this point, the inlined versions of
BEPutUint64() and BEUint64() still expand to sixteen byte stores and sixteen
byte loads, matching their source code:
funcBEUint64(b[]byte)uint64_=b[7]// bounds check hint to compiler; see golang.org/issue/14808returnuint64(b[7])uint64(b[6])<<8uint64(b[5])<<16uint64(b[4])<<24uint64(b[3])<<32uint64(b[2])<<40uint64(b[1])<<48uint64(b[0])<<56
Let s follow two bytes of output.addr.lo: addr[15] and addr[11]. Here is
a simplified SSA form before late opt:
The first rule loads through the move: (Load (OffPtr [o] p) (Move p src mem))
=> (Load (OffPtr [o] src) mem). It matches both loads, which now read a16
with the memory state before the copy:
The second rule shortcuts a load following a store: (Load p (Store p x _)) =>
x. It matches v435, as v282 stores a16[15]. It does not match v481:
v235 stores a16[11] four stores earlier in the chain, while the variants of
this rule look through three stores at most.
The same happens to the other bytes: the rule forwards the four bytes stored
last, a16[12] to a16[15]. The twelve other loads now read a16 instead of
addr.
BEUint64() becomes a chain of Or64, each one adding a byte shifted into
place. memcombine is a pass written in Go, not a set of rewrite
rules. It starts from the last Or64 of the chain and collects up to eight
terms. If each term is a byte load, extended to 64 bits and shifted, and if the
eight loads read consecutive addresses from the same pointer with the same
memory state, it replaces the whole chain with a single 64-bit load and a byte
swap. Otherwise, it tries again with four, then two terms, and from each
intermediate Or64. Here is the loop checking each term in a simplified version
of combineLoads():
From v520, four of the eight terms are forwarded bytes, not loads from memory,
and memcombine can t combine them. It doesn t merge the four remaining loads
either, as they sit on top of the forwarded bytes.
Back in order
In summary, the rewriting rules run too early to be effective. A quick
workaround exists: run an earlier round of memcombine before late opt. After
this change, the generated code for the helper is back to the
shortest possible version:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Next steps
I think Go maintainers would reject this change because of the additional
memcombine pass. Instead, I plan to publish this blog post and bring up the
subject again as a follow-up to issue #54365. Either the sheer complexity and
the Go 1.27 regression convince the maintainers that adding a To6() method is
simpler and more efficient, or they advise me on how to move forward. Either
way, digging into this subject taught me a lot about the Go compiler!
IPv4-mapped IPv6 addresses let you handle only IPv6 addresses in your code
and keep conversions at a few well-defined boundaries. I use them in
Akvorado.
This is not strictly equivalent. The zero value becomes :: while it would
make more sense to leave it untouched.
To avoid catastrophic bugs when netip.Addr s layout changes, you must add
tests to detect it. This is more dangerous if you put this code in a
package. Either ask users to run the tests themselves, or detect the change
at run time and panic. Hiding this optimization behind a build tag would
make users aware of this potential trap.
I produced the assembly code with GOTOOLCHAIN=go1.26.8 GOAMD64=v3 ./go-asm
'\.asm' from the companion repository, then edited it a bit to keep this
article from turning into an endless rabbit hole. Due to an unfortunate
sequence of events, we switch between versions: Go 1.27 introduced a
regression that blurs the point of this article.
The function is short enough for the compiler to inline it, so the assembly
code may vary depending on the surrounding code.
MOVBEQ requires GOAMD64=v3, matching the x86-64-v3
microarchitecture from 2013. Otherwise, the compiler translates
BEPutUint64() to BSWAPQ+MOVQ and BEUint64() to MOVQ+BSWAPQ.
When the call is used as a statement, a struct literal alone is invalid. The
patch then turns it into _ = netip.Addr .
The compiler can also write an HTML file with the result of each pass:
$ GOSSAFUNC=AddrTo6Safe\> GOTOOLCHAIN=go1.26.8\> GOAMD64=v3gobuild-a.
dumped SSA for AddrTo6Safe,1 to ./ssa.html
Source line numbers in parentheses follow value identifiers, but I removed
them from the examples. The SSA form also features branches, but we don t
need them to understand our optimizations.
netip.Addr features an Unmap()
method returning the unwrapped IPv4 contained in an IPv4-mapped IPv6
address: from ::ffff:203.0.113.10 or ::ffff:cb00:710a, it returns
203.0.113.10.1 There is no Map() or To6() method for the reverse
direction. Such a method is trivial to implement, but Go maintainers have
rejected it on the grounds that users should write
netip.AddrFrom16(ip.As16()) and let the compiler optimize it.2 Today,
this pattern is eight times slower than a native method. How can we teach the
compiler to optimize this sequence?
The alternatives
Let's explore three ways to implement the map semantics for netip.Addr. My
favorite is to add it to the Go standard library. Go maintainers prefer a small
external helper chaining netip.AddrFrom16() and netip.Addr.As16(), hoping
the compiler eventually optimizes it. The unsafe package
opens a third path, with the same performance as the first solution.
Modifying the Go standard library
Internally, netip.Addr stores any IP address as a
128-bit value with an extra field z to encode the family and the zone:
typeAddrstructaddruint128zunique.Handle[addrDetail]typeaddrDetailstructisV6bool// IPv4 is false, IPv6 is true.zoneV6string// != "" only if IsV6 is true.var(z0unique.Handle[addrDetail]z4=unique.Make(addrDetail )z6noz=unique.Make(addrDetailisV6:true ))
AddrFrom4() encodes an IPv4 address as an
IPv4-mapped IPv6 address and sets z to the unique value z4:
// AddrFrom4 returns the address of the IPv4 address given by the bytes in addr.funcAddrFrom4(addr[4]byte)AddrreturnAddraddr:uint1280,0xffff00000000uint64(addr[0])<<24uint64(addr[1])<<16uint64(addr[2])<<8uint64(addr[3]) ,z:z4,
Unmap() turns an IPv4-mapped IPv6 address into an
IPv4 address by setting the z field to z4:
Implementing the reverse direction inside the Go standard library is trivial: we
set the z field to z6noz if the address is IPv4.
// To6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.func(ipAddr)To6()Addrifip.Is4()ip.z=z6nozreturnip
Update (2026-10)
Instead of patching Go, we can use the -overlay flag of go
build to hijack any package, including the standard library. In our case,
it can add To6() to net/netip. Yet it is
cumbersome:3 the flag expects a JSON file mapping absolute
paths in GOROOT to replacement files, and you need to add it to every go
command.
As a helper
We can't access the z field from outside the net/netip package. Instead, we
build a small helper around the netip.AddrFrom16(ip.As16()) pattern:
// AddrTo6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.funcAddrTo6(ipnetip.Addr)netip.Addrifip.Is4()ip=netip.AddrFrom16(ip.As16())returnip
As an unsafe function
Another solution uses the unsafe package to alter the Addr struct through
a proxy with the same memory layout:4
// addrProxy has the same memory layout as netip.Addr.typeaddrProxystructaddr[2]uint64// netip.uint128zunsafe.Pointer// unique.Handle[netip.addrDetail]var(anyIPv6=netip.IPv6Unspecified()netipZ6noz=(*addrProxy)(unsafe.Pointer(&anyIPv6)).z)// AddrTo6 maps an IPv4 address to an IPv4-mapped IPv6 address. It returns an// IPv6 address unmodified.funcAddrTo6(ipnetip.Addr)netip.Addrif!ip.Is4()returnip(*addrProxy)(unsafe.Pointer(&ip)).z=netipZ6nozreturnip
Benchmarks
On my computer, with Go 1.27.1, the standard library solution costs 0.88 ns per
operation, while the solution favored by Go maintainers costs 7.14 ns. The
unsafe solution matches the performance of the first one.
Assembly code
Let's check the assembly code the compiler generates for each solution.5
The one built into the standard library looks like this:6
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Go's assembly language is not a direct representation of the underlying
machine language: it operates on a semi-abstract instruction set derived from
Plan 9's assembler. It has four pseudo-registers: FP (frame pointer
for function arguments), PC (program counter), SB (static base pointer for
global symbols), and SP (stack pointer). It also has architecture-specific
registers like AX, CX, DX, BX, SI, DI, and R8 to R15.
Instructions storing data use their last argument as the destination.
Instructions can carry an explicit size suffix: MOVB moves a byte, MOVW 16
bits, MOVL 32 bits, and MOVQ 64 bits. In the example above, the first
instruction compares the 64-bit value z4 with the CX register.
The unsafe solution looks almost the same:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnetipZ6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
The helper solution has far more instructions. To understand why, let's look at
the code for As16() and
AddrFrom16(). They are short enough for the compiler
to inline them.
We can already guess the pattern to optimize: the code packs the IP address into
an array, copies it, then unpacks it. If we inline the Go code by hand, we get:
Unfortunately, as of Go 1.26.8, the compiler is not smart enough to do the same:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z; Push the stack (32 bytes):; 0(SP) addr netip.uint128; 16(SP) a16 [16]bytePUSHQBPMOVQSP,BPSUBQ$32,SPCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop here; Pack: byteorder.BEPutUint64(a16[:8], input.addr.hi); byteorder.BEPutUint64(a16[8:], input.addr.lo)MOVBEQAX,net/netip a16+16(SP)MOVBEQBX,net/netip a16+24(SP); addr = a16, 16 bytes at once through the vector register X0MOVUPSnet/netip a16+16(SP),X0MOVUPSX0,net/netip addr(SP); CX = netip.z6nozMOVQnet/netip z6noz(SB),CX; Unpack: output.addr.hi = byteorder.BEUint64(addr[:8]); output.addr.lo = byteorder.BEUint64(addr[8:])MOVBEQnet/netip addr(SP),AXMOVBEQnet/netip addr+8(SP),BXend:ADDQ$32,SPPOPQBPRET// return value = Addr hi: AX, lo: BX, z: CX
The compiler does a decent job on the byte shuffling: the eight byte stores of
BEPutUint64() become a single MOVBEQ, which stores a register byte-swapped.
The eight byte loads of BEUint64() become a single MOVBEQ the other way
round.7 Three groups of instructions remain: a pack, a copy, and an
unpack.
Hacking the Go compiler
The Go compiler has several phases:
The compiler converts the syntax tree and its types into its own intermediate
representation (IR). This process, called "noding," goes through
a serialization format named unified IR.
This phase runs two steps: order of evaluation decomposes complex
statements into simpler ones, and desugaring transforms higher-level Go
constructs, like switch or channels, into more primitive instructions or
calls to the runtime.
The compiler rewrites the SSA form into machine-specific variants,
allocates registers, and applies more optimization passes. At the end, the
assembler turns the generated instructions into machine code.
The hammer
My first idea is to replace occurrences of netip.AddrFrom16(ip.As16()) with
netip.Addr addr: ip.addr, z: netip.z6noz as early as possible, during the
"noding" process. Before that, the type checking phase prevents
us from accessing unexported struct fields.
Go 1.27 introduced a convenient debug option to dump the IR of a function at
interesting points during compilation:
$ GOTOOLCHAIN=go1.27.1GOAMD64=v3gobuild-a-gcflags="-d=astdump=AddrTo6Safe".
Writing text ast output for AddrTo6Safe to AddrTo6Safe.astWriting html ast output for AddrTo6Safe to AddrTo6Safe.htmlWriting html syntax output for AddrTo6Safe to AddrTo6Safe.syntax.html
In the HTML file, the first column shows the IR as it comes out of noding:
In the body of the if statement, we spot the calls to the method
netip.Addr.As16() and to the function netip.AddrFrom16(). Our goal is to
patch them with a struct literal:
In noder's reader.go, the expr() method builds the IR tree for
an expression. At the end of the exprCall case, we add a call to a
rewriteAddrFrom16As16() function. It takes the current node and returns the
struct literal on success, or nil if the rewrite is not possible. First, we
check that we have the expected pattern: a call to the netip.AddrFrom16()
function with a call to the netip.Addr.As16() method as its only argument:
Have a look at the complete patch.8 We can test it
with the following commands:
$ cdsrc
$ ./make.bash
Building Go cmd/dist using /usr/lib/go-1.27. (go1.27.1 linux/amd64)Building Go toolchain1 and bootstrap cmd/go (go_bootstrap) using /usr/lib/go-1.27.Building Go toolchain2 using go_bootstrap and Go toolchain1.Building Go toolchain3 and commands using go_bootstrap and Go toolchain2.Checking command staleness for linux/amd64.---Installed Go for linux/amd64 in /home/bernat/code/free/goInstalled commands in /home/bernat/code/free/go/bin*** You need to add /home/bernat/code/free/go/bin to your PATH.$ exportPATH=$PWD/../bin:$PATH$ goversion
go version go1.28-devel_9834516e20 Sat Sep 12 08:23:11 2026 -0700 linux/amd64$ gotestnet/netip/...
ok net/netip 0.224s$ cd../../go-netip-addrto6
$ gotest.
ok github.com/vincentbernat/go-netip-addrto6 0.062s
The generated code for the helper is now the shortest possible version!
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Go maintainers are unlikely to accept this change. It relies on the internal
structure of net/netip.Addr. It's an ugly hack in the noder, whose job is to
faithfully translate the type-checked AST into the IR. And it's harder to
maintain than adding a To6() method.
The screwdriver
The right place for such an optimization is the generic SSA phase. One of
the last machine-independent passes is memcombine. With the appropriate debug
flag, the compiler dumps the SSA form after this pass:9
The result of the memcombine pass follows the same structure as the assembly
code for AddrTo6Safe()we looked at earlier: two stores,
one move, and two loads we would like to optimize away.
Each line features a value identifier (v442), an operation with its type
(Bswap64 <uint64>), and its arguments (v490).10 Values are the basic
building blocks of SSA and are defined exactly once. Square brackets enclose
integer parameters ([8]) and curly braces contain auxiliary arguments
( netip.addr ). Operations writing to memory produce a new memory state. Every
memory operation takes the current state as its last argument, which keeps them
in order.
To simplify this code, we could apply three rewriting rules:
The first one adds a shortcut when loading through a move: (Load (OffPtr
[o] p) (Move p src mem)) => (Load (OffPtr [o] src) mem). This matches v174
with its arguments v415 and v286 and creates a new value v600:
The second one simplifies a load following a store: (Load p (Store p x
_)) => x. The load is forwarded: the stored value replaces it and no memory
access remains. It matches v174. It notices that v600 and v173 are the
same address and replaces v174 with a copy of v442:
To optimize it away, we also apply three rewriting rules:
The first one also adds a shortcut when loading through a move, but
without an offset: (Load p (Move p src mem)) => (Load src mem). This rewrites v416
to use arguments from v286:
The second rule forwards a value stored one step earlier, skipping over a
store to another address: (Load p (Store q _ (Store p x _))) => x. This
matches v416: x is v542, p is v22 (&a16), q is v173
(&a16[8]), and p and q do not overlap for uint64.
In practice
Most of these rules already exist in generic.rules. They use
conditions to validate their context: ssa.IsSamePtr() for the same address,
ssa.Disjoint() for addresses that do not overlap. The rule forwarding a stored
value to a load already exists with three variants looking through several other
stores. Here are the two we need:
There is no generic rule to cancel two byte swaps, but the AMD64 lowering
pass includes this rule:
(BSWAP(Q L)(BSWAP(Q L)p))=>p
After switching to Go's development branch and adding the missing
rule, the generated assembly code is worse than with Go 1.26.8,
even though our additional rule slightly improves the situation at the end:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.z; Push the stack (16 bytes):; 0(SP) a16 [16]bytePUSHQBPMOVQSP,BPSUBQ$16,SPCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop here; The four forwarded bytes: the low half of input.addr.lo is taken apart and; put back together in registersMOVQBX,DX; DX = input.addr.loSHRQ$24,BX; BX = input.addr.lo >> 24MOVQDX,SI; SI = input.addr.loSHRQ$16,DX; DX = input.addr.lo >> 16MOVQSI,DI; DI = input.addr.lo, kept for the packSHRQ$8,SI; SI = input.addr.lo >> 8MOVBLZXDIB,R8; R8 = byte(input.addr.lo)MOVBLZXSIB,SI; SI = byte(input.addr.lo >> 8)SHLQ$8,SIORQR8,SI; SI = two low bytes of input.addr.loMOVBLZXDL,DX; DX = byte(input.addr.lo >> 16)SHLQ$16,DXORQSI,DXMOVBLZXBL,BX; BX = byte(input.addr.lo >> 24)SHLQ$24,BXORQDX,BX; BX = input.addr.lo & 0xffffffff; Pack: byteorder.BEPutUint64(a16[:8], input.addr.hi); byteorder.BEPutUint64(a16[8:], input.addr.lo)MOVBEQAX,net/netip a16(SP)MOVBEQDI,net/netip a16+8(SP); The four other bytes of input.addr.lo, read one by one from a16MOVBLZXnet/netip a16+11(SP),DX; a16[11]SHLQ$32,DXORQDX,BXMOVBLZXnet/netip a16+10(SP),DX; a16[10]SHLQ$40,DXORQDX,BXMOVBLZXnet/netip a16+9(SP),DX; a16[9]SHLQ$48,DXORQDX,BXMOVBLZXnet/netip a16+8(SP),DX; a16[8]SHLQ$56,DX; output.z = netip.z6nozMOVQnet/netip z6noz(SB),CX; output.addr.hi = byteorder.BEUint64(a16[:8])MOVBEQnet/netip a16(SP),AX; output.addr.lo assembled from the previous stepsORQDX,BXend:LEAVEQRET// return value = Addr hi: AX, lo: BX, z: CX
The rule loading through a move, added in Go 1.27, introduced this regression.
Out of order
Let's not give up now! In reality, the rewriting rules run before memcombine,
notably in the late opt pass. At this point, the inlined versions of
BEPutUint64() and BEUint64() still expand to sixteen byte stores and sixteen
byte loads, matching their source code:
funcBEUint64(b[]byte)uint64_=b[7]// bounds check hint to compiler; see golang.org/issue/14808returnuint64(b[7])uint64(b[6])<<8uint64(b[5])<<16uint64(b[4])<<24uint64(b[3])<<32uint64(b[2])<<40uint64(b[1])<<48uint64(b[0])<<56
Let's follow two bytes of output.addr.lo: addr[15] and addr[11]. Here is
a simplified SSA form before late opt:
The first rule loads through the move: (Load (OffPtr [o] p) (Move p src mem))
=> (Load (OffPtr [o] src) mem). It matches both loads, which now read a16
with the memory state before the copy:
The second rule shortcuts a load following a store: (Load p (Store p x _)) =>
x. It matches v435, as v282 stores a16[15]. It does not match v481:
v235 stores a16[11] four stores earlier in the chain, while the variants of
this rule look through three stores at most.
The same happens to the other bytes: the rule forwards the four bytes stored
last, a16[12] to a16[15]. The twelve other loads now read a16 instead of
addr.
BEUint64() becomes a chain of Or64, each one adding a byte shifted into
place. memcombine is a pass written in Go, not a set of rewrite
rules. It starts from the last Or64 of the chain and collects up to eight
terms. If each term is a byte load, extended to 64 bits and shifted, and if the
eight loads read consecutive addresses from the same pointer with the same
memory state, it replaces the whole chain with a single 64-bit load and a byte
swap. Otherwise, it tries again with four, then two terms, and from each
intermediate Or64. Here is the loop checking each term in a simplified version
of combineLoads():
From v520, four of the eight terms are forwarded bytes, not loads from memory,
and memcombine can't combine them. It doesn't merge the four remaining loads
either, as they sit on top of the forwarded bytes.
Back in order
In summary, the rewriting rules run too early to be effective. A quick
workaround exists: run an earlier round of memcombine before late opt. After
this change, the generated code for the helper is back to the
shortest possible version:
// AX = input.addr.hi, BX = input.addr.lo, CX = input.zCMPQnet/netip z4(SB),CX; check "z" if this is an IPv4 addressJNEend; if not, stop hereMOVQnet/netip z6noz(SB),CX; CX = netip.z6nozend:RET// return value = Addr hi: AX, lo: BX, z: CX
Next steps
I think Go maintainers would reject this change because of the additional
memcombine pass. Instead, I plan to publish this blog post and bring up the
subject again as a follow-up to issue #54365. Either the sheer complexity and
the Go 1.27 regression convince the maintainers that adding a To6() method is
simpler and more efficient, or they advise me on how to move forward. Either
way, digging into this subject taught me a lot about the Go compiler!
Update (2026-10)
I opened issue #81994 to propose Addr.To6(). Give it a if you want
it in Go!
IPv4-mapped IPv6 addresses let you handle only IPv6 addresses in your code
and keep conversions at a few well-defined boundaries. I use them in
Akvorado.
This is not strictly equivalent. The zero value becomes :: while it would
make more sense to leave it untouched.
I suppose Go maintainers keep it inconvenient on purpose: they don't want
random packages to patch the standard library or other packages.
To avoid catastrophic bugs when netip.Addr's layout changes, you must add
tests to detect it. This is more dangerous if you put this code in a
package. Either ask users to run the tests themselves, or detect the change
at run time and panic. Hiding this optimization behind a build tag would
make users aware of this potential trap.
I produced the assembly code with GOTOOLCHAIN=go1.26.8 GOAMD64=v3 ./go-asm
'\.asm' from the companion repository, then edited it a bit to keep this
article from turning into an endless rabbit hole. Due to an unfortunate
sequence of events, we switch between versions: Go 1.27 introduced a
regression that blurs the point of this article.
The function is short enough for the compiler to inline it, so the assembly
code may vary depending on the surrounding code.
MOVBEQ requires GOAMD64=v3, matching the x86-64-v3
microarchitecture from 2013. Otherwise, the compiler translates
BEPutUint64() to BSWAPQ+MOVQ and BEUint64() to MOVQ+BSWAPQ.
When the call is used as a statement, a struct literal alone is invalid. The
patch then turns it into _ = netip.Addr .
The compiler can also write an HTML file with the result of each pass:
$ GOSSAFUNC=AddrTo6Safe\> GOTOOLCHAIN=go1.26.8\> GOAMD64=v3gobuild-a.
dumped SSA for AddrTo6Safe,1 to ./ssa.html
Source line numbers in parentheses follow value identifiers, but I removed
them from the examples. The SSA form also features branches, but we don't
need them to understand our optimizations.
A friend wants to proofread your work-in-progress blog post, but its preview
only runs on localhost:8080. Several tools can help. Some run as a
commercial service, like ngrok or Cloudflare Quick Tunnels. Some are
self-hostable but require a specific client, like frp or localtunnel.
Some only require a plain SSH client but rely on a specific SSH server, like
sish. Let's implement a self-hosted solution with only OpenSSH and
nginx!
$ ssh-R0:localhost:8080http-over-ssh
Allocated port 41535 for remote forward to localhost:8080https://6J3jK1WmB15c6WmjW_X-Wg--1789928654@p41535.ssh.luffy.cx/
Basic setup
First, we forward connections from a port on a remote server to your local
service:
$ ssh-N-R0:localhost:8080web02.luffy.cx
Allocated port 41535 for remote forward to localhost:8080
When you specify 0 as the remote port, the server allocates a free port.
Then, we configure nginx to proxy requests from https://p41535.ssh.luffy.cx to
http://127.0.0.1:41535:
Access control
The port is the only "secret"1 keeping the content confidential. Other
forwarding solutions add a random string to the domain name to prevent an
intruder from enumerating the possible values.
Thanks to ngx_http_secure_link_module, we can secure
this setup a bit. This module computes a hash2 over a set of values,
including a secret, and compares it with the hash from the request. The hash is
base64-encoded, so we cannot put it in the domain name, which is
case-insensitive. Instead, we put it in the URL as a username, along with its
expiration timestamp:3
https://6J3jK1WmB15c6WmjW_X-Wg--1789928654@p41535.ssh.luffy.cx/en/blog
hash expires port path
The client sends the username to the server with HTTP basic
authentication. This works with most HTTP clients, including curl.
Nginx exposes the username in the $remote_user variable. The module expects
the hash and the expiration timestamp separated by a comma. We use a map
directive to extract the two parts from $remote_user and join them with a
comma.4 We also give the module the string to hash. It contains the
expiration timestamp, the port, and a secret:
The module returns the status of the check in the $secure_link variable:
empty if the hashes do not match,
"0" if they match but the link has expired, or
"1" otherwise.
If the hash is incorrect or missing, we return a 401 error with a
WWW-Authenticate header to ask for credentials. If the link has expired, we
return a 410 error. We remove the Authorization header before forwarding the
request and add a few directives to proxy WebSocket connections.
Here is the complete configuration:5
Well, I suppose you are now saying: "Vincent, this is not very convenient! I'll stick
with ngrok if you don't mind." Okay, I hear you. Let's write a helper script.
Helper script
The main difficulty is finding the ephemeral port that OpenSSH allocates, as it
does not appear in any environment variable.6 To work around this obstacle,
we look for the ancestor sshd-session processes:7
With this solution, I only rely on OpenSSH and nginx, two pieces of software
already running on this server. One short command gives me a self-hosted tunnel
and a URL to share. To try it, grab the complete helper script, which
includes a few minor improvements. If you run NixOS, as any person of taste
would, have a look at my http-over-ssh.nix instead.
Update (2026-10)
This post was widely discussed on Hacker News.
Update (2026-10)
I have since switched to Caddy, which does not include a module to check the
validity of a URL. Instead, Caddy queries a local HTTP service written in
Go through the forward_auth directive. As a bonus, this lets me put
the token in the domain name.
Since the kernel allocates it from the local port range, its entropy is low.
Moreover, on Linux, we lose one more bit because the kernel favors odd
ports when it picks a random free port.
The module relies on MD5. Its security is weak but good enough for this
use.
We need an expiration date because a later session could reuse the port,
and we have no way to detect this case.
The username could use a comma directly instead of a double dash. But some
applications do not recognize the URL correctly, making it harder to share.
This configuration exposes any TCP port listening on 127.0.0.1 or
0.0.0.0 to anyone with the secret, bypassing most firewall rules. You
could strengthen it by limiting the server_name regex to the ephemeral
port range.
One SSH session can contain several tunnels, and the client can add or
remove them at any time. This is unlike tun device forwarding (ssh -w),
which gets its own SSH_TUNNEL environment variable.
Since OpenSSH 9.8, sshd-session is the name of the helper handling the
session. With older versions, look for sshd instead.
We need sudo because the sshd-session process dropped its privileges.
The kernel then marks it as not dumpable, and its /proc/PID/fd directory
belongs to root. Without access to this directory, ss cannot
find which process owns a socket.
In 2016, I removed Google Analytics from this blog to avoid being
complicit in feeding the biggest machine for harvesting personal data. Instead,
I relied on GoAccess to analyze my server logs.1 For the past couple
of years, the statistics have made no sense, despite my attempts to filter bots:
AI scrapers inflate the number of visitors to around 2,000 per
day. Eventually, I settled on GoatCounter, an open-source, privacy-friendly
web analytics platform. I replaced the JavaScript client to filter bots more
aggressively and added a CSS fallback. To improve reliability, I implemented a
local proxy running on each of the five web servers serving this blog. The rest
of this post details how these pieces fit together and how I deploy them on
NixOS.
Why GoatCounter?
GoatCounter does not collect personal data: instead of storing the reader s
IP address or relying on cookies, it creates a session identifier valid for 8
hours from the user agent and the IP address. Its feature set is modest but
sufficient for a blog. If you want to look at the interface, GoatCounter s
author runs a public instance for his site. A hosted
version lets you try it before running your own instance. With a single binary
and an SQLite database, GoatCounter is one of the lightest self-hosted
solutions. Privacy-friendly alternatives, in increasing order of complexity,
include Umami, Plausible, and Rybbit.
Custom JavaScript client
GoatCounter includes a small JavaScript client 2,189 bytes minified and
gzipped. It ships some features I don t use: a visitor counter, tracking clicks,
configurable settings, etc. I replace it with this function to register a hit:
If a reader has disabled JavaScript in their browser, I record the hit using a
CSS image. The :hover pseudo-class loads it only after an interaction, another
trick stolen from Bear Blog. About 2% of my visitors fit into this
bucket.3
<!DOCTYPE html><htmllang="en"class="nojs"><head><script>// The JavaScript code for this blog requires ES6if("noModule"inHTMLScriptElement.prototype)document.documentElement.classList.remove("nojs");</script></head><body><!-- ... --><style>.nojsbody:hoverborder-width:0;border-image:url('/count?p=/en/blog/2026-kpi-goodhart&t=Building...&r=NoJS&e=false');</style></body></html>
Where GoAccess reported around 2,000 visitors a day, GoatCounter counts fewer
than 200 humans.4 I assume AI scrapers use a low-effort approach: if the
content is available without barriers, as on this blog, they don t spawn a
complex mechanized browser that could trigger a page view. Even crawlers running
JavaScript, like Googlebot with its headless Chromium, do not
interact with the page and never trigger the events I listen
to. The interaction-based proof of humanity I use is likely to keep
working.5
Local proxy
Five servers across the world in Europe and in North
America serve the content of this website, but GoatCounter runs on only
one of them. To avoid losing track of visitors when GoatCounter is down, I run a
local proxy listening on the same /count endpoint. On each server, it stores
the hits in memory with a buffer large enough to survive several days of
downtime. It sends them in batches to the upstream backend using the
/api/v0/count authenticated endpoint.
Servers on a map. web02 is in Paris, web03 in Helsinki, web04 in Nuremberg,
web05 in Ashburn, web06 in Chicago.
I proposed the code for the proxy in pull request #909. GoatCounter s
maintainer declined to maintain so much code for such a niche use case. As a
fellow open-source developer, I often hold the same position for my own
projects: a one-time contributor effort may translate into a long-term
maintainer commitment.
I expose the endpoint for the proxy on the domain of this website to evade ad
blockers. This sounds like I don t respect the reader s choice, but as
GoatCounter is privacy-friendly, I find it acceptable.
Deploying on NixOS
My web servers run NixOS, a declarative Linux distribution with built-in
configuration management. I manage this small fleet with Colmena, a
stateless deployment tool for NixOS. My configuration is available on
GitHub.
Deploying applications in containers
For better isolation, each application runs inside an ephemeral lightweight
container, powered by systemd-nspawn. Each container runs a stripped-down
NixOS instance. A module wraps NixOS s containers options to
avoid repeating the same options for each application.6 The containers
share their network namespace with the host: the additional isolation is not
worth the increased complexity. For a smaller footprint, I also disable a few
non-essential services.
To configure a GoatCounter instance running in a container and listening on
127.0.0.4:8088, we import the module7 and declare the container in the
config.luffy.containers attribute set:
As the containers are ephemeral, we need to keep persistent data in directories
on the host. We add a mounts option and ask NixOS s containers to expose the
configured directories through the bindMounts option.
For example, to persist GoatCounter s database in the /var/db/goatcounter
directory on the host, we add the directory to the mounts option and alter the
service definition to tell GoatCounter where the database is.
A container may also need some secrets. Colmena can upload secrets without
storing them in the Nix store. We add a keys option to our containers. It
takes an attribute set mapping secret names to the commands to populate them.
Then, the module declares the required secrets to Colmena in the
deployment.keys option, makes the container depend on the presence of the
secrets, and exposes them to the container.
config, lib,... :letcfg= config.luffy.containers;in
options.luffy.containers= lib.mkOption type= lib.types.attrsOf (lib.types.submodule options=keys= lib.mkOption type= lib.types.attrsOf (lib.types.listOf lib.types.str);default= ;description="Secrets, as a command to run locally. They are mounted in /etc."; ; ; ); ;config=# Colmena uploads each secret in /var/keys and make them available# to the group "keys".
deployment.keys= lib.concatMapAttrs
(_: container: lib.mapAttrs
(_: keyCommand:inherit keyCommand;group="keys";permissions="0640";destDir="/var/keys"; )
container.keys)
cfg;# The container can only start if the required secrets are available.
systemd.services= lib.mapAttrs'
(name: container:letunits=map(key:"$ key-key.service")(lib.attrNames container.keys);in
lib.nameValuePair "container@$ name"requires= units;after= units; )
cfg;# Mount each secret inside the container.containers= lib.mapAttrs
(name: container:bindMounts= lib.mapAttrs'
(key: _: lib.nameValuePair "/etc/$ key"hostPath="/var/keys/$ key";isReadOnly=true; )
container.keys; )
cfg; ;
For example, GoatCounter needs credentials to download the GeoIP database. I
provide a local command to fetch the secret from my password manager and expose
it inside the container through the /etc/goatcounter.env environment file.
GoatCounter server
Nixpkgs already packages GoatCounter. By overriding the src and vendorHash
attributes, I reuse its definition for my custom version with the proxy:
I wrote a NixOS module to encapsulate GoatCounter: the
container definition, the service definition, and the secrets. The module
accepts the following options: package, serve.enable, serve.listenAddress,
serve.port, and serve.databaseFile. I already detailed the container
configuration in the previous section. In the end, I chose not to reuse the
GoatCounter module from NixOS: it s small, so it s better to insulate my module
from unexpected future changes.
config, pkgs, lib,... :letcfg= config.luffy.goatcounter;databaseDirectory=builtins.dirOf cfg.serve.databaseFile;chown="$ pkgs.coreutils/bin/chown -R";in
config.luffy.containers.goatcounter=
config.systemd.services.goatcounter=description="GoatCounter Web Analytics";wantedBy=["multi-user.target"];serviceConfig=EnvironmentFile="/etc/goatcounter.env";SupplementaryGroups=["keys"];DynamicUser=true;Restart="always";ExecStart= lib.escapeShellArgs [(lib.getExe cfg.package)"serve""-listen=$ cfg.serve.listenAddress:$ toString cfg.serve.port""-tls=none""-db=sqlite+$ cfg.serve.databaseFile""-automigrate"];# Transfer database ownership to dynamically assigned user "goatcounter".ExecStartPre="+$ chown goatcounter:goatcounter $ databaseDirectory";ReadWritePaths= databaseDirectory; ; ; ;
The following snippet configures GoatCounter to listen on 127.0.0.4:8088:
GoatCounter proxy
The same NixOS module configures the local proxy, with the
following options: proxy.enable, proxy.listenAddress, proxy.port, and
proxy.site the site receiving the batches of page views. The local proxy has
no persistent data, but it needs the API key to authenticate to the main
GoatCounter instance: its container uses the keys option but not the mounts
option.
config, pkgs, lib,... :letcfg= config.luffy.goatcounter;keyCommand= _:[" "];in
config.luffy.containers.goatcounter-proxy= keys."goatcounter-proxy.env"= keyCommand "GOATCOUNTER_API_KEY"; config.systemd.services.goatcounter=description="GoatCounter Proxy.";wantedBy=["multi-user.target"];serviceConfig=EnvironmentFile="/etc/goatcounter-proxy.env";SupplementaryGroups=["keys"];DynamicUser=true;Restart="always";ExecStart= lib.escapeShellArgs [(lib.getExe cfg.package)"proxy""-site=$ cfg.proxy.site""-listen=$ cfg.proxy.listenAddress:$ toString cfg.proxy.port""-ratelimit=10/1"# 10 requests per second per IP]; ; ; ;
For each server, I enable the local proxy with the following snippet. The
nginx configuration shown earlier exposes the /count endpoint under the same
domain as my blog.
Backup of the SQLite database with Litestream
Litestream is a streaming replication tool for SQLite databases. It
compresses the changes committed to the write-ahead log (WAL) next to the
database and sends them to a remote destination. I encapsulate its configuration
in a NixOS module, which takes an attribute set databases
mapping a name to the path of the database to back up.
Litestream also runs in a container. I mount the databases to replicate, as well
as the secrets to push the backups to a Hetzner storage box using SFTP:
We can restore the database from the backup with a few shell commands. First, we
stop the containers. Then, we move the damaged database away, invoke litestream
restore from the right environment, and restart the containers.9
Ten years after removing Google Analytics, JavaScript-based analytics is
back on this blog, but without storing cookies or IP addresses, and without
involving a third party. I still write for myself first, notably because it lets
me dig into a topic and refer back to it years later. But knowing a bit more
about my fellow human readers is a nice bonus, even the ones disabling
JavaScript.
Nginx scrambles IP addresses before storing them, thanks to the ipscrub
nginx module.
GoatCounter already filters some bots based on the user agent or the IP
address. But AI scrapers lie about their user agent and hide behind
residential proxies.
Without JavaScript, I cannot send the real referrer. I insert NoJS
instead.
I am missing the humans reading the RSS feed. I am not comfortable adding a
tracking pixel, and bots are likely to fetch it, compromising the
statistics. I ll live without counting these readers.
In February 2025, I tested another CSS-only approach without the interaction
trick: each page loaded an empty image as a background. Over a month, it
recorded up to ten times fewer page views than the nginx logs, even after
removing user agents identifying as bots. Compared to this experiment,
GoatCounter counts about three times fewer views, 18 months later. As the
time ranges differ, this is not an apples-to-apples comparison, but it gives
a hint about how efficient bot filtering is.
A NixOS module is a function receiving the configuration of the whole
system as config and returning three attributes:
imports adds other modules to import,
options declares user-configurable settings, each with a type and a default value, and
config sets values for options declared by any module, like containers from NixOS.
If a module does not need to declare options, you can return the config attribute
set directly. When a module does not require any argument, you can define it as an attribute
set instead.
Most of the time, you don t need an explicit import. NixOS automatically
imports the modules shipped with Nixpkgs. For my own
modules, some machinery also imports them automatically.
Litestream warns against using the auto-recover option as
it can cause data loss. But I don t properly monitor my servers and I prefer
uninterrupted backups to a slight chance of losing the last few records.
In my case, the process is slow: around 20 minutes for a 20 MiB database.
You can test by restoring to a copy with the -o option, but you still need
to stop the Litestream container.
I am a heavy user of sidenotes:1 they keep optional content next to the
text instead of sending the reader to the bottom of the page and back. Tufte
CSS renders them without JavaScript but only accepts inline content. CSS
anchor positioning, now supported by recent browsers,2 is an
elegant alternative. Sidenotes can hold several blocks, still without
JavaScript, and fall back below the paragraph referencing them on narrow
viewports and older browsers.
In 2023, Eric Meyer demonstrated this technique in Nuclear Anchored
Sidenotes. The main improvement over other solutions is that the notes can
sit anywhere in the HTML document. You can place them after the paragraph
referencing them, as regular block elements for text browsers, screen readers,
feed readers, and reader mode to render them properly:
Rendering in Lynx, a text browser
When the viewport is too narrow or the browser does not support CSS anchor
positioning, you can style them so the reader can skip them or glance at them
without losing their position in the text:
Rendering below the paragraph on a narrow viewport
Once the viewport is large enough, they appear in the margin, at the same
vertical position as the matching reference mark, unless they would collide with
a previous sidenote, as in the example below:3
Rendering in the margin on a large viewport
The gist of CSS anchoring is to position an element relative to another
element the anchor. For the sidenotes, the anchor is the reference mark. I use
the following markup, with a data attribute to specify the anchor name:
The matching note is an <aside> element carrying the same data attribute for
the anchor name. We put it after the paragraph holding the reference mark:
<asiderole="note"id="sidenote-YYY"data-anchor="--lf-sn-YYY"><sup>1</sup><p>A first paragraph.</p><p>A second paragraph.</p></aside>
On a narrow viewport or when the browser is too old for CSS anchoring, we style
the sidenote, which stays below its paragraph, with a muted color:
aside[role="note"]margin-block:1rlh;color:#444;
On a wide viewport and when the browser is recent enough, we move the sidenote
to the right margin:
attr() extracts the anchor name for the reference mark from the data-anchor
attribute. It returns a string, unless we specify a CSS unit or a type, like
here: the browser parses the data attribute as a custom
identifier, which anchor-name validates as a dashed
identifier, a custom identifier starting with two
dashes.4
The note itself is absolutely positioned past the right edge of the main block.
It selects the matching reference mark as its anchor with position-anchor set
to the value of the data-anchor attribute. Each note is also an anchor named
--lf-sidenote. We use it to keep the next note from colliding with this one.
The anchor() CSS function lets us position the note s top
edge relative to its anchor: anchor(top) aligns the top edge of the note with
the top edge of the reference mark. It can also take another anchor as a
parameter: anchor(--lf-sidenote bottom) would align the top edge of the note
with the bottom edge of the closest preceding anchor named --lf-sidenote so
the previous note.5 Like attr(), anchor() accepts a fallback
value as its second parameter and use it when the named anchor does not exist.
The top property handles three cases, illustrated in the following diagram:
The three cases for the vertical position of a note
The first note s top edge aligns with the top edge of its reference mark: as
there is no previous note, anchor(--lf-sidenote bottom, -1rlh) + 1rlh
resolves to 0 and max() returns anchor(top).
When the reference mark of a later note sits above the bottom of the previous
note, plus some vertical space, the note goes below the previous one to avoid
a collision. max() returns anchor(--lf-sidenote bottom) + 1rlh.
Otherwise, the note s top edge aligns with the reference mark s top edge, as
max() returns anchor(top).
Have a look at the complete stylesheet, which also adapts the
reference mark to the location of the note: a arrow when the note sits below
the paragraph, a arrow when it moves to the margin. Gwern s Sidenotes In
Web Design lists more implementations and their trade-offs.
Some bloggers aim to write a post in 30 minutes. I planned to publish
three web-related articles this weekend. Instead, I spent an inordinate amount
of time elsewhere: about 15 commits on the build system, a pull request to
update CSS highlighting for nested selectors in Pygments, and a
small correction to MDN s article on the anchor() CSS function. The
SVG illustration took a bit less than an hour and the article itself a handful
of hours. The attr() function came in after I thought inline style looks
ugly, isn t there a better way? But, hey, I still think this is worth it!
My PhD advisor told me this is unwise.
The first bits of anchor positioning are supported from Chrome 125 (May 2024), Firefox 147 (January 2026), and Safari 26 (September 2025).
Before Safari 26.5, sidenotes may collide due to a bug in how dependency
chains are handled. You can detect this situation with some JavaScript.
It is, however, not needed in the solution described here as we depend on a
more recent feature.
If you noticed the runt in the first note, I share your pain and lament that
Firefox does not implement text-wrap: pretty.
Typed attr() is supported from Chrome 133 (February 2025),
Firefox 155 (September 2026), and Safari 27 (September 2026). Check Una
Kravets article for details. To support more
browsers, you can inline the anchor name and the position anchor directly in
the HTML:
The exact rule for the target anchor element is more complex: if an
ancestor of [the note] satisfies the following conditions, return the
nearest such element to [the note]. Otherwise, return the last element in
tree order that satisfies the conditions. One of these conditions is that
[the candidate] is an acceptable anchor element for [the note], which
requires that [the candidate] is laid out strictly before [the note],
where the relevant clause is that [the candidate] is either not absolutely
positioned or occurs earlier in the flat tree order than [the note].
Warning
This post contains interactive examples. To visualize and interact
with them, you need to leave your RSS reader.
Imagine you rent office space for a three-day event. You quickly set up a few
Ethernet switches and tape some cables on the floor to get everyone online.
Unfortunately, Stan, your clumsiest coworker, kicks out a cable every time he
gets up for coffee. You could add extra cables, but then you d get a broadcast
storm: Ethernet packets that loop and multiply until nothing else gets through.
That s where the spanning tree protocol (STP) comes in. STP blocks just enough
of your spare cables to leave a loop-free tree. When Stan strikes again, it
rebuilds the tree in a second, leaving some time for Blobby, your one-person
support crew, to reconnect the cable.1 See for yourself: the diagram
below runs a real STP implementation in your browser!
:demo
A1 @0,0 prio=4096
A2 @0,1
A3 @0,2
A4 @0,3
B1 @1,0 prio=8192
B2 @1,1
B3 @1,2
B4 @1,3
C1 @2,0 prio=8192
C2 @2,1
C3 @2,2
C4 @2,3
A1 -- A2 hazard=0
A2 -- A3 hazard=0
A3 -- A4 hazard=0
B1 -- B2
B2 -- B3
B3 -- B4
C1 -- C2 hazard=0
C2 -- C3 hazard=0
C3 -- C4 hazard=0
A1 -- B1 cost=10
B1 -- C1 cost=10
A4 -- B4 cost=20
B4 -- C4 cost=20
Leo @-0.3,0.7 proto=none icon=
Mia @-0.3,1.3 proto=none icon=
Joy @0.3,0.7 proto=none icon=
Roy @0.3,1.3 proto=none icon=
A2 -- Leo hazard=0 A2:edge
A2 -- Mia hazard=0 A2:edge
A2 -- Joy hazard=0 A2:edge
A2 -- Roy hazard=0 A2:edge
Max @-0.3,1.7 proto=none icon=
Zoe @-0.3,2.3 proto=none icon=
Ada @0.3,1.7 proto=none icon=
Amy @0.3,2.3 proto=none icon=
A3 -- Max hazard=0 A3:edge
A3 -- Zoe hazard=0 A3:edge
A3 -- Ada hazard=0 A3:edge
A3 -- Amy hazard=0 A3:edge
Eli @0.7,0.7 proto=none icon=
Jay @0.7,1.3 proto=none icon=
Kai @1.3,0.7 proto=none icon=
Ben @1.3,1.3 proto=none icon=
B2 -- Eli hazard=0.2 B2:edge
B2 -- Jay hazard=0.2 B2:edge
B2 -- Kai hazard=0.2 B2:edge
B2 -- Ben hazard=0.2 B2:edge
Ava @0.7,1.7 proto=none icon=
Lea @0.7,2.3 proto=none icon=
Ivy @1.3,1.7 proto=none icon=
Rex @1.3,2.3 proto=none icon=
B3 -- Ava hazard=0.2 B3:edge
B3 -- Lea hazard=0.2 B3:edge
B3 -- Ivy hazard=0.2 B3:edge
B3 -- Rex hazard=0.2 B3:edge
Ana @1.7,0.7 proto=none icon=
Eve @1.7,1.3 proto=none icon=
Abe @2.3,0.7 proto=none icon=
Ian @2.3,1.3 proto=none icon=
C2 -- Ana hazard=0 C2:edge
C2 -- Eve hazard=0 C2:edge
C2 -- Abe hazard=0 C2:edge
C2 -- Ian hazard=0 C2:edge
Ned @1.7,1.7 proto=none icon=
Lou @1.7,2.3 proto=none icon=
Fay @2.3,1.7 proto=none icon=
Sue @2.3,2.3 proto=none icon=
C3 -- Ned hazard=0 C3:edge
C3 -- Lou hazard=0 C3:edge
C3 -- Fay hazard=0 C3:edge
C3 -- Sue hazard=0 C3:edge
Note
This article is also available as a video, but I advise you to
keep reading here to try the interactive demonstrations.
The basics
Designed in the 80s, the spanning tree protocol has evolved into a rapid
flavor (RSTP) and a VLAN-aware variation (MSTP).2 Any sound-minded
network engineer knows there are better alternatives, like BGP EVPN VXLAN.
Yet, because any switch speaks it, the venerable spanning tree protocol still
fills a niche.
We focus on RSTP: it replaced the original protocol in 2004. To eliminate
network loops, RSTP implements a complex state machine. Timers, link state
changes, and the link-local control frames a bridge receives from its neighbors
drive its transitions. These Ethernet frames are the Bridge Protocol Data
Units (BPDUs). You can watch them in action below: hit the Start button.
After some time, the topology converges to a tree: from the root
C11, there is a path to each bridge3 and no loop. In the upper right
corner, the interface displays a tree icon followed by the time it took to
reach this state. Cut a link and see how the protocol
finds an alternate path to reach C12 in less than a second. You can stop the
simulation, move it forward step by step, reset it to its initial state, or slow
it down with the snail mode . Don t worry about all the displayed
information: I explain it later.
Note
While you scroll, the current simulation stays in view so you can
look at it while reading. Uncheck this box to disable this behavior: .
All examples run in your browser, powered by MSTPD an open-source
user-space4 implementation of RSTP.5
Historical interlude
Radia Perlman, an inductee of the Internet Hall of Fame in 2014,
summarized the ancestor of STP she invented at DEC with this poem, later
included in a US patent:
I think that I shall never see
A graph more lovely than a tree.
A tree whose crucial property
Is loop-free connectivity.
A tree which must be sure to span
So packets can reach every LAN.
First, the root must be selected.
By ID, it is elected.
Least cost paths from root are traced.
In the tree, these paths are placed.
A mesh is made by folks like me,
Then bridges find a spanning tree.
Radia Perlman, Algorhyme.
Electing the root bridge
To build a tree, RSTP first elects the bridge with the lowest bridge
identifier as the root bridge. The bridge identifier combines the priority
and the MAC address: 8192.6e:2b:10:a0:5f:29.
In the example below, S1 and S2 have priorities of 4,096 and 8,192: S1 becomes
root. S4 has a priority of 12,288, while S3 keeps the default priority of
32,768:6 S4 becomes root. S5 and S6 don t have a specific priority, so
the lowest MAC address wins and S5 becomes root.
Each non-root bridge chooses its root port, the one with the lowest-cost
path to the root. Unless you override it, each bridge derives the link cost
from the speed: 20,000 for 1 Gbps. In case of equality, the lowest port
identifier wins.
Each remaining port becomes a designated port if the BPDU it sends is
better than the BPDU it receives. Otherwise, it becomes an alternate port.
Later, if the root port goes down, the best alternate port becomes the new
root port. The tiebreakers for the best BPDU are:
In the example above, after convergence, S1 is the root bridge
because it has a priority of 4,096, while the other bridges have a priority of
32,768. All its ports are designated ports because the accumulated cost to the
root is 0.
S2 s port facing S1 becomes a root port because it has the lowest accumulated
cost to the root 20,000 vs 40,000. S3 has two ports facing S1, and the one with
the lowest port identifier becomes the root port 0x8000 vs 0x8001. The other
candidate is an alternate port because the remote port on the link sends a
better BPDU, with an accumulated cost of 0. On the segment between S2 and S3,
S2 s port wins: while both bridges have the same accumulated cost to the root
(20,000), S2 s bridge identifier is smaller 32768.02:00:00:00:00:01 vs
32768.02:00:00:00:00:02.
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) Root Identifier: 4096.02:00:00:00:00:00
Root Path Cost: 20000
Bridge Identifier: 32768.02:00:00:00:00:01
Port identifier: 0x8002
If you cut the active link between S1 and S3, S3 promotes
the best alternate port to root port. If you also disable the second
link, S3 chooses the remaining alternate port as a
root port. But if you disable the link between S1 and
S2, S2 needs a bit more work to elect a new root port
because it does not have an alternate port.
Unless a specific event happens, designated ports send BPDUs every 2
seconds.9 If a bridge does not
receive BPDUs from its neighbor for 3 consecutive hello periods, it considers
the neighbor dead and removes the port information.
Port state transition
Each port can have one of three states. The diagram displays a background color
for each state:
discarding (red),
learning (yellow), or
forwarding (green).
A root port transitions automatically to the forwarding state. An alternate
port stays in the discarding state. A designated port has two options to
transition from the discarding state to the forwarding state:
If the port is an edge port, either through configuration or because the
remote device does not speak any flavor of STP, the bridge assumes the device
won t participate in the protocol and cannot create a loop. In this case, the
designated port immediately transitions to the forwarding state.
Otherwise, it sends a proposal to its downstream neighbor. If the remote
bridge agrees that the received BPDU is better than any other BPDU stored
for other ports, it elects the receiving port as its root port and starts the
synchronization process: it transitions all non-edge non-synced designated
ports to the discarding state to avoid a loop. Then, it sends back an
agreement. Upon receiving the agreement, the peer designated port
transitions to the forwarding state.10
In the topology above, H1, H2, H3, and H4 are end devices not participating in
the protocol. We configure the ports they connect to as edge ports, so these
ports immediately move to the forwarding state.
Use the step button to move the simulation forward. The clock moves to 1
second. Step again and S1 and S2 send a proposal to
each other. Here is the proposal from S2:
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x4e, Agreement, Port Role: Designated, Proposal
0... .... = Topology Change Acknowledgment: No
.1.. .... = Agreement: Yes
..0. .... = Forwarding: No
...0 .... = Learning: No
.... 11.. = Port Role: Designated (3).... ..1. = Proposal: Yes
.... ...0 = Topology Change: No
Root Identifier: 32768.02:00:00:00:00:01
Root Path Cost: 0
Bridge Identifier: 32768.02:00:00:00:00:01
Port identifier: 0x8001
S1 ignores it: its own root identifier is lower. When S2 receives a similar
proposal from S1, it accepts S1 as its root bridge. It also elects the port to
S1 as the root port and starts the synchronization process. The two designated
ports are already discarding, so no change here. Step
again and S2 sends two BPDUs to S1. In one of them, the
agreement bit is 1 and the proposal bit is 0. It also shows that S2 accepted S1
as the root bridge and its root port is now in the forwarding state. When
receiving this BPDU, S1 transitions its own designated port to the forwarding
state. From this point, the link between S1 and S2 forwards user traffic.
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x79, Agreement, Forwarding, Learning, Port Role: Root, Topology Change
0... .... = Topology Change Acknowledgment: No
.1.. .... = Agreement: Yes
..1. .... = Forwarding: Yes
...1 .... = Learning: Yes
.... 10.. = Port Role: Root (2).... ..0. = Proposal: No
.... ...1 = Topology Change: Yes
Root Identifier: 4096.02:00:00:00:00:00
Root Path Cost: 20000
Bridge Identifier: 32768.02:00:00:00:00:01
Port identifier: 0x8001
Let s look at what happened to S5. Reset the simulation and step
twice. S5 exchanges BPDUs with both S3
and S6. Since S5 has a lower root identifier than S3 and S6, it stays the root
bridge, while S3 and S6 accept the proposal and elect their root ports. S3 and
S6 start the synchronization process. S6 s port to H4 keeps forwarding because
it is an edge port. Move one step. Both S3 and S6 send
an agreement back to S5, which transitions both designated ports to the
forwarding state. Yet, the link between S5 and S3 keeps discarding user traffic!
If you look carefully, S3 s port toward S5 is now a designated port, not a root
port. During the same step, S3 also receives a better BPDU
from S2 with S1 as the root bridge. It elects its port to S2 as the root port
and downgrades the port to S5 to a designated port, which stays in the
discarding state.
On the next step, things get a bit tricky. S3 sends a
proposal to S5:11
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x4f, Agreement, Port Role: Designated, Proposal, Topology Change
0... .... = Topology Change Acknowledgment: No
.1.. .... = Agreement: Yes
..0. .... = Forwarding: No
...0 .... = Learning: No
.... 11.. = Port Role: Designated (3).... ..1. = Proposal: Yes
.... ...1 = Topology Change: Yes
Root Identifier: 4096.02:00:00:00:00:00
Root Path Cost: 40000
Bridge Identifier: 32768.02:00:00:00:00:02
Port identifier: 0x8002
S5 elects S1 as its root bridge and the port toward S3 as its root port. It
starts its synchronization process, but the designated port to S6 does not
move into the discarding state. Why? That port stays a designated port and its
neighbor S6 has already sent an agreement on the link, so the port keeps its
synced status.
Now, let s step back to look at what happens to S6. At this point,
S6 believes S5 is the root bridge. Step once and S4 sends
a new proposal to S6. S6 accepts the proposal, elects S1 as the root bridge and
the port to S4 as its root port. The role of the port facing S5 changes: from a
root port, it becomes a designated port. Because its peer keeps advertising an
inferior BPDU on the link, this port becomes disputed and moves to the
discarding state. The root port transitions to the forwarding state and the link
starts forwarding immediately because S4 s designated port is already in the
forwarding state. If we step one more time, S5 and S6
exchange two BPDUs. The one from S5 is better because of its lower bridge
identifier. S5 s port stays a designated port, while S6 downgrades its own port
to an alternate port.
Let s rewind to the start one last time: cut the link between S1 and S2, run
the simulation until the topology is stable, stop the
simulation, and restore the link between S1 and S2. During the first
step, S1 and S2 exchange proposals. S2
elects S1 as the root bridge instead of S5 and the port to S1 as the root port.
It downgrades the previous root port to a designated port and moves it into the
discarding state. The other designated port stays synced and keeps its
forwarding state. At the next step, S2 sends
an agreement to S1 and the link between them starts forwarding user traffic. It
also sends a proposal to S3, but not to S4.
Instead, it sends a regular BPDU to S4. S4
still elects S1 as its root bridge and the port to S2 as its root port. It
demotes its previous root port, the one to S3, to a designated port, which
transitions to the discarding state because of the root port change. The other
alternate port, to S6, also becomes a designated port and stays in the
discarding state. The new root port moves to the forwarding state. On the next
step, S4 s port to S3 settles as an
alternate port after receiving a better BPDU from S3.
RSTP is a giant state machine split into smaller ones: bridge detection, port
information, port protocol migration, port role selection, port role
transitions, port receive, port state transitions, port timers, port transmit,
and topology change. Some of them are per bridge, some per port. Each bridge
runs an instance. Time, operational port state changes, and the BPDUs it
receives from other instances drive the transitions. Being event-driven makes
RSTP more efficient but also more difficult to understand.
Placeholder for the Port Information state machine extracted from IEEE 802.1Q-2005, page 182. Pending IEEE authorization for reproduction, this is the blueprint for the Western Australian Government Railways class Msa Garratt articulated steam locomotive.
Topology change notification
A bridge populates a MAC address table: it associates each source MAC address
with the port that last received it. When forwarding an Ethernet frame, it looks
up this table to choose the right port.12 When a link fails, a connected
fridge reachable through one port may become reachable through another one. The
affected bridges should flush the MAC addresses they learned, because these
entries may now be wrong.
For this purpose, RSTP implements topology change notifications using a
flooding mechanism. When a non-edge port transitions to the forwarding state, a
bridge generates BPDUs with the topology change (TC) bit set. It sends them to
all the non-edge designated ports and to the root port. It also flushes the MAC
address table on these ports. When a bridge receives such a BPDU, it propagates
the notification to all non-edge designated ports and the root port, except the
one the notification came from. It also flushes the MAC address table on these
ports. In the examples, the BPDUs with the TC bit set to 1 have a red circle.
Start the simulation and wait a few seconds for the topology to
settle. Stop the simulation and disable the link between S2 and
S5. S5 elects the port facing S4 as the root port, which
transitions immediately to the forwarding state. Step
once and S5 emits a BPDU with the TC bit set to 1:
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x79, Agreement, Forwarding, Learning, Port Role: Root, Topology Change
0... .... = Topology Change Acknowledgment: No
.1.. .... = Agreement: Yes
..1. .... = Forwarding: Yes
...1 .... = Learning: Yes
.... 10.. = Port Role: Root (2).... ..0. = Proposal: No
.... ...1 = Topology Change: Yes
Root Identifier: 4096.02:00:00:00:00:00
Root Path Cost: 40000
Bridge Identifier: 32768.02:00:00:00:00:04
Port identifier: 0x8002
S4 receives this BPDU. It flushes the MAC address table on the port facing S1:
while LPT was previously reachable through this port, it is now reachable
through S5. Step once. S4 sends S1 a BPDU
with the TC bit set to 1. When S1 receives this BPDU, it flushes the MAC address
table on the ports facing S2 and S3. Step
once and S1 sends a notification to S2 and
S3. Step once again and S2 sends a notification to
S3, while S3 does nothing because the port toward S2 is an alternate port. S3
does not flush any MAC address table: LPT is still reachable through its port to
S1.
If you step a bit more, you will see that some of the
periodic BPDUs keep the TC bit set to 1. Each port runs a timer equal to the
hello timer plus one second.13 The timer starts when the port emits a
notification. Until it expires, the port sets the TC bit to 1 in every BPDU it
sends. You can also see some periodic BPDUs
without the TC bit: they originate from a port that only received a notification
and therefore did not arm its timer.
Security
RSTP is weak against configuration errors and malicious actors. A bridge not
talking RSTP can create a loop. An attacker can insert themselves into the
topology to disrupt the service, spy on the traffic, or alter it.
To mitigate such problems, you need to identify the edge ports. An edge port
connects to an end device, like a PC or a printer. Such devices do not generate
BPDUs and cannot create a loop. RSTP defines two related flags:
When true, AdminEdge initializes a port as an edge port. It defaults to
false.
When true, AutoEdge lets a port become an edge port when it does not
receive BPDUs for 3 seconds. It defaults to true.
If an edge port receives a BPDU, regardless of the values of these two flags, it
reverts to a non-edge port.
In the topology above, S1, S2, S3, S4, S5, and S6 act as bridges, while H1, H2,
H3, H4, H5, and H6 act as end devices:
S1 and H1 are on a port without a specific configuration: AutoEdge is true,
AdminEdge is false,
S2 and H2 are on a port where AdminEdge is true,
S3 and H3 are on a port where AutoEdge is false and AdminEdge is true,
S4 and H4 are on a port where AutoEdge is false.
If you start the simulation and wait about 20 seconds, links to S1,
S2, S3, S4, H1, H2, H3, and H4 eventually forward user traffic: none of the
flags matter.
But what about the two remaining pairs? S5 and H5 connect to a network port.
Such a port enables a non-standard feature: bridge assurance. The port
transmits BPDUs regardless of its role. If it does not receive BPDUs for 3
consecutive hello periods, it transitions to the discarding state. On the link
between R0 and S5, you can see BPDUs traveling in both
directions, unlike the other links, where only
designated ports send BPDUs.
S6 and H6 connect to a port where AdminEdge is true and BPDU guard is
enabled. This is another non-standard feature that shuts down a port if it
receives a BPDU.
In summary, if you expect a port to be an edge port, you should set AdminEdge
to true and enable BPDU guard. Otherwise, declare it as a network port.
Why RSTP today?
A compelling use case for RSTP today is an out-of-band network for a datacenter,
since you can tolerate an outage of a few seconds. The configuration is minimal
and you can use cheap switches, like a Cisco 2960X.14 You need two
switches acting as root bridges, and you build several loops to connect OOB
switches in each cabinet. This simple design survives one failure on each
loop.15
This topology converges in about 6 seconds. Each loop should stay
small (around 16 bridges) to reduce the probability of a double failure and to
avoid sharing too much bandwidth. The design can evolve a bit without adding too
much complexity: one VLAN per loop or one bridge domain per loop.
How large can a network be?
The maximum age, whose default value is 20, governs the maximum distance of a
bridge from the root. The topology below is too big for BPDUs from R1 to reach
beyond S20.16
Once the topology settles, part of the network considers R1 the
root, while the other votes for R2. At the boundary, S20 tries to start a
synchronization with S21 to move its designated port to the forwarding state.
The BPDU looks like this:
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x4e, Agreement, Port Role: Designated, Proposal
Root Identifier: 4096.02:00:00:00:00:00
Root Path Cost: 400000
Bridge Identifier: 32768.02:00:00:00:00:15
Port identifier: 0x8002
Message Age: 20
Max Age: 20
S21 rejects it because the message age equals the maximum age. On the other
hand, the BPDU S21 sends to S20 looks like this:
Spanning Tree Protocol Protocol Identifier: Spanning Tree Protocol (0x0000) Protocol Version Identifier: Rapid Spanning Tree (2) BPDU Type: Rapid/Multiple Spanning Tree (0x02) BPDU flags: 0x7c, Agreement, Forwarding, Learning, Port Role: Designated
Root Identifier: 4096.02:00:00:00:00:01
Root Path Cost: 320000
Bridge Identifier: 32768.02:00:00:00:00:16
Port identifier: 0x8001
Message Age: 16
Max Age: 20
This is not enough to change S20 s root port because S20 has a lower root
identifier4096.02:00:00:00:00:00 vs 4096.02:00:00:00:00:01.
Fixing the link between R1 and R2 resolves the issue. The
maximum message age any packet carries is now 18, below the configured maximum
age. But it only works until another link breaks. A plausible fix is to increase
the maximum age to 40.17
How fast is RSTP?
RSTP usually converges in a couple of seconds at startup. It often repairs a
tree in less than a second. Even the 38-bridge topology takes less than 10
seconds to converge.18 Some topologies can take a bit more time to recover
when the root bridge becomes unavailable.19
In the topology above, start the simulation, wait for convergence,
hit stop, and cut the link between R0 and S1. The topology is
already optimal, but RSTP has a hard time converging again.
First, S1 loses its root port. It has no more information about R0 and elects
itself as the root bridge. It keeps its ports to S2 and S3 as designated ports
in the forwarding state. Step once and it
sends a BPDU to both S2 and S3 to let them know about the root change. When
receiving it, S2 accepts S1 as its root because it does not have a better root
on another port. It elects the port to S1 as its root port. The other port stays
a designated port. Both ports keep forwarding.
When receiving the BPDU from S1, S3 behaves differently: it knows R0 as a better
root than S1 through its alternate port to S2. It promotes this port to a root
port and demotes the port facing S1 to a designated port, which requires a new
agreement. Step once and S3 sends a proposal to
S1 with R0 as the root bridge. S1 elects R0 as the root bridge and promotes its
port to S3 as a root port.
During the same step, S3 also receives a BPDU from
S2 stating that S1 is the root bridge. Therefore, S3 has no port left with R0 as
the root bridge: it elects S1 as the root bridge and its port to S2 as the root
port. Step once and its next BPDU to S1 includes
this information: S1 elects itself again as the root bridge. But during the
same wave, S1 sends a proposal to S2 with R0 as
the root bridge. While S1 and S3 agree that S1 is the root bridge, S2 now
believes this is R0! In turn, S2 again convinces S3
that R0 is the root bridge, S3 convinces S1, S1 convinces S2, and S2 convinces
S3.
This could go on forever, but it does not. The BPDUs saying R0 is root
eventually age out when the message age goes past the maximum age. In the
example above, at the eleventh second, S2 sends a
BPDU to S3 with R0 as root, but S3 drops it because its message age reached the
maximum. With some luck, the topology can also converge faster if a port stops
transmitting new BPDUs after tripping the transmit hold count, whose default
value is 6 per second.
About MSTP
MSTP is the VLAN-aware version of RSTP: it runs several instances of RSTP and
lets the administrator map each VLAN to a specific instance. For example, you
can map VLANs 100 to 200 to a first instance, and 300 to 400 to a second
instance. The remaining VLANs map to a special instance named the Internal
Spanning Tree (IST). MSTP adds its own complexity, but the gist is that you have
several logical topologies acting independently. If you want to dig deeper, have
a look at MSTP Tutorial Part I: Inside a Region.
About the interactive examples
The interactive examples run MSTPD directly in your browser, compiled to
WebAssembly with emscripten. A C API replaces the code talking to the
Linux kernel: it manages bridges and ports, exports state as JSON, and drives
time deterministically. A JavaScript wrapper makes it more user-friendly:
importloadMSTPDfrom"./dist/mstpd.mjs";constmstp=awaitloadMSTPD();// Create 3 bridgesconsta=mstp.createBridge("A",priority:4096 );constb=mstp.createBridge("B",priority:8192 );constc=mstp.createBridge("C");// Each bridge has two portsconsta1=a.addPort("a-b",portno:1 );consta2=a.addPort("a-c",portno:2 );constb1=b.addPort("b-a",portno:1 );constb2=b.addPort("b-c",portno:2 );constc1=c.addPort("c-a",portno:1 );constc2=c.addPort("c-b",portno:2 );// Build a triangle topologymstp.link(a1,b1);mstp.link(a2,c1);mstp.link(b2,c2);// Enable all bridges and portsfor(constbrof[a,b,c])br.enable();for(constpof[a1,a2,b1,b2,c1,c2])p.enable();// Execute 40 seconds' worth of wall clock and display the topologymstp.step(40);console.log("Topology:",mstp.topology());
Several dozen unit tests explore the features of MSTPD and check that they work
correctly in this environment:
$ node--test*.test.mjs
two bridges: lower priority becomes root (41.657342ms) triangle loop: exactly one port blocks and all agree on the root (5.832ms) breaking the active link reconverges and restoring recovers (18.730753ms)[ ] tests 40 pass 40 fail 0[ ] duration_ms 396.190897
Additional JavaScript code looks for specific <pre> blocks containing a
topology definition and turns them into interactive widgets. You can inspect
and modify the definition by hitting the edit button.
There is also a cool trick to tell whether the topology has converged. After
each step, we save a snapshot of the simulation memory, play 50 seconds worth
of simulation to check if the topology is stable, and travel back in time by
restoring that snapshot.
The complete code lives on GitHub. I am happy with the result. It can be
difficult to follow everything happening during a single step, but stepping
forward and backward helps. I plan to use the same approach in future blog posts
about networking features.
Note
Michael Lynch reviewed a first draft of this article. He authored
Refactoring English, a book to sharpen your writing for blog posts,
documentation, commit messages, and tutorials. Any errors are still mine!
The sprites for Stan and Blobby come from Craftpix, the coffee
cups from Yanin.
The priority is a multiple of 4,096: with MSTP, the lower 12 bits
of the bridge priority encode the MST instance identifier, leaving only the
upper 4 bits for the configured priority.
To inspect the BPDUs crossing a link, select it, click the
Download packets button, and open the file with Wireshark.
A backup port only exists if the bridge has several ports on the same
collision domain. This should not happen in a switched network.
This is the value of the hello timer. It used to be configurable,
but IEEE 802.1Q-2005 pins it to 2. MSTPD does not allow another value.
If the peer port does not receive an agreement after the hello
timer elapses or the maximum age if the port has just come up it falls back
to the timer-based method for compatibility with STP: it transitions to
the learning state, waits again for the hello timer to expire, and
transitions to the forwarding state.
As in many proposals, S3 also sets the agreement bit to 1. The
proposal bit says I am the designated port on this link and I want to
transition to the forwarding state. The agreement bit says I am already in
sync with the rest of my bridge on this root information. Both can be true.
If it finds no entry, the bridge duplicates the Ethernet frame on all
ports, except the incoming one. The same happens if the destination MAC
address is the broadcast one (ff:ff:ff:ff:ff:ff). This behavior bootstraps
the learning process.
This timer makes RSTP resistant to packet loss.
You can get them for less than US$100 through a broker. All the ports
run PVST+ by default and automatically fall back to plain RSTP.
If you look closely at what happens at t=2s, you can see that R2 is
gaining popularity as root: S17 to S36 believe R2 is the root bridge. S16
does not follow because we hit the maximum age. Later, S17 to S20 reverse
their position. I ll let you explore the state of the various bridges to
understand the root cause.
When increasing the maximum age to 40, you also need to
increase the forward delay to 21 (:forward-delay 21), as the standard
enforces this condition: 2 (Forward Delay 1) Max Age. For this
specific topology, you could also increase the maximum age to 37 and
forward-delay to 20.
The simulation may seem slow, but it does not run in real time. Look at
the current timestamp in the upper right corner to know the wall clock, e.g.
t=8s. Once the topology stabilizes, the same corner shows the convergence
time, e.g. 2s.
Imagine you rent office space for a three-day event. You quickly set up a few
Ethernet switches and tape some cables on the floor to get everyone online.
Unfortunately, Stan, your clumsiest coworker, kicks out a cable every time he
gets up for coffee. Spare cables would fix that, but a loop turns into a
broadcast storm: Ethernet packets multiply until nothing else gets through.
That s where the spanning tree protocol comes in: it blocks just enough of the
spare cables to leave a loop-free tree, and rebuilds it in a second each time
Stan strikes again.1
This content is also available as a text version, with interactive demos
that run a real implementation directly in your browser!
This video is an experiment.2 Honestly, except for Radia Perlman reading
her poem,3 you should read the original article instead. It presents the same content, but you can play with the
interactive examples, which are the main contribution. On the other hand, if you
happen to like the video, be sure to tell me in the comments!
In 2008, I landed my second job, in the network team at Orange
Portails1, the division behind the websites and search engine of the
French telecom operator Orange. The place ran like clockwork: a comprehensive
technical setup, a dedicated team for every part of the business, and room to
focus on what I do best. A few years later, none of that mattered: thanks to an
obsession with the numbers, we could no longer deliver new services on time.
Disclaimer
This is a story I like to tell to warn people about
Goodhart s law.2 As these events happened almost 15 years ago, my
recollection is a bit fuzzy. I left in 2012.
The first years
During my first years, the department operated like a startup. Its cradle was
the French company Echo. They built a search engine. France T l com bought it
and renamed it Voila. It was the most visited search engine in France in the
early 2000s. France T l com consolidated the portal activities into the Wanadoo
Portails division, later renamed Orange Portails.
The technical environment was excellent. We had many internal tools:3 a
ticket system, an RRD-based graphing tool, an IPAM, a reporting tool, and an
SNMP-based alerting tool.4 We deployed our Linux servers with
CFEngine. We installed systems and applications from internal Debian
repositories. We documented everything in a private MediaWiki instance.
Supervision was performed with an ancestor of Xymon. The network
architecture was clean and scalable with little legacy. We onboarded new people
in a day.
It was a nurturing environment for me. I developed several tools:
lldpd, an 802.1AB implementation, Snimpy, a pythonic binding for
Net-SNMP, Wiremaps, a layer-2 discovery tool with a time machine to know
which device is connected where, Kit r , a tool to simulate network
conditions, QCSS-3, a controller for load-balancers, and ipoo, a service
available through a Jabber chatbot and a Greasemonkey script to expose
IP-related information. I added SNMP support for Keepalived and
Quagga. I also started this blog, with articles like
Anycast DNS, TLS-related articles like TLS computational DoS
mitigation, SNMP-related articles like Integration of Net-SNMP into an
event loop, Linux-related articles like Tuning Linux IPv4 route cache,
and an article about VXLAN long before it was cool.
The collapse
When we needed new servers, the on-site team would take a set from the
inventory, install our base Linux distribution on them, put them in the
datacenter, and cable them to the top-of-the-rack switches. We opened a ticket
describing the servers we needed, and one week later, our servers were
available.
Orange wanted to know if this team was performing well, so they asked for KPIs.
They decided to use the number of tickets completed in a year. They asked to
double this number. So instead of one ticket for a new service, we would open
six tickets one per server. By the end of the year, the KPIs had more than
doubled.
Everybody saw it as a success for performance management. So, they asked to do
the same for the next year. Now, we needed to open a ticket per server and per
step. Again, the KPIs doubled. Behind the scenes, the tickets went to different
people and were no longer handled in order. So, for the next year, it was decided to
have meta-tickets and meetings to follow the progress of these tickets. Of
course, all these extra steps pushed the KPI even higher.
This performance management method spread to the other teams.5
Everything became slower. Instead of a couple of weeks, a new service now took
six months. We built a Soviet nail factory. But the KPIs were good, and we
stopped caring.
Let me give you another example. We had to estimate the impact of each night
operation. We weren t half bad: we declared most operations without any
expected impact. Most of the time, there was no impact. One time out of five,
there was a 5-second impact. We were told to try harder to meet our expected
impact. What did we do? We started declaring a 5-second expected impact. One
day, we got a 30-second impact and were told we failed to match the expected
impact. In the end, we declared most operations with a 10-minute expected
impact, and we stopped caring: instead of carefully shifting traffic around, we
allowed ourselves a 5-minute impact. And our KPIs were never better.
An artist's rendering of the evolution of impacts over the years.
KPIs are not bad, but they are easy to break. Use them carefully: let the people
doing the work help choose the metrics, and tie those metrics to the quality of
the service for example, with service level objectives. Otherwise, even
dedicated people stop caring, game the system, and eventually quit.6
Internally, this division was named Hebex. It was located in
Bagnolet (next to Paris) and Sophia-Antipolis (near Nice).
Goodhart s law often gets the credit, but Campbell s law
describes my experience even better: the more you lean on a number to make
decisions, the faster people corrupt it.
At the time, SaaS was not really a thing. I remember we considered,
with a couple of colleagues, selling Wiremaps as a SaaS, with
homomorphic encryption for the database. But who would outsource their
observability stack?
Snalert was a metacircular alerting tool in Perl. It was able to
poll a very large number of SNMP targets in a short timespan. All our
monitoring was SNMP-based, including system monitoring.
My team also managed the rules of many Linux-based firewalls. To
increase our KPIs, we used the same method: rather than accepting one ticket
with a flow matrix, we requested one ticket per flow.
Orange is not unique. Google s promotion process is another
well-known example of a broken KPI. Michael Lynch explains it in Why I
Quit Google to Work for Myself.
AI slop is invading the web. A recent story about disallowing LLM-generated
submissions on Lobsters triggered a lot of debate. My personal worst
offenders are LinkedIn articles with AI-generated images and uninspired
articles filled with emojis from people trying to masquerade as experts on a
subject they don t care enough to write themselves. While I am unhappy about
this situation, I rely on LLMs for grammar, copyediting, and
translation. I don t see this as a contradiction.
I am a native French speaker, but I blog in both English and French. When I
started writing this blog in 2011, I was composing in French and translating
to English, but I found it was better to work in the reverse order to
avoid unnatural and non-idiomatic constructions. One of my goals is to write
good English but I never felt it was my strong point.1 For example, verb
tenses are often an issue, even if I mostly stick with the present tense. I
learn the rules and forget them right away. I also don t feel like hiring an
editor for something I see as a hobby.
As an example, I have kept the history of the successive iterations when writing
Scaling Akvorado BMP RIB with sharding :
the first draft, authored with the help of a thesaurus,2
I know that LLMs may alter the author s voice when editing, but the
corrections in the second step are minor. The prompt asks to apply light
stylistic edits, with some guidance around avoiding passive voice, long
sentences, bland verbs, and filler words. It also defines the target audience:
technical with a B2 level in English.
In the following excerpt, I used long time instead of long-standing. The
former is missing a hyphen and applies to people a long-time friend, while
the later relates to a situation a long-standing agreement. I had a hard
time understanding the reason of the second change: the LLM prefers a
defining relative clause to provide the definition of RIB sharding.
As the Internet routing table contains more than 1 million routes, Akvorado
needs to scale to tens of millions of routes. This has been a long
time long-standing challenge, but I expect this issue is now
fixed by using RIB sharding, a method to split that
splits the routing database into several parts to enable concurrent
updates.
In the next modification, the LLM puts device instead of equipment. This is
correct as equipment is an uncountable noun. I know that, but I still fall
into this trap.
When Akvorado does not find a route from a specific device, it falls back to a
route sent by another equipment device.
I ask the LLM to use descriptive verbs and it complies by replacing a
multi-word predicate with a lexically rich verb:
The benchmarks demonstrate it has better performance than
outperforms other packages, both packages for
lookups, insertions, and memory usage.
It also fixes grammar errors. In the next excerpt, a list of routes is a
singular expression. Moreover, stored is a state and I should not use into
as it expresses a change.
The list of routes for each prefix are is not stored
directly into in the prefix tree.
As a last example, consider the following snippet. The require verb
accepts a noun or an object followed by a to-infinitive. I can t use it with
just a to-infinitive.
An alternative would be to have one prefix tree for each peer but it would
require to configure configuring all routers to export
their routes.
As someone who didn t grow up speaking English, I struggle with these grammar
rules despite reading a lot of English material.3 French is more
complex to get started but more systematic. English is full of irregularities.
On each page, I disclose in the footer whether an AI modified the content. There
are three levels:
: no AI or almost no AI (e.g., grammar corrections)
: enhanced (e.g., copyediting)
: generated (e.g., translated from another language, even if human-edited)
Hover or tap the icon to reveal the AI s name and its role in the document.
Example of AI usage disclosure: Claude Sonnet 4.5 edited this article.
The graph below shows which tool altered each post, year by year. Recently, I
applied the grammar skill to past articles. Since 2018,
French articles have been translated with the help of DeepL first, then of
an LLM. Since 2024, English articles are copyedited.
🖼 Graph showing the AI usage over the years. Each level get its own
color.
AI usage over the years. Hover or tap a band for the details.
If you are strongly against any usage of LLMs specifically for writing, I hope
you accept my more nuanced position on the usage of these tools as a trade-off
to provide clearer and more engaging articles. Years of literature on improving
English told us it is important to choose the right word to keep the reader
engaged.
[ ] Good writing consists of mastering the fundamentals (vocabulary,
grammar, the elements of style) and then filling the third level of your
toolbox with the right instruments.
Stephen King, On Writing
Note
Unlike other recent articles, I did not use an LLM to edit this post:
an unnamed person kindly accepted to proofread it. I translated it to French
without using an LLM either.
I am quite happy with the writing tools provided by Kagi. Both the
translate tool and the dictionary are a valuable help to find
different wordings. I also lean on Kagi s research assistant when
researching a topic.
When I was ten, I played Monkey Island 2 in English without having
taken any classes. I used a dictionary to translate word by word and I found
the irregular verbs confusing and not in the dictionary.
To associate routing information like AS paths or BGP communities to flows,
Akvorado can import routes through the BGP Monitoring Protocol (BMP). As
the Internet routing table contains more than 1 million routes, Akvorado
needs to scale to tens of millions of routes.1 This has been a
long-standing challenge,2 but I expect this issue is now fixed by using
RIB sharding, a method that splits the routing database into several parts
to enable concurrent updates.
Previous implementation
Akvorado connects 2 elements to build its RIB:
a prefix tree, and
a list of routes attached to each prefix.
Akvorado BMP RIB implementation without sharding. One single read/write lock.
In the diagram above, the RIB stores five IPv4 prefixes and two IPv6 prefixes.
One of them, 2001:db8:1::/48, contains three routes:
from peer 3, next hop 2001:db8::3:1, AS 65402, AS path 65402, community
65402:31,
from peer 4, next hop 2001:db8::4:1, same ASN, AS path, and community,
from peer 5, next hop 2001:db8::5:1, AS 65402, AS path 65401 65402,
community 65402:31.
The prefix tree uses the bart package, an adaptation of Donald Knuth s ART
algorithm. The benchmarks demonstrate it outperforms other packages for
lookups, insertions, and memory usage.3 Plus, the author is quite
helpful.
Storing routes in a map
The list of routes for each prefix is not stored directly in the prefix tree:
it would put too much pressure on the garbage collector by allocating per-prefix
arrays.
Instead, the RIB assigns a unique 32-bit prefix identifier for each prefix,
either by picking the last available prefix identifier from the freePrefixIDs
array if any, or using the nextPrefixID value before incrementing it. Then,
the routes are stored in the routes map, leveraging the optimized Swiss
table in Go. To retrieve routes attached to a prefix, we look them up
one by one in the routes map with a 64-bit key combining the 32-bit prefix
index with a 32-bit route index matching the position of the route in the list.
Akvorado scans routes from the first to the last to find the best one.4 It
knows there is no more route if the route key returns no result.
To save memory and allocations, NLRI, next hops, and route attributes are
interned : a 32-bit integer replaces the real value. The mechanism predates the
unique package introduced in Go 1.23. We keep it because it has
different trade-offs:
It uses explicit reference counting instead of relying on weak pointers.
It works with non-comparable values implementing Hash() and Equal()
methods.6
It uses explicit pool instances. This will be useful for sharding.
It has better performance. See for example this benchmark.
It consumes half the memory thanks to unsigned 32-bit references instead
of pointers.
The global read/write lock is a bottleneck in this implementation. But how?
There are several users of the RIB, each with its own set of constraints:
The Kafka workers look up the RIB to enrich flows with routing
information. They are bound by the number of Kafka partitions.8
Akvorado also adjusts their number to ensure efficient batching to ClickHouse.
On our setup, the number of workers oscillates between 8 and 16. As we want
to observe the latest data, we cannot afford for the Kafka workers to lag too
much.
The monitored routers send route updates through the BMP protocol. When
connecting, they can send millions of routes.9 After the initial
synchronization, updates are sent continuously and may spike from time to
time. The router detects a stuck BMP station when its TCP window is full and
resets the session in this case. While Akvorado implements a large incoming
buffer, it still needs to update the received routes with the write lock held
fast enough to avoid being detected as stuck.
When a remote BGP peer goes down, Akvorado flushes the associated routes by
walking the RIB with the write lock held. When a monitored router goes
down, Akvorado waits a bit but eventually flushes all the associated routes.
In short: on a busy setup, lock contention is high for both readers and
writers, and neither can lag too much behind.
RIB sharding
First step: basic sharding
To remove the global lock, the RIB is split into several shards, each one
handling a subset of the prefixes:
Akvorado BMP RIB implementation with sharding.
The prefix tree stays global and is protected by a single lock. Each shard gets
its read/write lock, its route map, and its intern pools to store NLRIs, next
hops, and route attributes, which would not have been possible with Go s
unique package. The prefix indexes are also sharded: the 8 most
significant bits are the shard index and the 24 remaining bits are the local
prefix index.
Gerhard confirmed that after this blind change,
the BMP receiver chugged steadily.
Later, I wrote a concurrent benchmark over half a million synthetic but
plausible routes10 partitioned over 0 to 8 writers, churning routes as
fast as possible, while 1 to 16 readers continuously look up a set of 10,000
routes. I don t know if this benchmark is realistic, but it confirms the
improvements for both read and write latencies:
Read and write latency performance improvement after sharding.
It also shows that a high number of writers degrades read latency.
Second step: lock-free reads
The single read/write lock protecting the prefix tree is the next target. The
bart package provides alternative mutation methods returning an updated tree
using copy-on-write. Readers don t need the global lock any more, leaving it
only to synchronize writers. The prefix tree is boxed in an atomic pointer.
Akvorado BMP RIB implementation with sharding and lock-free reads.
Without a lock, readers can now fetch a stale prefix index when walking their
copy of the tree if a concurrent writer removes the last route attached to this
prefix index and recycles it for another prefix. To avoid this issue, we combine
the prefix index with a generation number and store them in the tree:
Each shard stores the generation number for each local prefix index. The
generation number increases by one if the associated prefix index is freed. When
looking up the routes attached to a prefix index, the reader checks if the
generation number matches. Otherwise, it assumes the index was recycled and the
list of routes is empty.11 You can see this case in the diagram above for
prefix index 5, stored with a generation index of 3, while the current value in
the []generations array is 4. The generation number could overflow, but it is
not a problem as lookups are quick.
Running the concurrent benchmark against this new implementation shows the
improvements for the read latency as soon as the cost of the copy-on-write
prefix tree is amortized.
Read and write latency performance improvement after lock-free reads. The middle column shows the cumulative improvements of both steps.
Among the multiple attempts to optimize the BMP component, RIB sharding is one
of the more satisfying. Akvorado 2.2 implements the first step.
PR #2433, drafted while writing this blog post, implements the second step
and was released with Akvorado 2.4.
Each router exporting flows doesn t need to send its routes. When
Akvorado does not find a route from a specific device, it falls back to a
route sent by another device. It is up to the operator to decide if this
is a good enough approximation.
I made many attempts to scale the BMP component. See for example
PR #254, PR #255, PR #278, PR #2244, and PR #2245.
Despite these efforts, this component remained problematic for some users.
See discussion #2287 as the latest example.
It keeps improving: bart 0.28.0 features a new
implementation that trades a bit of memory for greater lookup performance. I
did not test it yet, as I have been preparing this blog post for a couple
of months already.
Akvorado prefers the route matching the exact next hop. Otherwise, it
falls back to any other route. This is an approximation. An alternative
would be to have one prefix tree for each BGP peer but it would require
configuring all routers to export their routes. pmacct s BMP daemon
implements this approach.
If we consider the BGP RIB as a database, the Network Layer
Reachability Information (NLRI) is the primary key. Its content depends on
the BGP family. With IPv4 or IPv6 unicast, this is the prefix. For VPNv4 and
VPNv6 families, it includes the route distinguisher. If you enable the
ADD-PATH extension, the NLRI also contains a path identifier.
In our implementation, we don t store the prefix as we get it from the
looked-up IP address using the prefix length stored separately.
Despite being an author or co-author of the first BMP-related RFCs since
2016 (RFC 7854, RFC 8671, RFC 9069), Cisco did not implement it
in a usable way in IOS XR until version 24.2.1. We still need to upgrade a
few routers to enable this feature.
KIP-932 introduces, in Kafka 4.2, the concept of share groups to
enable cooperative consumption on the same partition. This is not supported
in Akvorado yet.
You can configure BMP to send routes for each BGP peer before or after
applying the incoming policies. In this case, you can get more than one
million routes for each transit peer. You can also tell BMP to send the
local RIB, which only contains the best path for each prefix.
The prefixes are random, but the prefix size distribution and the
AS path length distribution follow the data provided by Geoff Huston.
Alternatively, we could retry the lookup, but it would be pointless:
the RIB is an eventually consistent database, and an empty list was a
correct answer at some point in the recent past.
Vertical rhythm aligns lines to a consistent spacing cadence down the page. It
creates a predictable flow for the eye to follow. Thanks to the rlh CSS unit,
vertical rhythm is now easier to implement for text.1 But illustrations
and tables can disrupt the layout. The amateur typographer in me wants to follow
Bringhurst s wisdom:
Headings, subheads, block quotations, footnotes, illustrations, captions and
other intrusions into the text create syncopations and variations against the
base rhythm of regularly leaded lines. These variations can and should add
life to the page, but the main text should also return after each variation
precisely on beat and in phase.
Robert Bringhurst, The Elements of Typographic Style
Text
Three factors govern vertical rhythm: font size, line height and
margin or padding. Let s set our baseline with an 18-pixel font and a 1.5
line height:
CSS Values and Units Module Level 4 defines the rlh unit, equal to the
computed line height of the root element. All browsers support it since
2023.2 Use it to insert vertical spaces or to fix the line height
when altering font size:3
We can check the result by overlaying a grid4 on the content:
Using CSS rlh unit to set vertical space works well for text. You can display the grid using Ctrl+Shift+G.
If a child element uses a font with taller intrinsic metrics, it may stretch
the line s box beyond the configured line height.5 A workaround
is to reduce the line height to 1. The glyphs overflow but don t push the line
taller.
code,kbdline-height:1;
Responsive images
Responsive images are difficult to align on the grid because we don t know their
height. CSS Rhythmic Sizing Module Level 1 introduces the block-step
property to adjust the height of an element to a multiple of a step unit. But
most browsers don t support it yet.
With JavaScript, we can add padding around the image so it does not disturb
the vertical rhythm:
The image is snapped to the grid thanks to the additional padding computed with JavaScript. 216 is divisible by 27, our line height in this example.
As the image is responsive, its height can change. We need to wrap a resize
observer around the adjust() function:
Tables
Table cells could set 1rlh as their height but they would feel constricted.
Using 2rlh wastes too much space. Instead, we use incremental leading: we
align one in every five lines.
To align the elements after the table, we need to add some padding. We can
either reuse the JavaScript code from images or use a few lines of CSS that
count the regular rows and compute the missing vertical padding:
A header cell has twice the padding of a regular cell. With two regular rows,
the total padding is 2 2 0.2+2 0.4=1.6. We need to add 0.4rlh to reach
2rlh of extra vertical padding across the table.
One line out of five is aligned to the grid. Additional padding is added after the table to not break the vertical rhythm. 405 is divisible by 27, our line height in this example.
None of this is necessary. But once you start looking, you can t unsee it. Until
browsers implement CSS Rhythmic Sizing, a
bit of CSS wizardry and a touch of JavaScript is enough to pull it off. The main
text now returns after each intrusion precisely on beat and in phase.
For broader compatibility, you can replace 2rlh with
calc(var(--line-height) * 2rem) and set the --line-height custom
property in the :root pseudo-class. I wrote a simple PostCSS
plugin for this purpose.
It would have been nicer to compute the line height with
calc(round(up, calc(2.4rem / 1rlh), 0) * 1rlh). Unfortunately, typed
arithmetic is not supported by Firefox yet. Moreover, browsers support
round() only since 2024. Instead, I coded a PostCSS
plugin for this as well.
The following CSS code defines a grid tracking the line height:
I often need a quick calculation or a unit conversion. Rather than reaching for
a separate tool, a few lines of Zsh configuration turn = into a calculator.
Typing = 660km / (2/3)c * 2 -> ms gives me 6.60457 ms1 without
leaving my terminal, thanks to the Zsh line editor.
The equal alias
The main idea looks simple: define = as an alias to a calculator command. I
prefer Numbat, a scientific calculator that supports unit conversions.
Qalculate is a close second.2 If neither is available, we fall back to
Zsh s built-in zcalc module.
As the alias built-in uses = as a separator for name and value, we need to
alter the aliases associative array:
With this in place, = 847/11 becomes numbat -e 847/11.
The quoting problem
The first problem surfaces quickly. Typing = 5 * 3 fails: Zsh expands the *
character as a glob pattern before passing it to the calculator. The same issue
applies to other characters that Zsh treats specially, such as > or . You
must quote the expression:
$ ='5 * 3'15
We fix this by hooking into the Zsh line editor to quote the expression
before executing it.
Automatic quoting with ZLE
Zsh calls the line-finish widget before submitting a command. We hook a
function that detects the = prefix and quotes the expression:
_vbe_calc_quote()case$BUFFERin"="*)typeset-g_vbe_calc_expr=$BUFFER# not used yetBUFFER="= $ (q-)$ $ BUFFER#=# ";;esac
add-zle-hook-widgetline-finish_vbe_calc_quote
When you type = 5 * 3 and press , _vbe_calc_quote strips the =
prefix, quotes the remainder with the (q-) parameter expansion flag,
and rewrites the buffer to = '5 * 3' before Zsh submits the command. As a
bonus, you can save a few keystrokes with =5*3!
You can now compute math expressions and convert units directly from your shell.
Zsh automatically quotes your expressions:
The metric system is the tool of the devil! My car gets forty rods to the hogshead, and that's the way I like it! Grampa Simpson, A Star Is Burns
Storing unquoted history
As is, Zsh records the quoted expression in history. You must unquote it
before submitting it again. Otherwise, the ZLE widget quotes it a second time.
Bart Schaefer provided a solution to store the
original version:
The zshaddhistory hook returns 1 if we are evaluating an expression, telling
Zsh not to record the command. The preexec hook then adds the original,
unquoted command with print -s.
The complete code is available in my zshrc. A common alternative is the
noglob precommand modifier. If you stick with to instead of ->
for unit conversion, it covers 90% of use cases. For a related Zsh line editor
trick, see how I use auto-expanding aliases to fix common typos.
This is the fastest a packet can travel back and forth between
Paris and Marseille over optical fiber.
Qalculate is less understanding with units. For example, it parses
Mbps as megabarn per picosecond:
Akvorado, a network flow collector, relies on Traefik, a reverse HTTP
proxy, to expose HTTP endpoints for its Docker Compose services. Docker
labels attached to each service define the routing rules. Traefik picks them
up automatically when a container starts. Instead of maintaining a static
configuration file to collect Prometheus metrics, we apply the same approach
with Grafana Alloy.
Traefik & Docker
Traefik listens for events on the Docker socket. Each service advertises its
configuration through labels. For example, here is the Loki service in Akvorado:
Once the container is healthy, Traefik creates a router forwarding requests
matching /loki to its first exposed port. Colocating Traefik configuration
with the service definition is attractive. How do we achieve the same for
Prometheus metrics?
Metrics discovery with Alloy
Grafana Alloy, a metrics collector that scrapes Prometheus endpoints,
includes a discovery.docker component. Just like Traefik,
it connects to the Docker socket.1 With a few relabeling rules, we teach
it to use Docker labels to locate and scrape metrics.
We define three labels on each service:
metrics.enable set to true enables metrics collection,
metrics.port specifies the port exposing the Prometheus endpoint, and
metrics.path specifies the path to the metrics endpoint.
If a service exposes more than one port, metrics.port is mandatory. Otherwise,
it defaults to the only exposed port. The default value for metrics.path is
/metrics. The Loki service from earlier becomes:
This connects to the Docker socket and lists containers every 30
seconds.2 The filter block restricts discovery to containers belonging
to the akvorado project, avoiding interference with unrelated containers on
the same host. For each discovered container, Alloy produces a target with
labels such as __meta_docker_container_label_metrics_port for the
metrics.port Docker label.
Relabeling targets
The relabeling step filters and transforms raw targets from Docker discovery
into scrape targets. The first stage keeps only targets with metrics.enable
set to true:
discovery.relabel"prometheus"targets=discovery.docker.docker.targets // Keep only targets with metrics.enable=truerulesource_labels=["__meta_docker_container_label_metrics_enable"]regex=trueaction="keep" //
The second stage overrides the discovered port when the service defines
metrics.port:
// When metrics.port is set, override __address__.rulesource_labels=["__address__", "__meta_docker_container_label_metrics_port"]regex=(.+):\d+;(.+)target_label="__address__"replacement="$1:$2"
Next, we handle containers in host network mode. When
__meta_docker_network_name equals host, Alloy rewrites the address to
host.docker.internal instead of localhost:3
// When host networking, override __address__ to host.docker.internal.rulesource_labels=["__meta_docker_container_label_metrics_port", "__meta_docker_network_name"]regex=(.+);host target_label="__address__"replacement="host.docker.internal:$1"
The next stage derives the job name from the service name, stripping any
numbered suffix. The instance label is the address without the port:
prometheus.scrape periodically fetches metrics from the discovered targets.
prometheus.remote_write sends them to Prometheus.
Built-in exporters
Some services do not expose a Prometheus endpoint. Redis and Kafka are common
examples. Alloy ships built-in Prometheus exporters that
query these services and expose metrics on their behalf.
Each exporter is a separate component with its own relabeling and scrape
configuration. We set the job label explicitly since no Docker metadata can
provide it.
With this setup, adding metrics to a new service with a Prometheus endpoint
requires only a few labels in docker-compose.yml, just like adding a Traefik
route. Alloy picks it up automatically. You can apply the same pattern with
another discovery method, like discovery.kubernetes,
discovery.scaleway, or discovery.http.
Both Traefik and Alloy require access to the Docker socket, which
grants root-level access to the host. A Docker socket proxy mitigates
this by exposing only the read-only API endpoints needed for discovery.
Unlike Traefik, which watches for events, Grafana Alloy polls the
container list at regular intervals a behavior inherited from Prometheus.
The Alloy service needs extra_hosts:
["host.docker.internal:host-gateway"] in its definition.
I have unearthed a few old articles typed during my adolescence, between
1996 and 1998. Unremarkable at the time, these pages now compose, three decades
later, the chronicle of a vanished era.1
The word blog does not exist yet. Wikipedia has yet to come. Google has not
been born. AltaVista reigns over searches, while already struggling to
embrace the nascent immensity of the web2. To meet someone,
you had to agree in advance and prepare your route on paper maps.
The web is taking off. The CSS specification has just emerged, HTML tables still
serve for page layout. Cookies and advertising banners are making
their appearance. Pages are adorned with music and videos, forcing
browsers to arm themselves with plugins. Netscape Navigator sits on 86% of
the territory, but Windows 95 now bundles Internet Explorer to quickly catch
up. Facing this offensive, Netscape open-sources its
browser.
France falls behind. Outside universities, Internet access remains
expensive and laborious. Minitel still reigns, offering a phone
directory, train tickets, remote shopping. This was not yet possible with the
Internet: buying a CD online was a pipe dream. Encryption suffers from
inappropriate regulation: the DES algorithm is capped at 40 bits and
cracked in a few seconds.
These pages bear the trace of the web s adolescence. Thirty years have passed.
The same battles continue: data selling, advertising, monopolies.
Most articles linked here are not translated from French to English.
I recently noticed that Google no longer fully indexes my blog. For
example, it is no longer possible to find the article on lan o. I
assume this is a consequence of the explosion of AI-generated content or a
change in priorities for Google.
Standard RAID solutions waste space when disks have different sizes. Linux
software RAID with LVM uses the full capacity of each disk and lets you grow
storage by replacing one or two disks at a time.1
We start with four disks of equal size:
$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZEvda disk 101Mvdb disk 101Mvdc disk 101Mvdd disk 101M
We create one partition on each of them:
$ sgdisk--zap-all--new=0:0:0-t0:fd00/dev/vda
$ sgdisk--zap-all--new=0:0:0-t0:fd00/dev/vdb
$ sgdisk--zap-all--new=0:0:0-t0:fd00/dev/vdc
$ sgdisk--zap-all--new=0:0:0-t0:fd00/dev/vdd
$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZEvda disk 101M vda1 part 100Mvdb disk 101M vdb1 part 100Mvdc disk 101M vdc1 part 100Mvdd disk 101M vdd1 part 100M
We set up a RAID 5 device by assembling the four partitions:2
$ mdadm--create/dev/md0--level=raid5--bitmap=internal--raid-devices=4\> /dev/vda1/dev/vdb1/dev/vdc1/dev/vdd1
$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZE vda disk 101M vda1 part 100M vdb disk 101M vdb1 part 100M vdc disk 101M vdc1 part 100M vdd disk 101M vdd1 part 100M md0 raid5 292.5M$ cat/proc/mdstat
md0 : active raid5 vdd1[4] vdc1[2] vdb1[1] vda1[0] 299520 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/4] [UUUU] bitmap: 0/1 pages [0KB], 65536KB chunk
We use LVM to create logical volumes on top of the RAID 5 device.
$ pvcreate/dev/md0
Physical volume "/dev/md0" successfully created.$ vgcreatedata/dev/md0
Volume group "data" successfully created$ lvcreate-L100m-nbitsdata
Logical volume "bits" created.$ lvcreate-L100m-npiecesdata
Logical volume "pieces" created.$ mkfs.ext4-q/dev/data/bits
$ mkfs.ext4-q/dev/data/pieces
$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZE vda disk 101M vda1 part 100M vdb disk 101M vdb1 part 100M vdc disk 101M vdc1 part 100M vdd disk 101M vdd1 part 100M md0 raid5 292.5M data-bits lvm 100M data-pieces lvm 100M$ vgs
VG #PV #LV #SN Attr VSize VFree data 1 2 0 wz--n- 288.00m 88.00m
This gives us the following setup:
RAID 5 setup with disks of equal capacity
We replace /dev/vda with a bigger disk. We add it back to the RAID 5 array
after copying the partitions from /dev/vdb:
We do not use the additional capacity: this setup would not survive the loss of
/dev/vda because we have no spare capacity. We need a second disk replacement,
like /dev/vdb:
$ pvcreate/dev/md1
Physical volume "/dev/md1" successfully created.$ vgextenddata/dev/md1
Volume group "data" successfully extended$ vgs
VG #PV #LV #SN Attr VSize VFree data 2 2 0 wz--n- 384.00m 184.00m$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZE vda disk 201M vda1 part 100M vda2 part 100M vdb disk 201M vdb1 part 100M vdb2 part 100M md1 raid1 98.9M vdc disk 101M vdc1 part 100M vdd disk 101M vdd1 part 100M md0 raid5 292.5M data-bits lvm 100M data-pieces lvm 100M
$ mdadm--grow/dev/md1--raid-devices=4--add/dev/vdd2
mdadm: added /dev/vdd2$ cat/proc/mdstat
md0 : active raid5 vdd1[4] vda1[5] vdc1[7] vdb1[6] 299520 blocks super 1.2 level 5, 512k chunk, algorithm 2 [4/4] [UUUU] bitmap: 0/1 pages [0KB], 65536KB chunkmd1 : active raid5 vdd2[3] vda2[0] vdc2[2] vdb2[1] 303936 blocks super 1.2 level 5, 64k chunk, algorithm 2 [4/4] [UUUU] bitmap: 0/1 pages [0KB], 65536KB chunk$ pvresize/dev/md1
$ vgs
VG #PV #LV #SN Attr VSize VFree data 2 2 0 wz--n- 580.00m 380.00m$ lsblk-MoNAME,TYPE,SIZE
NAME TYPE SIZE vda disk 201M vda1 part 100M vda2 part 100M vdb disk 201M vdb1 part 100M vdb2 part 100M vdc disk 201M vdc1 part 100M vdc2 part 100M vdd disk 301M vdd1 part 100M vdd2 part 100M md0 raid5 292.5M data-bits lvm 100M data-pieces lvm 100M md1 raid5 296.8M
You can continue by replacing each disk one by one using the same steps.
Write-intent bitmaps speed up recovery of the RAID array after a
power failure by marking unsynchronized regions as dirty. They have an
impact on performance, but I did not measure it myself. An alternative
is to use a partial parity log with --consistency-policy=ppl.
In the lsblk output, /dev/md1 appears unused because the logical
volumes do not use any space from it yet. Once you create more logical
volumes or extend them, lsblk will reflect the usage.
Akvorado collects sFlow and IPFIX flows over UDP. Because UDP does
not retransmit lost packets, it needs to process them quickly. Akvorado runs
several workers listening to the same port. The kernel should load-balance
received packets fairly between these workers. However, this does not work as
expected. A couple of workers exhibit high packet loss:
Options for load-balancing
There are three methods to load-balance UDP packets across workers:
One worker receives the packets and dispatches them to the other workers.
All workers share the same socket.
Each worker has its own socket, listening to the same port, with the
SO_REUSEPORT socket option.
SO_REUSEPORT option
Tom Hebert added the SO_REUSEPORT socket option in Linux 3.9. The
cover letter for his patch series explains why this new option is better than
the two existing ones from a performance point of view:
SO_REUSEPORT allows multiple listener sockets to be bound to the same port.
[ ] Received packets are distributed to multiple sockets bound to the same
port using a 4-tuple hash.
The motivating case for SO_RESUSEPORT in TCP would be something like a web
server binding to port 80 running with multiple threads, where each thread
might have it s own listener socket. This could be done as an alternative to
other models:
have one listener thread which dispatches completed connections to workers, or
accept on a single listener socket from multiple threads.
In case #1, the listener thread can easily become the bottleneck with high
connection turn-over rate. In case #2, the proportion of connections accepted
per thread tends to be uneven under high connection load. [ ] We have seen the
disproportion to be as high as 3:1 ratio between thread accepting most
connections and the one accepting the fewest. With SO_REUSEPORT the
distribution is uniform.
The motivating case for SO_REUSEPORT in UDP would be something like a DNS
server. An alternative would be to receive on the same socket from multiple
threads. As in the case of TCP, the load across these threads tends to be
disproportionate and we also see a lot of contection on the socket lock.
Akvorado uses the SO_REUSEPORT option to dispatch the packets across the
workers. However, because the distribution uses a 4-tuple hash, a single socket
handles all the flows from one exporter.
SO_ATTACH_REUSEPORT_EBPF option
In Linux 4.5, Craig Gallek added the SO_ATTACH_REUSEPORT_EBPF
option to attach an eBPF program to select the target UDP socket. In Linux 4.6,
he extended it to support TCP. The socket(7) manual page
documents this mechanism:1
The BPF program must return an index between 0 and N-1 representing the socket
which should receive the packet (where N is the number of sockets in the
group). If the BPF program returns an invalid index, socket selection will
fall back to the plain SO_REUSEPORT mechanism.
In Linux 4.19, Martin KaFai Lau added the
BPF_PROG_TYPE_SK_REUSEPORT program type. Such an eBPF program
selects the socket from a BPF_MAP_TYPE_REUSEPORT_ARRAY map instead. This new
approach is more reliable when switching target sockets from one instance to
another for example, when upgrading, a new instance can add its sockets and
remove the old ones.
Load-balancing with eBPF and Go
Altering the load-balancing algorithm for a group of sockets requires two steps:
eBPF program in C
A simple load-balancing algorithm is to randomly choose the destination socket.
The kernel provides the bpf_get_prandom_u32() helper function to get a
pseudo-random number.
In , we declare a volatile constant for the number of sockets in the group. We
will initialize this constant before loading the eBPF program into the kernel.
In , we define the socket map. We will populate it with the socket file
descriptors. In , we randomly select the index of the target socket.3
In , we invoke the bpf_sk_select_reuseport() helper to record our decision.
Finally, in , we accept the packet.
Header files
If you compile the C source with clang, you get errors due to missing headers.
The recommended way to solve this is to generate a vmlinux.h file with
bpftool:
For my 6.17 kernel, the generated vmlinux.h is quite big: 2.7 MiB. Moreover,
bpf/bpf_helpers.h is shipped with libbpf. This adds another dependency for
users. As the eBPF program is quite small, I prefer to put the strict minimum in
vmlinux.h by cherry-picking the definitions I need.
Compilation
The eBPF Library for Go ships bpf2go, a tool to compile eBPF programs and
to generate some scaffolding code. We create a gen.go file with the following
content:
packagemain//go:generate go tool bpf2go -tags linux reuseport reuseport_kern.c
After running go generate ./..., we can inspect the resulting objects with
readelf and llvm-objdump:
$ readelf-Sreuseport_bpfeb.o
There are 14 section headers, starting at offset 0x840: [Nr] Name Type Address Offset[ ] [ 3] sk_reuseport PROGBITS 0000000000000000 00000040 [ 6] .maps PROGBITS 0000000000000000 000000c8 [ 7] license PROGBITS 0000000000000000 000000e8[ ]$ llvm-objdump-Sreuseport_bpfeb.o
reuseport_bpfeb.o: file format elf64-bpfDisassembly of section sk_reuseport:0000000000000000 <reuseport_balance_prog>:; 0: bf 61 00 00 00 00 00 00 r6 = r1; __u32 index = bpf_get_prandom_u32() % num_sockets; 1: 85 00 00 00 00 00 00 07 call 0x7[ ]
Usage from Go
Let s set up 10 workers listening to the same port.5 Each socket
enables the SO_REUSEPORT option before binding:6
The second step is to load the eBPF program, initialize the num_sockets
variable, populate the socket map, and attach the program to the first
socket.7
// Load the eBPF collection.spec,err:=loadReuseport()iferr!=nilt.Fatalf("loadVariables() error:\n%+v",err)// Set "num_sockets" global variable to the number of file descriptors we will registeriferr:=spec.Variables["num_sockets"].Set(uint32(len(fds)));err!=nilt.Fatalf("NumSockets.Set() error:\n%+v",err)// Load the map and the program into the kernel.varobjsreuseportObjectsiferr:=spec.LoadAndAssign(&objs,nil);err!=nilt.Fatalf("loadReuseportObjects() error:\n%+v",err)t.Cleanup(func()objs.Close() )// Assign the file descriptors to the socket map.forworker,fd:=rangefdsiferr:=objs.reuseportMaps.SocketMap.Put(uint32(worker),uint64(fd));err!=nilt.Fatalf("SocketMap.Put() error:\n%+v",err)// Attach the eBPF program to the first socket.socketFD:=int(fds[0])progFD:=objs.reuseportPrograms.ReuseportBalanceProg.FD()iferr:=unix.SetsockoptInt(socketFD,unix.SOL_SOCKET,unix.SO_ATTACH_REUSEPORT_EBPF,progFD);err!=nilt.Fatalf("SetsockoptInt() error:\n%+v",err)
We are now ready to process incoming packets. Each worker is a Go routine
incrementing a counter for each received packet:8
Graceful restart
You can also use SO_ATTACH_REUSEPORT_EBPF to gracefully restart an
application. A new instance of the application binds to the same address and
prepare its own version of the socket map. Once it attaches the eBPF program to
the first socket, the kernel steers incoming packets to this new instance. The
old instance needs to drain the already received packets before shutting down.
To check we are not losing any packet, we spawn a Go routine to send as many
packets as possible:
Then, while the Go routine runs, we start the second set of workers. Once they
are running, they start receiving packets. If we gracefully stop the initial set
of workers, not a single packet is lost!9
Unfortunately, gracefully shutting down a UDP socket is not trivial in Go.10
Previously, we were terminating workers by closing their sockets. However, if we
close them too soon, the application loses packets that were assigned to them
but not yet processed. Before stopping, a worker needs to call conn.Read()
until there are no more packets. A solution is to set a deadline for
conn.Read() and check if we should stop the Go routine when the deadline is
exceeded:
With TCP, this aspect is simpler: after enabling the net.ipv4.tcp_migrate_req
sysctl, the kernel automatically migrates waiting connections to a random socket
in the same group. Alternatively, eBPF can also control this
migration. Both features are available since Linux 5.14.
Addendum
After implementing this strategy in Akvorado, all workers now drop packets!
The root cause is the default limit of 32 records for Kafka batch sizes. This
limit is too low because the brokers have a large overhead when handling each
batch: they need to ensure they persist correctly before acknowledging
them. Increasing the limit to 4096 records fixes this issue.
While load-balancing incoming flows with eBPF remains useful, it did not solve
the main issue. At least the even distribution of dropped packets helped
identify the real bottleneck.
The current version of the manual page is incomplete and does not
cover the evolution introduced in Linux 4.19. There is a pending patch
about this.
Rust is another option. However, the program we use is so trivial that
it does not make sense to use Rust.
As bpf_get_prandom_u32() returns a pseudo-random 32-bit unsigned
value, this method exhibits a very slight bias towards the first indexes.
This is unlikely to be worth fixing.
Some examples include <linux/bpf.h> instead of "vmlinux.h". This
makes your eBPF program dependent on the installed kernel headers.
listenAddr is initially set to 127.0.0.1:0 to allocate a
random port. After the first iteration, it is updated with the allocated
port.
In C, we would poll() both the socket and a pipe used to signal for
shutdown. When the second condition is triggered, we drain the socket by
executing a series of non-blocking read() until we get EWOULDBLOCK.
Go s embed feature lets you bundle static assets into an executable, but it
stores them uncompressed. This wastes space: a web interface with documentation
can bloat your binary by dozens of megabytes. A proposition to optionally
enable compression was declined because it is difficult to handle all use
cases. One solution? Put all the assets into a ZIP archive!
The automatic variable$@ is the rule target, while $^ expands to all
the dependencies, modified or not.
Space gain
Akvorado, a flow collector written in Go, embeds several static assets:
CSV files to translate port numbers, protocols or AS numbers, and
HTML, CSS, JS, and image files for the web interface, and
the documentation.
Breakdown of the space used by each component before (left) and after (right) the introduction of embed.zip.
Embedding these assets into a ZIP archive reduced the size of the Akvorado
executable by more than 4 MiB:
Performance loss
Reading from a compressed archive is not as fast as reading a flat file. A
simple benchmark shows it is more than 4 slower. It also allocates some
memory.2
Each access to an asset requires a decompression step, as seen in this flame
graph:
🖼 Flame graph when reading data from embed.zip compared to reading data directly
CPU flame graph comparing the time spent on CPU when reading data from embed.zip (left) versus reading data directly (right). Because the Go testing framework executes the benchmark for uncompressed data 4 times more often, it uses the same horizontal space as the benchmark for compressed data. The graph is interactive.
While a ZIP archive has an index to quickly find the requested file, seeking
inside a compressed file is currently not possible.3 Therefore, the files
from a compressed archive do not implement the io.ReaderAt or io.Seeker
interfaces, unlike directly embedded files. This prevents some features, like
serving partial files or detecting MIME types when serving files over HTTP.
For Akvorado, this is an acceptable compromise to save a few mebibytes from an
executable of almost 100 MiB. Next week, I will continue this futile adventure
by explaining how I prevented Go from disabling dead code elimination!
You can safely read multiple files concurrently. However, it does
not implement ReadDir() and ReadFile() methods.
You could keep frequently accessed assets in memory. This
reduces CPU usage and trades cached memory for resident memory.
SOZip is a profile that enables fast random access in a compressed
file. However, Go s archive/zip module does not support it.