Solutions / Case studies
Case studies
Four problems, four builds, and the code that solved them — the same domains the use-cases page covers, taken all the way to a working program.
A typed JSON API over Postgres
Route table, middleware chain, and one query API — the whole service in a single file that compiles to one binary.
The problem
A small team needed a read API over Postgres with a handful of endpoints, request logging, and a rate limit — without adopting a web framework and the dependency tree that comes with it.
The approach
- Declare the routes as a table of rows, so each endpoint is data you can read, diff, and reorder.
- Wrap the server in middleware: secure headers, CORS for a single origin, then a per-IP token bucket.
- Query through `std.sqlz`, which speaks SQLite, Postgres, and MySQL with the same calls.
- Serialize with `std.json`; a value that cannot be encoded becomes a 500, not a crash.
`zz build` turns the service into a single static binary — the deploy copies one file, not a runtime and a lockfile.
import std.http
import std.json
import std.sqlz
struct RouteDef {
method: str,
path: str,
handle: func(http.request) -> http.response,
}
func route(
method: str,
path: str,
handle: func(http.request) -> http.response,
) -> RouteDef {
RouteDef{method: method, path: path, handle: handle}
}
func main() {
db := sqlz.open("app.db")
defs := [
route("GET", "/users", |r: http.request| users(db, r)),
route("GET", "/users/:id", |r: http.request| user(db, r)),
route("GET", "*", |r: http.request| http.not_found()),
]
s := http.server()
s = http.cors(s, ["https://app.example.com"])
s = http.secure_headers(s)
for d in defs {
s = http.route(s, d.method, d.path, d.handle)
}
s = http.rate_limit(s, 300, 60000)
http.listen_cfg(s, 8080, {"max_body_bytes": 1000000})
}
func users(db: sqlz.db, req: http.request) -> http.response {
rows := sqlz.query(db, "SELECT id, name FROM users LIMIT 50")
http.ok(json.stringify(rows) ?? "[]")
}
func user(db: sqlz.db, req: http.request) -> http.response {
match http.param(req, "id") {
.ok(id) => {
q := "SELECT id, name FROM users WHERE id = {id}"
rows := sqlz.query(db, q)
http.ok(json.stringify(rows) ?? "[]")
}
.err(_) => http.not_found(),
}
}Runs in the playground — no install required. Open it
A TCP proxy that stays responsive
Accept on one task, handle on many: slow clients park their own green thread instead of blocking the listener.
The problem
A legacy TCP service had to sit behind a proxy, but a single-threaded relay stalled whenever one client stopped reading — every other connection waited behind it.
The approach
- Accept connections on a dedicated task and hand each one off over a channel.
- Handle every connection on its own green thread, so a slow read parks one task rather than the listener.
- Write the reply on the same connection handle — no copying into a shared buffer, no lock to get wrong.
- Close cleanly on error so a dropped client frees its slot instead of leaking a task.
Green threads and channels are part of the language, so the concurrency model costs no dependency and no callback glue.
import std.chan
import std.net
import std.task
func main() {
upstream := net.tcp_connect("10.0.0.7:7000", 5000)
listener := net.tcp_listen("0.0.0.0:9000")
incoming := chan()
task.spawn(|_| {
for {
match net.accept(listener) {
.ok(stream) => chan.send(incoming, stream),
.err(e) => {
println("accept failed: {e}")
break
},
}
}
})
for {
stream := chan.recv(incoming)
task.spawn(|_| {
match net.read(stream, 4096) {
.ok(data) => {
match net.write(upstream, data) {
.ok(_) => net.write(stream, data),
.err(_) => net.close(stream),
}
}
.err(_) => net.close(stream),
}
})
}
}Runs in the playground — no install required. Open it
One binary for every release
A backup tool that ships as one file: parsed flags, colourised output, and a help text generated from the same declarations.
The problem
An internal backup script had grown into something people depended on, but it needed Python on every machine and its flag handling had quietly diverged from its documentation.
The approach
- Declare flags once — name, type, and default — and read them from the parser after a single `parse` call.
- Let the tool generate its own `--help` text from those declarations, so the docs cannot go stale.
- Colourise failures with `std.colors`, which appends a reset so styles never bleed into a pipeline.
- Compile ahead of time so the tool is one file the user downloads and runs, with no runtime to install.
Ahead-of-time compilation means the deliverable is a binary — no runtime, no interpreter, and no cold start.
import std.args
import std.colors
import std.env
import std.fs
func main() {
p := ArgsParser.new()
p.str_flag("out", "out.txt")
p.int_flag("jobs", 4)
p.bool_flag("verbose")
if !p.parse(env.args()) {
println(p.error() |> colors.red())
return
}
out := p.get_str("out")
jobs := p.get_int("jobs")
verbose := p.get_bool("verbose")
if verbose {
println("writing {out} with {jobs} jobs")
}
match fs.write(out, "backup payload\n") {
.ok(_) => println("wrote {out}"),
.err(e) => {
println("write failed: {e}" |> colors.red())
}
}
}Runs in the playground — no install required. Open it
A deploy that refuses to ship a broken service
A release step that runs the migration, reads the exit status, and emits a structured log line a collector can ship.
The problem
Deploys were reported as successful by the pipeline while the migration underneath had failed — the two steps never shared an exit code, so a broken release looked green.
The approach
- Run the migration with `std.process` and read the status from the result instead of trusting the shell.
- Emit the outcome as a structured JSON log line, so the collector can route it without parsing prose.
- Exit non-zero on failure so the pipeline halts on the real status of the step.
- Cover the same check with `zz test`, which exercises the handler without opening a socket.
The deploy step is a compiled program with precise exit codes — the same guarantees you would ask of the service itself.
import std.log
import std.process
func main() {
log.set_format("json")
log.set_level("info")
log.to_stderr()
match process.run("./migrate.sh", []) {
.ok(out) => {
if out[0] != 0 {
log.error("migrate failed with status {out[0]}")
process.exit(1)
}
log.info("migrate ok")
}
.err(e) => {
log.error("could not run migrate: {e}")
process.exit(1)
}
}
}Runs in the playground — no install required. Open it
Want the capabilities behind these?Read the use casesRead the docs