Viltrum 1.x: I Threw the Engine Away and Rewrote It

8 min read vlang viltrum http epoll tls performance systems open-source v

When I first wrote about Viltrum in July, I said: "No HTTP/2. No TLS. Good thing, too; no distractions."

Three months later, we're at v1.5. There's TLS, there's WebSocket, there's static files and uploads. HTTP/2 still isn't there, so I kept my word on that one.

But the real story isn't these features. Somewhere in between, I threw the whole engine in the trash once.

What 0.x was

The 0.x series ran from July to October. A spawn per connection, my own HTTP/1.1 parser, upgrades via hijack, WebSocket, TLS on top of mbedtls (reloading the certificate on SIGHUP), forms, a small HTTP client. In v0.13 I squeezed the hot path quite a bit.

Then I took a step back: no matter how much I squeezed, the model was the same. A spawn per connection, allocations per request. Instead of building another floor on top, the foundation had to change.

I shipped 1.0 on October 15 and wrote this in the CHANGELOG: TLS, WebSocket, static files, forms and the client are not in 1.0. I deleted all of them. From a user's point of view it looked like a step backwards, and it was. But I didn't want to keep anything that hadn't been moved onto the new core.

1.0's one rule

The core was written from day one with a single rule: zero allocations per request inside the framework. And that rule isn't a statement of intent, it's a test in CI:

// The acceptance gate of the whole rewrite: once buffers have grown to their working
// size, serving a request allocates nothing on the GC heap.
fn test_hot_path_allocates_nothing() {
	mut w := new_worker(make_router(), Options{}, 0)
	mut c := new_conn()
	for name, raw in shapes {
		req := raw.bytes()
		for _ in 0 .. 200 {
			run(mut w, mut c, req)
		}
		before := http1.allocated_bytes()
		for _ in 0 .. 10000 {
			run(mut w, mut c, req)
		}
		assert http1.allocated_bytes() - before == 0, '${name} allocates'
	}
}

200 requests warm up the buffers, and if the GC heap grows by even one byte over the next 10,000 requests, the test goes red. Every PR goes through this gate.

A few decisions make this possible:

  • One worker per CPU. Each one has its own SO_REUSEPORT listener and its own epoll loop. Whichever worker a connection lands on, it stays there for its whole life. On the request path, workers don't wait on each other.
  • Fixed buffers per connection. 8 KiB for reading, 16 KiB for writing. They grow for large messages and shrink when the connection closes.
  • Request strings are views, not copies. c.path(), c.param(), c.body() point into the connection's buffer and stay valid until the handler returns. If you want to keep one, .clone() it.
  • Pipelining is a single send. However many complete requests arrive in one read, all of them get answered, and the responses go out in a single send.

Two bugs the gate couldn't see

I wrote the test, it went green, I relaxed. I relaxed way too early.

First: V's GC pins. When V 0.5.2 compiles with -prod and Boehm GC, it puts a scan around every function call made while a by-value struct or array holding pointers is in scope. Once the pointer count goes over 32, it callocs a root list and takes the GC's global lock. The allocation gate can't see this, because technically the heap doesn't grow. But every worker queues up on the same lock.

The JSON encoder was doing this once per element on a 40-element page. At 8 threads that was 400 µs of CPU per request, at a single thread 50 µs. After the fix, on a 12-thread Ryzen 5 3600, json-comp went from 19.9 thousand requests/sec to 51.6 thousand. CI now has scripts/gcpin_check.sh, which fails the build if it sees a pin on the hot path.

Second: a Conn per fd. fd numbers are process-wide. With SO_REUSEPORT, any worker can get any fd number. Each worker was keeping a Conn for every fd number it had ever seen. With connections constantly opening and closing, every worker ends up allocating a Conn for almost every fd, each one with 24 KiB of buffers. At 64 workers that adds up to gigabytes, and every allocation takes the GC lock again.

On HttpArena's short-lived profile (10 requests per connection), they measured 158 thousand requests/sec, 373% CPU and 2.2 GiB of memory. With one free list per worker, the same scenario on my 8-core server came down to 223 thousand requests/sec and 233 MiB. Today that profile is at 2.70 million requests/sec on HttpArena.

The lesson I took from both: a "no allocations" test is necessary but not enough. You have to measure lock and memory behavior separately.

Deferred responses: timers

1.1 brought c.after(ms, cb, arg). The handler returns right away and doesn't hold the worker; ms milliseconds later, cb writes the response on the same worker. Underneath there's one min-heap per worker. The epoll loop waits until the next timer.

This week I found a nice bug here. epoll_wait takes its timeout in whole milliseconds. To avoid firing early, I was rounding the remaining time up. A request that should have been answered after 0.2 ms went out after 1 ms. Under load this piles up: a /delay/10 request was getting an extra 1.0 to 1.7 ms on top of its 10 ms.

The fix is epoll_pwait2. It's been around since Linux 5.11 and takes the timeout in nanoseconds. If the kernel doesn't support it or seccomp rejects it, it falls back to the old path. On my own server the overshoot dropped to 0.3-0.4 ms, and requests/sec went up 7-13%. The cost is 15-25% more CPU per request, because timers now fire in smaller batches. This change shipped in v1.5.1.

TLS: the handshake in mbedtls, the records in my code

Viltrum has a rule: no third-party dependencies. No vendored C code either. Only what ships with V itself. That's why TLS sits on top of mbedtls 3.6, which comes bundled with V.

In 1.2, TLS moved onto the same epoll workers. Non-blocking handshake, WANT_READ / WANT_WRITE translated into epoll, the certificate reloaded when the file changes (no SIGHUP, it watches the file), and a half-written certificate pair never replaces the one in use.

Then I profiled it: on a 10 KB TLS echo, two thirds of the CPU was in mbedtls's GCM. mbedtls pushes a record through the cipher layer in 16-byte blocks.

In 1.3.2, once the TLS 1.3 handshake finishes, I started doing the records myself: AES-GCM with AES-NI and PCLMULQDQ in engine/aesgcm.h. The methods are the ones Intel published, the code is mine. Eight counter blocks side by side, GHASH with a single reduction per eight blocks, tags checked in constant time before decryption. For correctness there are the GCM specification's test vectors and a comparison against mbedtls on 1200 random inputs.

The handshake, TLS 1.2, ChaCha20 and CPUs without AES-NI stayed in mbedtls.

Result: CPU per 10 KB echo went from 283-357 µs down to 135-171 µs.

gzip: my own DEFLATE

In the json-comp profile, gzip was half the profile. The miniz that ships with V is a streaming compressor: on every call it clears roughly 97 KB of window and hash state and runs the input through a ring buffer. For a 1 KB JSON that's way too much setup.

Adding libdeflate came up. The rule was clear: no dependencies. So I'd write libdeflate's ideas myself.

http1/deflate.v compresses the body in place. Chunks of up to 64 KB, a hash table sized to the chunk, hash chains with a single lazy step, the smallest block type per chunk (dynamic, fixed or stored), slice-by-8 CRC-32. State is allocated once per worker, zero allocations per call.

I tuned the search depth to json-comp's scoring formula. There, HttpArena multiplies requests/sec by (smallest size / my size)², so every byte counts. On the profile's three JSON bodies it's 52 µs per body, versus 126 µs for miniz at level 6. Size is 1263 B versus 1232 B, so a bit bigger but much faster.

WebSocket and topics

WebSocket came back in 1.3: app.ws(pattern, handler), RFC 6455, on the same workers, ws:// and wss://. Messages arrive as views into the read buffer, with no allocations on the echo path.

For topics (subscribe / publish) I gave each worker an inbox: a queue behind a mutex and an eventfd in the epoll set. Publish copies the message once and drops it into each worker's queue, and each worker writes to its own subscribers. A connection's buffers never leave its own worker.

What's missing

  • HTTP/2. The decision is pending. First h2c, then h2 over TLS with ALPN, but I haven't started yet.
  • HTTP client. It was in 0.x, it didn't get moved to the 1.x core.
  • Serving outside Linux. The engine is epoll. On macOS and Windows, tests and examples compile in CI and you can test handlers with handle_raw, but listen returns an error.
  • recover doesn't catch real panics. V can't catch a panic, the process exits. Run it behind a supervisor like systemd's Restart=always.

Try it

git clone https://github.com/Tuntii/viltrum.git && cd viltrum
bash scripts/install.sh
v run examples/hello
# in another terminal
curl http://127.0.0.1:8080/

Repo: github.com/Tuntii/viltrum. The roadmap is in ROADMAP.md, and so is what we're not going to do.

At the end of the July post I said "if you don't like it, open an issue". That still stands. Let me add this too: rewriting the engine looks scary, but the scary part is writing it without tests. With the gate in place, deleting is easy.

In the next post I'll explain where these numbers come from: HttpArena, A/B measuring on a noisy VM, and the medals I lost yesterday.

← Blog