Intro
The other day I was scraping the National Weather Service API so that I could have emergency weather alerts on the e-ink dashboard on my wall, you know, as you do.
But I got to thinking, how much additional load am I adding to this free service? Not a lot of course, but why do I have to poll anyway?
I hate polling. It is just so wasteful in the majority of cases. I cringe when I think of the billions upon billions of things that are polling some system, only because there is no convenient way to get a push.
The only polling I can get behind is when NICs automatically transition from events to polling in high frames-per-second situations. This is what Linux’s NAPI does. When the first interrupt under load masks further interrupts, the driver starts polling the receive ring in batches. This reduces load, but only because in heavy traffic we know there will always be work to do. Otherwise it falls back to interrupt mode.
Other than that case, most polling is just wasteful and sucks.
I really like my friend Joey’s solution to “getting rid of all the pollers”: vwatch.
vwatch can sit in front of any versioned artifact (anything with an ETag, hash, or version: a Docker registry, S3, a versioned API) and centralize the notifications (or polling) in one place, so all the clients can do a normal blocking HTTP connection instead of polling.
It takes the load off your main app by allowing you to infinitely scale the number of watchers.
Why can’t every National Weather Service API customer just keep an open connection and get a push/interrupt when there is bad weather?
Of course this is a hard problem. Keeping connections open is expensive. State is bad, blah blah blah.
But actually, how hard would it be to hold, say, 1 BILLION connections open in 2026?
Background: The C10k, C1M, and C10M Problems
C10k
In 1999, Dan Kegel wrote The C10k problem, asking how a web server could handle ten thousand clients at once. This was very hard at the time because of the traditional design of having one thread/process per connection. The answer turned out to be non-blocking sockets and event notification APIs like epoll on Linux and kqueue on BSD. These days Wikipedia describes it as “long solved”.
C1M
The next milestone was a million connections on one server (C1M). In 2012, WhatsApp wrote that they could push a single box to over 2 million TCP connections, using Erlang on FreeBSD. In 2015, the Phoenix team got 2 million websocket connections on one server. By now C1M is common enough that projects ship configs for it, like Pushpin’s.
C10M
After that came C10M. In 2013, Robert Graham argued that the kernel is the problem, not the solution, and that getting to 10 million means moving the network stack out of the kernel. MigratoryData reported 10 million concurrent connections on a single commodity server, with the Linux kernel using about 32 GB of memory just to hold the sockets open.
I couldn’t find anyone who has tried a billion.
So here I am solving C1B on the cheap with my laptop?
Constraints
Every good problem space has constraints. Here are mine:
- Must literally run on my laptop
- 16 GB of RAM
- 1 GbE NIC
- Real, open TCP/IP connections
- Real HTTP server that can push1
- Pretend I don’t have Comcast
- Must scale to 1 billion connections
- IPv4 only2
Memory Math
To get to 1 billion TCP connections on a single laptop, you’re going to have to bypass the kernel (“obviously”).
That’s the easy part. The hard part is doing your own TCP/IP in such a way that it can handle all these connections with my constraints.
Let’s look at some napkin math first to see what we’re up against.
I opened 50,000 idle TCP connections on my laptop (Linux kernel 6.8) and checked how much kernel memory each one costs. It’s about 4 KB per connection on the server side. At that rate 1 billion connections needs about 4 TB of RAM, which is 250x what my laptop has!
Where Does the Memory Go?
Here’s the kernel memory for one idle server-side connection:
| What | Bytes |
|---|---|
TCP socket (struct tcp_sock) |
2,368 |
| Socket inode | 832 |
Open file (struct file) |
256 |
| dentry | 192 |
| epoll entry | 128 |
| Total | ~4,000 |
That’s for a connection with no data waiting yet. As soon as data arrives, the kernel allocates buffers on top of this, at least a few KB more.
Our Budget
16 GB divided by 1 billion connections is 16 bytes per connection 🫠.
The absolute bare minimum TCP needs to remember per-connection is already most of that budget:
| What | Bytes | Bits |
|---|---|---|
| Client IPv4 address | 4 | 32 |
| Client port | 2 | 16 |
| Our sequence number | 4 | 32 |
| Their sequence number | 4 | 32 |
| Total | 14 | 112 |
That leaves … 2 whole bytes for everything else!
TCP experts are getting antsy here. What about timers? What about the window scaling? What about TCP options?
I promise we don’t need any of that stuff where we are going. See later in the post where I explain how we can get away without that stuff.
Squeezing the Address
The address is where the savings are. An IP and port is 48 bits, but the table holding a billion of them doesn’t need to store all 48.
We are going to use one mega hash table.
Imagine if that hash table had two big buckets.
Just put all the IPs that start with 0 in the first bucket, and 1 in the second bucket.
Now you don’t need to store the leading bit at all, because we can extract that information from which bucket it is in!
Just keep doing that trick with more buckets!
There is a slight problem in that IP addresses are “clumpy”. It would be sympathetic to the hash table if they were all incoming random bits…
We can do that actually. The trick is to scramble the address with a reversible, keyed shuffle and use the top bits of the result to pick a bucket. Now the bucket’s position already tells you most of the address, and each record only stores what’s left over.
Follow one address through it.
Say 203.0.113.42:51201 connects:
| Step | Our example |
|---|---|
| A connection arrives | 203.0.113.42 : 51201 |
| Pack the IP and port into 48 bits | 11001011 00000000 01110001 00101010 + 11001000 00000001 |
| Scramble with a keyed, reversible shuffle | 10110100101101001011010010 1101001010010110100101 |
| Top 26 bits pick the bucket | bucket #47,370,962 (which we don’t need to bother storing) |
| Low 22 bits are the remainder | 1101001010010110100101 = 3,450,277 (this we store) |
| +1 bit: which of two candidate buckets3 | tag 0 or 1 |
| Written to memory | 23 bits: the 22-bit remainder plus the 1-bit tag |
The top 26 bits never hit memory.
They’re implied by which bucket the record sits in: position is free storage.
To find the connection again, the bucket’s position hands back those top 26 bits, the record hands back the low 22, you glue them into the scrambled 48 bits and run the shuffle backwards to recover 203.0.113.42:51201 exactly.
Solving A Real Problem
I didn’t want just a “hello world” webserver. I wanted to build something that actually could serve NWS notifications to 1 BILLION clients.
That forced me to solve a real problem, and make room for counties, subscriptions, and actual alerts.
Here is what the API looks like.
A client subscribes to a county by opening one plain HTTP connection and leaving it open:
curl -N http://10.4.0.2/alerts/OKC109
OKC109 is the NWS code for Oklahoma County: two letters for the state, a C, then the county’s three-digit FIPS code.
The server answers with an event stream and waits:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-store
: subscribed
When a warning lands for that county, every connection subscribed to it gets the same push:
event: alert
data: Tornado Warning until 6:15 PM
The NWS Record
Here is everything the server remembers about one idle connection:
| What | Bits |
|---|---|
| Client address (in our special packed form) | 23 |
| Our sequence number | 32 |
| Their sequence number | 32 |
| County subscribed to | 12 |
| Age (missed keepalives) | 2 |
| Total | 101 |
That’s 12.6 bytes. Records sit ten to a 128-byte bucket, so 12.8 bytes per slot. In the real run, with buckets not quite full, it came to 13.4 bytes per connection.
But I can hear you already.
There is a lot of other “stuff” you need in memory to serve a web request over TCP/IP.
What about…
SYN, ACK, TCP Windows, etc?
There is NO handshake state! Every connection starts with a SYN cookie. More on this trick below.
TCP Timers?
There are no per-connection timers. Instead, a background sweep walks the table and a record’s position decides when it gets a TCP keepalive.
Regular old buffers for packet data?
We don’t need any per-connection buffers, because every message fits in one 536-byte packet.
TLS, keys, etc
Sorry, no TLS. The keys alone would be several times the size of the whole record. Just HTTP for this one.
The Network Budget
Let’s talk about the gigabit NIC constraint.
Could a gigabit NIC actually pull this off? Could it really handle 1 billion connections?
1 Gbit/s divided by 1 billion connections is 1 bit per second per connection in each direction.
| What | Bytes on the wire | @ 1 billion connections |
|---|---|---|
| One keepalive | 84 out, 84 in | every 30 minutes uses 37% of the link |
| One 400-byte NWS alert | 474 out, 84 in | about 166,000 alerts per second with what’s left |
| One new established connection | 285 out, 370 in | filling the table takes about 50 minutes |
So an alert to a county with a million subscribers takes about 6 seconds. An alert to all billion subscribers takes over an hour and a half.
But generally, yes!
A gigabit NIC can do it.
Implementation
An Ode to SYN Cookies
I remember the first time I encountered SYN cookies, when I saw a mysterious dmesg line that read like this:
TCP: possible SYN flooding on port 80. Sending cookies. Check SNMP counters.
I remember looking it up and it being a little bit over my head at the time. I had no idea about the mechanics of TCP/IP when I first got into computers.
I encountered it again later in my career when I was copy-pasting from some generic server-hardening guide.
It was only later, when I was taking my CCNA class at my local community college, that I really learned what the heck it was doing.
It’s cool that now, for this project, I have to reimplement it, because we’re bypassing the kernel. And we need SYN cookies, because without them we would not have enough RAM to store all of the TCP/IP state to track everything.
A normal TCP server has to remember the incoming client’s sequence number, the options it saw, and the fact that this half-open connection exists at all.
It has to hold that state through the round trip until the client’s ACK comes back.
Wouldn’t it be cool if we didn’t need to store anything for this?
This is what SYN cookies do.
Instead of storing anything when the SYN arrives, we encode everything we need into the one number the client is obligated to echo back: our initial sequence number.
The technical details of how SYN cookies are encoded are beyond the scope of this blog post, please read the Wikipedia article for details.
Results
Hitting One Billion (Simulated)
Without asking a billion iPhones to query my API, I could simulate on localhost first. Here is how it went:
| What | Result |
|---|---|
| Connections held | 1,000,000,000 |
| Connections lost | 0 |
| Memory used | 12.51 GiB |
| Bytes per connection | 13.4 |
| Time to fill | 62 minutes |
| Connections per second | about 264,000 |
| Random lookup | 482 ns |
| Alert to one county (312,500 subscribers) | 9.7 seconds |
The system was working. Next, using a real gigabit link.
Hitting One Billion Over a Real Gigabit Link
For real packets, I had to run a load generator on a second machine. It was kinda slow. I just couldn’t generate enough packets per second on a single load generator to really exercise the line rate.
The server uses a raw socket here, not a proper kernel bypass. And the server is single-threaded.
That is ok, the important part is how well it can handle lots of connections, it doesn’t matter too much to me how fast I can generate those connections at my house.
| What | Result |
|---|---|
| Clients that tried to connect | 1,020,000,000 |
| Connected | 1,018,637,006 (99.87%) |
| Time to pass one billion | 3 hours, 5 minutes |
| New connections per second | 90,000 |
| Server memory | 12.54 GiB |
| Still connected 17 hours later | 1,018,566,801 |
| Keepalives sent in those 17 hours | 2.09 billion |
| Connections dropped by mistake | 70,205 (0.007%) |
| Alert to one county (1,018,540 subscribers) | all delivered |
I didn’t create 1 billion IP addresses to run this benchmark. Instead my load generator spoofs IPs, but makes sure the destination MAC address is my laptop, so they don’t accidentally go out to the internet.
The clients here are kinda stubs, it isn’t exercising the kernel’s TCP stack, just like the server doesn’t!
While ramping up, the link was only about 20% full. My home lab just isn’t a home datacenter yet.
Conclusion
The source code is here.
Obviously it is not some production-grade TCP stack, but it really does scale to a billion.
Some future work here is to explore XDP and other kernel bypass techniques instead of my simple TUN-based thing.
SSL would also be cool, but I would run out of CPU for sure. And there is no way I could do 1 billion in 16 GB of RAM with the encryption overhead.
I don’t really know if this thing is applicable in the real world. Things like Pushpin are kinda the only real world example that I found that is like this.
-
It uses Server-Sent Events. ↩︎
-
Don’t get me wrong, I’m an IPv6 true believer, but for this experiment I stuck with single stack IPv4 for simplicity and RAM usage. ↩︎
-
This is cuckoo hashing. ↩︎