xin

← Blog

Inside Xin Architecture: Memory-Safe, Fast, and NGINX-Compatible

Xin isn’t NGINX. We built it from the ground up, in Rust, as a proxy and web server that runs the NGINX configuration you already have. We believe a daemon that faces the network and parses untrusted input all day has to be held to a higher standard than most software: memory safe, running with as little privilege as possible, and secure by construction. Xin is built to that standard, and for environments where configuration changes many times an hour. This post covers which ideas we kept from NGINX’s design and which we redesigned.


What we were aiming for

Memory safety. On NGINX’s own security advisories page, more than half of the entries are buffer overflows, use-after-frees, out-of-bounds reads, or similar memory errors. That is what decades of careful C with hand-managed memory pools looks like, in one of the better C codebases around. A new server that parses untrusted bytes all day should not repeat it, so we wrote Xin in Rust. Our earlier post on recent NGINX vulnerabilities goes through specific cases.

Rust also checks concurrency. Code in which two threads can touch the same data without synchronization does not compile, which removes data races as a class. The design below shares a lot of state between threads, so this matters. We wrote about a real-world data race in another server in this post.

Performance. Xin is event-driven, with one event loop per core, as NGINX is. There is no garbage collector.

Security beyond memory safety. The process that handles requests holds no privileges. The part that does is as small as we could make it.

Modern deployments. Many proxies now run where software generates the configuration and changes it constantly. Kubernetes is the best-known example, with a new configuration possible every time a pod starts or stops. Service discovery and automated certificate renewal produce the same pattern. A server in that position has to absorb each change without dropping connections or resetting rate limiters and caches.

Where NGINX’s design fits less well today

NGINX’s architecture is a good answer to the problem it was built for, and it has held up for two decades. A root master process supervises single-threaded worker processes, each running an event loop. Workers are isolated, so a crash in one costs only its own connections. Configuration is a file, and a reload either succeeds completely or leaves the old configuration running. That model is easy to reason about.

master process root
reads configuration · opens listening sockets and log files · loads TLS keys · starts and replaces workers
fork — workers inherit the sockets and loaded keys, then switch to the unprivileged user
worker processone event loop
own memory
worker processone event loop
own memory
worker processone event loop
own memory
shared memory zonesrate and connection limiters · cache index · TLS session cache · upstream state
NGINX’s process model: workers are separate processes, so state they must agree on lives in shared memory zones declared in the configuration.

Four things about it get expensive for the goals above.

A reload replaces every worker

On HUP, the master builds the new configuration, starts a complete new set of workers, and asks the old ones to shut down gracefully. An old worker closes its listening sockets and idle connections, stops offering keep-alive, and exits when its remaining work is done. Unless worker_shutdown_timeout is set, there is no deadline. One long download, WebSocket, or stream keeps that whole process alive, along with its copy of the old configuration.

old worker 1serving
old worker 2servingshutting down, one WebSocket still open
new worker 1serving new configuration
new worker 2serving new configuration
reloadconnection closes
An NGINX reload over time: an old worker stays until its last connection ends, and by default nothing forces it to exit sooner.

With a couple of reloads a day, nobody notices. When reloads are generated automatically and arrive faster than long-lived connections end, shutting-down workers stack up, and each one is a full process.

The root process reads the configuration, every time

The master stays root for its whole life. On every reload it reparses the entire configuration, opens log files, creates temporary directories, binds new listening sockets, and loads certificates and private keys. Workers drop to the unprivileged user only after they are forked. That is convenient, because anything root can read, a reload can pick up. It also means the component that interprets operator-supplied text is the one holding root, and it does so again on each reload, in C.

Processes can only share state through shared memory

Workers are separate processes, so anything that must be consistent across them lives in a shared memory zone that the configuration declares and sizes in advance. It works well, and zones with an unchanged name and size carry over a reload. But every new piece of cross-worker state needs a zone, and state outside a zone is per-worker.

Configuration is a file and a signal

To change what open source NGINX is doing, you write new files and signal the master, which takes the full reload path above. That suits a file an operator edits by hand. It is a lot of machinery for a program that only needs to add one backend to one pool.

How we re-architected

One internal model, several configuration dialects

Configuration now arrives from programs as well as from files, and the engine should not care which. So Xin’s data plane runs from an internal model of listeners, virtual servers, routing rules, upstream pools, and policies. Each configuration dialect has its own compiler that parses the input, validates it, and produces that model. Today there are four: NGINX configuration files, Envoy’s xDS resources, the Kubernetes Gateway API, and Kubernetes Ingress.

NGINX config files
Envoy xDS
Gateway API
Ingress
parse · validate · compile
Internal modelthe only thing the data plane executes
↓
Data planerequest pipeline · upstream pools · TLS · caches · limiters
The engine sees the same model whether it came from a file or from a controller.

The model had to be rich enough for NGINX, the most demanding of the four. NGINX configuration does much more than map paths to backends. Location matching has its own precedence, rewrite ... last restarts routing with a new URI, and try_files and error_page are control flow. So the engine is a pipeline of request phases over a set of variables, much like NGINX’s own. Envoy’s ordered route list fits the same pipeline.

An operator sending HUP and a controller reacting to a new pod take the same path inside the engine. The reload work described below applies to both.

Threads instead of worker processes

We kept NGINX’s one event loop per worker, but our workers are threads. In Xin, worker_processes sets the number of worker threads inside a single serving process. Each thread runs its own single-threaded event loop, can be pinned with worker_cpu_affinity, and keeps the connections it accepts.

broker root
holds the listening sockets · no configuration parser · no request handling
starts the serving process and hands it the sockets
serving process unprivileged
worker threadone event loop
worker threadone event loop
worker threadone event loop
shared in-process statelimiters · caches · upstream health · current configuration snapshot
Xin’s process model: the workers are threads in one unprivileged process, and the state they share is ordinary memory.

The case for threads gets stronger as core counts grow. In NGINX, anything outside a shared memory zone exists once per worker. Passive health checking is a good example. The failure count behind max_fails lives in each worker’s own memory unless the upstream block declares a zone. On a machine running sixteen workers, that is sixteen separate opinions about whether a backend is healthy, and each worker has to see the failures for itself before it stops sending traffic there. In Xin every worker thread updates the same record. A failing backend leaves rotation for the whole server once the configured number of failures has been seen, wherever they were seen. The same max_fails value trips sooner in Xin than on a many-worker NGINX.

The rest of the shared state works the same way. Limiter counters, caches, and upstream health are data structures every worker thread can see, partitioned so that unrelated keys do not contend. None of them needs a zone declared and sized first. The zone directives are still accepted, and their names still identify the state they refer to.

Threads also make the cost of a configuration change independent of the number of workers. There is one parsed configuration in the process, and every thread reads it through the same pointer. Publishing a new one is a single swap, whether the server has two workers or sixty-four. An NGINX reload starts as many new processes as there are workers.

The hot path keeps its shape. Each thread has its own event loop and its own pool of idle upstream connections, as an NGINX worker does, so serving a request involves no handoff between threads. By default all threads accept from one listening socket per address. With listen ... reuseport, each thread gets its own socket and the kernel spreads connections across them. NGINX offers the same two arrangements.

Threads sharing memory is where data races come from. The compiler rejects code that lets two threads reach the same data without a lock or an atomic type, so the limiter tables, the caches, and the pointer to the current configuration had to be built from synchronized types before they would compile. In C we would have hesitated to give up process boundaries. Rust does not prevent deadlocks or two correctly locked operations running in an order we did not intend. Those remain ours to get right.

A small broker instead of a root master

We wanted the process that reads configuration and handles requests to hold no privilege at all, including during a reload. On Linux, the process you start parses the configuration once and works out two lists: the addresses to listen on, and the directories that hold files the server will need later, such as certificates, keys, and logs. It then starts a second copy of itself as the serving process and settles into a much smaller role, the broker.

The broker stays root, but it has no configuration parser and no request-handling code. It holds the listening sockets, and it does a handful of things when the serving process asks: open a file under one of the directories on its list, bind another address, or start a successor for a binary upgrade. The serving process switches to the configured user, gives up its capabilities, and checks that the kernel agrees before it serves anything. Every later reload is parsed without privilege. When a reload needs a file only root can read, such as a renewed private key, the serving process asks the broker. The broker checks the request against its list both as written and as the kernel resolved it, so a symbolic link cannot steer it elsewhere.

NGINX
master root
parses configuration at start and on every reload · opens files · binds sockets · loads keys
fork, then drop privileges
workers unprivileged
parse and serve requests
Xin
broker root
holds sockets · opens files under directories listed at startup
file and socket requests ↑ · descriptors ↓
serving process unprivileged
parses configuration on reload · parses and serves requests
In NGINX the root process interprets the configuration on every reload; in Xin that work happens in the unprivileged process, and root only answers a few fixed requests.

This sits under memory safety. Rust removes the most common way a network server gets taken over, and the unsafe code that remains is confined to specific places (more on that below). If something does go wrong in the serving process, the attacker is inside an unprivileged process whose only path to root is a broker that opens files from a fixed list of directories and little else.

Keeping the sockets in the broker has a second benefit. A reload does not rebind them, so connections waiting in the accept queue are kept. If the serving process dies, the broker starts a new one on the same sockets, and arriving connections wait in the queue. Binary upgrades follow the familiar NGINX sequence, with old and new serving processes accepting from the same sockets during the handover.

Reloads that swap configuration on running threads

When a new configuration arrives, Xin compares it with the running one and does only as much work as the difference requires.

If only the membership of an upstream pool changed, that pool is updated in place. Health history and in-flight counts are tracked per backend address, so the backends that stayed are untouched. The Kubernetes and xDS drivers use this when pods come and go, which in a busy cluster can happen every few seconds.

If routing changed (servers, locations, rewrites, headers, access rules, variables, the set of pools, certificate contents), Xin validates the whole new configuration, builds it off to the side as an immutable snapshot, and publishes it with a single atomic swap. No worker thread is created or stopped. Requests already in flight finish under the snapshot they started with, and the old snapshot is freed when the last of them completes.

A HUP under the NGINX personality goes through the same logic, and most reloads end up as a swap. Certificate files are read again on every reload, so a renewal takes effect with nothing else changing.

NGINX after a reload
master (root)unchanged
old workersshutting down until their last connection ends
new workersnew processes, new configuration
Xin after a reload
broker (root)unchanged
worker threadsunchanged
old snapshotheld only by requests still in flight
new snapshotevery new request
After a Xin reload the same threads are still running, and new requests are served from the new snapshot.

Some changes need more than a swap: a different set of listening addresses, different TLS handshake settings, new access-log destinations, changes to layer-4 stream configuration. For those, Xin starts a new set of accept loops on the worker threads that are already running and lets the previous set drain on those same threads. Only a new worker_processes value, which adds or removes exactly the difference, and a new worker_cpu_affinity touch the thread pool.

Caches, limiter counters, and upstream health live outside the snapshot and are matched to the new configuration by name, so a reload does not empty a cache or reset a rate limit. Clients move over the way they do in NGINX: a keep-alive connection that predates the change is closed after its current response, an HTTP/2 connection is told to go away, and both reconnect under the new configuration. And as in NGINX, if the new configuration fails any check, nothing is published and the running one stays in service.

Dynamic where NGINX is dynamic, checked up front where it is not

In NGINX, some directives are fixed when the configuration loads and others are evaluated for every request, from variables that hold the request’s own values. Xin splits them almost exactly the same way.

Everything static is validated when the configuration loads, so mistakes show up as a file and line from xinginx -t, not as a surprise in production. Everything dynamic is evaluated against the snapshot the request started under. A reload can swap the snapshot at any moment, and no request ever sees half of one.

At load, once per snapshot
structureservers, locations, upstream pools, zones, every directive’s syntax
files the broker openscertificate and key paths · password files · log files
validationerrors reported with file and line before anything is published
For every request, against that snapshot
routingrewrite · return · if · try_files · server_name captures
proxying and headersproxy_pass · proxy_set_header · add_header · proxy_redirect · charset
files, limits, logsroot · alias · limit_req and limit_conn keys · proxy_cache_key · log_format
Xin checks the shape of the configuration when it loads and evaluates the variables inside it for each request.

What is evaluated per request

Almost everything NGINX evaluates per request, Xin evaluates per request too.

What is fixed when the configuration loads

NGINX also lets a few directives take variables that Xin currently treats as fixed values:

All three name files. In Xin, files like these are opened through the broker, from the list of directories it was given at startup, before traffic arrives. That keeps the rule simple: the serving process never asks the broker to open a path that a request chose. A variable in one of these places is refused at load with the directive’s file and line.

We plan to add per-request versions that go through the broker, with a cache so the hot path does not pay for a round trip. Until then, per-host certificates are still easy to serve: list one server block per name. A handful of smaller settings are also fixed-value today, namely limit_rate and limit_rate_after, the replacement in proxy_cookie_domain and proxy_cookie_path, and proxy_ssl_name. xinginx -t names each one if your configuration puts a variable there.

What is not there yet

Some NGINX directives are not implemented yet, such as proxy_bind for HTTP, proxy_set_body, proxy_method, and a set of buffer-tuning directives. Xin refuses them at load and names the directive, so you find out from -t. The directive reference lists what is supported. perl and xslt are not planned.

A few differences on purpose

TERM is a fast shutdown in NGINX and a graceful one in Xin, because it is the signal process managers send by default and cutting responses off mid-body is rarely what anyone wanted. The Server header and generated error pages say xin. A variable name Xin does not know fails at load. The stream block and HTTP/3 are optional components that a default build leaves out, and a build without them tells you when a configuration needs them. Xin has no loadable modules. Features are compiled in, and load_module lines for modules it already includes are accepted so that existing files keep loading.

Trade-offs

Here is what this design costs.

No process isolation between workers. When one NGINX worker crashes, the others keep serving. A fault that takes down Xin’s serving process takes every connection with it, and the broker starts a new one on the same sockets. We are betting that memory safety and compile-time race checking remove most of the reasons a proxy crashes, and that one address space is worth it for everything above. Rust does not prevent logic errors, a panic on an unexpected state, or a deadlock, so the bet can lose, and when it does NGINX’s model would have limited the damage to one worker.

Not all of Xin is safe Rust. The NGINX configuration parser, the internal model, the HTTP/1 parser, and the request engine are compiled with unsafe code forbidden. Unsafe code remains where Xin calls the operating system directly, for privilege handling, passing descriptors between broker and serving process, sendfile, and kernel TLS, and in the per-request memory pool. Some dependencies are native code, including the cryptography library, the PCRE2 regular-expression engine, and the allocator. The memory safety page has the breakdown.

The broker learns directories at startup. Its list is fixed when the server starts, and a reload cannot extend it. Renewing a certificate in place works, because the new file lands in a directory that is already listed. A site whose certificates live in a directory the configuration did not mention before needs a restart, and so does a new temporary directory the unprivileged user cannot create for itself. Xin names the path and says a restart is needed. NGINX has no such limit, because its master redoes this work as root every time. We took the occasional restart in exchange for a root process that does far less.

The broker is Linux-only. On other platforms Xin runs as a single process that binds its sockets, loads its files, and then drops privileges. It still serves traffic unprivileged, but it cannot re-read root-only files on reload, restart itself after a crash, or upgrade its binary in place.

Compatibility is careful work. Matching what an NGINX configuration means includes the parts that surprise people: location precedence that ignores file order, inheritance where one directive in a location replaces everything inherited from above, defaults you would not guess. Existing configurations depend on each of these, so each has to match.

Several dialects in one engine need constant care. NGINX and Envoy disagree about what many unset options mean, whether a failed request is retried for example. The internal model has no defaults of its own, so each compiler spells out what its dialect expects. When one dialect needs a capability the engine lacks, we add it to the shared model and think through how it interacts with the other three.

Long-lived connections hold on to old state. A WebSocket opened before a reload keeps the configuration it began with until it closes, in Xin as in NGINX. In Xin that state is a snapshot in memory, or a draining set of accept loops that worker_shutdown_timeout can bound. That is far lighter than a process, so frequent reloads cost much less.

Try it on your own configuration

The quickest way to see what this means for you is to point Xin at a configuration you already run. xinginx -t -c /etc/nginx/nginx.conf loads it the way the server would and reports anything it does not support yet, with the file and line. If it passes, HUP gives you the reload behavior above with no other changes.