Home

Awesome

⚡zap⚡ - blazingly fast backends in zig

Discord

Zap is the zig replacement for the REST APIs I used to write in python with Flask and mongodb, etc. It can be considered to be a microframework for web applications.

What I needed as a replacement was a blazingly fast and robust HTTP server that I could use with Zig, and I chose to wrap the superb evented networking C library facil.io. Zap wraps and patches facil.io - the C web application framework.

⚡ZAP⚡ IS FAST, ROBUST, AND STABLE

After having used ZAP in production for a year, I can confidently assert that it proved to be:

Exactly the goals I set out to achieve!

FAQ:

Here's what works

I recommend checking out Endpoint-based examples for more realistic use cases. Most of the examples are super stripped down to only include what's necessary to show a feature.

NOTE: To see API docs, run zig build run-docserver. To specify a custom port and docs dir: zig build docserver && zig-out/bin/docserver --port=8989 --docs=path/to/docs.

I'll continue wrapping more of facil.io's functionality and adding stuff to zap to a point where I can use it as the JSON REST API backend for real research projects, serving thousands of concurrent clients.

⚡blazingly fast⚡

Claiming to be blazingly fast is the new black. At least, Zap doesn't slow you down and if your server performs poorly, it's probably not exactly Zap's fault. Zap relies on the facil.io framework and so it can't really claim any performance fame for itself. In this initial implementation of Zap, I didn't care about optimizations at all.

But, how fast is it? Being blazingly fast is relative. When compared with a simple GO HTTP server, a simple Zig Zap HTTP server performed really good on my machine (x86_64-linux):

Update: Thanks to @felipetrz, I got to test against more realistic Python and Rust examples. Both python sanic and rust axum were easy enough to integrate.

Update: I have automated the benchmarks. See blazingly-fast.md for more information. Also, thanks to @alexpyattaev, the benchmarks are fairer now, pinning server and client to specific CPU cores.

Update: I have consolidated the benchmarks to one good representative per language. See more details in blazingly-fast.md. It contains rust implementations that come pretty close to Zap's performance in the simplistic testing scenario.

So, being somewhere in the ballpark of basic GO performance, zig zap seems to be ... of reasonable performance 😎.

I can rest my case that developing ZAP was a good idea because it's faster than both alternatives: a) staying with Python, and b) creating a GO + Zig hybrid.

See more details in blazingly-fast.md.

💪 Robust

ZAP is very robust. In fact, it is so robust that I was confidently able to only work with in-memory data (RAM) in all my ZAP projects so far: over 5 large online research experiments. No database, no file persistence, until I hit "save" at the end 😊.

So I was able to postpone my cunning data persistence strategy that's similar to a mark-and-sweep garbage collector and would only persist "dirty" data when traffic is low, in favor of getting stuff online more quickly. But even if implemented, such a persistence strategy is risky because when traffic is not low, it means the system is under (heavy) load. Would you confidently NOT save data when load is high and the data changes most frequently -> the potential data loss is maximized?

To answer that question, I just skipped it. I skipped saving any data until receiving a "save" signal via API. And it worked. ZAP just kept on zapping. When traffic calmed down or all experiment participants had finished, I hit "save" and went on analyzing the data.

Handling all errors does pay off after all. No hidden control flow, no hidden errors or exceptions is one of Zig's strengths.

To be honest: There are still pitfalls. E.g. if you request large stack sizes for worker threads, Zig won't like that and panic. So make sure you don't have local variables that require tens of megabytes of stack space.

🛡️ Memory-safe

See the StopEndpoint in the endpoint example. That example uses ZIG's awesome GeneralPurposeAllocator to report memory leaks when ZAP is shut down. The StopEndpoint just stops ZAP when receiving a request on the /stop route.

You can use the same strategy in your debug builds and tests to check if your code leaks memory.

Getting started

Make sure you have zig 0.13.0 installed. Fetch it from here.

$ git clone https://github.com/zigzap/zap.git
$ cd zap
$ zig build run-hello
$ # open http://localhost:3000 in your browser

... and open http://localhost:3000 in your browser.

Using ⚡zap⚡ in your own projects

Make sure you have the latest zig release (0.13.0) installed. Fetch it from here.

If you don't have an existing zig project, create one like this:

$ mkdir zaptest && cd zaptest
$ zig init
$ git init      ## (optional)

Note: Nix/NixOS users are lucky; you can use the existing flake.nix and run nix develop to get a development shell providing zig and all dependencies to build and run the GO, python, and rust examples for the wrk performance tests. For the mere building of zap projects, nix develop .#build will only fetch zig 0.11.0. TODO: upgrade to latest zig.

With an existing Zig project, adding Zap to it is easy:

  1. Add zap to your build.zig.zon
  2. Add zap to your build.zig

In your zig project folder (where build.zig is located), run:

<!-- INSERT_DEP_BEGIN -->
zig fetch --save "git+https://github.com/zigzap/zap#v0.9.1"
<!-- INSERT_DEP_END -->

Then, in your build.zig's build function, add the following before b.installArtifact(exe):

    const zap = b.dependency("zap", .{
        .target = target,
        .optimize = optimize,
        .openssl = false, // set to true to enable TLS support
    });

    exe.root_module.addImport("zap", zap.module("zap"));

From then on, you can use the Zap package in your project. Check out the examples to see how to use Zap.

Updating your project to the latest version of zap

You can change the URL to Zap in your build.zig.zon

Using a tagged release

Go to the release page. Every release will state its version number and also provide instructions for changing build.zig.zon and build.zig.

Using other versions

See here.

Contribute to ⚡zap⚡ - blazingly fast

At the current time, I can only add to zap what I need for my personal and professional projects. While this happens blazingly fast, some if not all nice-to-have additions will have to wait. You are very welcome to help make the world a blazingly fast place by providing patches or pull requests, add documentation or examples, or interesting issues and bug reports - you'll know what to do when you receive your calling 👼.

Check out CONTRIBUTING.md for more details.

See also introducing.md for more on the state and progress of this project.

We now have our own ZAP discord server!!!

You can also reach me on the zig showtime discord server under the handle renerocksai (renerocksai#1894).

Support ⚡zap⚡

Being blazingly fast requires a constant feed of caffeine. I usually manage to provide that to myself for myself. However, to support keeping the juices flowing and putting a smile on my face and that warm and cozy feeling into my heart, you can always buy me a coffee ☕. All donations are welcomed 🙏 blazingly fast! That being said, just saying "hi" also works wonders with the smiles, warmth, and coziness 😊.

Examples

You build and run the examples via:

$ zig build [EXAMPLE]
$ ./zig-out/bin/[EXAMPLE]

... where [EXAMPLE] is one of hello, routes, serve, ... see the list of examples above.

Example: building and running the hello example:

$ zig build hello
$ ./zig-out/bin/hello

To just run an example, like routes, without generating an executable, run:

$ zig build run-[EXAMPLE]

Example: building and running the routes example:

$ zig build run-routes

hello

const std = @import("std");
const zap = @import("zap");

fn on_request(r: zap.Request) void {
    if (r.path) |the_path| {
        std.debug.print("PATH: {s}\n", .{the_path});
    }

    if (r.query) |the_query| {
        std.debug.print("QUERY: {s}\n", .{the_query});
    }
    r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
}

pub fn main() !void {
    var listener = zap.HttpListener.init(.{
        .port = 3000,
        .on_request = on_request,
        .log = true,
    });
    try listener.listen();

    std.debug.print("Listening on 0.0.0.0:3000\n", .{});

    // start worker threads
    zap.start(.{
        .threads = 2,
        .workers = 2,
    });
}