Kern
On this page

Kern Reference Backend Service

A production-grade internal HTTP/1.1 JSON + PostgreSQL service written in pure Kern (zero C FFI, static ELF64 Linux binaries with no libc). Use this project as a template for new Kern backend services.

Project Layout

examples/service/
├── kern.rules                     # Strict layered quality rules (api > store > config)
├── README.md
├── deploy/
│   ├── Dockerfile                 # Multi-stage static Linux build -> FROM scratch
│   ├── kern-service.service       # Hardened systemd unit with SIGTERM graceful drain
│   ├── kern-service.env.example   # Environment variable template
│   └── cloudflared.yml            # Cloudflare Tunnel edge TLS termination config
└── src/
    ├── main.kn                    # Startup, schema init, HTTP loop, graceful shutdown
    ├── config/
    │   └── config.kn              # Typed env configuration & startup validation
    ├── store/
    │   ├── model.kn               # Domain Item types & ItemStore generic interface
    │   ├── list.kn                # Flat arena-backed ItemList container
    │   ├── pg.kn                  # PostgreSQL repository over std.postgres.Pool
    │   ├── pg_decode.kn           # Row decoding & SQLSTATE -> StoreError mapping
    │   └── memory.kn              # In-memory ItemStore for tests & STORAGE=memory
    └── api/
        ├── codec.kn               # Strict JSON request parsing (depth/size limits)
        ├── response.kn            # JSON response encoding & HTTP status mapping
        ├── router.kn              # Route table, handlers & structured JSON logs
        └── server.kn              # Event-loop runner, SIGTERM/SIGINT drain & E2E tests

HTTP API

All responses use application/json; charset=utf-8 (except 204 No Content). Every request emits a structured JSON log record to stderr containing level, time (RFC 3339), msg, method, path, status, and latency_ms.

Method & PathSuccessError Responses
GET /healthz200 {"status":"ok"}—
GET /readyz200 {"status":"ready"}503 {"status":"unavailable"} when Postgres ping fails
GET /v1/items200 {"items":[...]}503 / 500
GET /v1/items/:id200 {"id":1,"slug":"...","title":"...","body":"...","created_at":"..."}400 invalid id, 404 {"error":"not_found",...}
POST /v1/items201 {...}400 malformed/oversized JSON or invalid fields, 409 {"error":"conflict",...} on duplicate slug (23505)
DELETE /v1/items/:id204 No Content400 invalid id, 404 {"error":"not_found",...}

Unsupported methods on known routes return 405 Method Not Allowed with an Allow header.

Configuration

VariableDefaultValidation / Notes
HOST127.0.0.1Valid IPv4 or IPv6 bind address
PORT80801..65535
STORAGEpostgrespostgres or memory
PGHOST127.0.0.1IP address (TCP) or Unix socket path starting with /
PGPORT54321..65535
PGUSERpostgresNon-empty
PGPASSWORD(empty)Supports SCRAM-SHA-256 or trust auth; cleartext only over a Unix socket
PGDATABASEkern_serviceNon-empty
PGPOOL_SIZE81..128
REQUEST_TIMEOUT_MS15000100..300000 (applies to HTTP read/write)
QUERY_TIMEOUT_MS500100..300000 (limit of each PostgreSQL connect, read and write; see Hung database)
SHUTDOWN_GRACE_MS10000100..120000 (graceful drain window on SIGTERM/SIGINT)
WORKERS11..64. Above 1, the parent starts that many copies of itself (see Several processes)
LOG_LEVELinfodebug, info, warn, or error

Hung database

The service has one event loop. A PostgreSQL call blocks it, so a hung database would also stall /healthz and /readyz. Three rules limit this:

  • Each PostgreSQL connect, read and write waits at most QUERY_TIMEOUT_MS (not REQUEST_TIMEOUT_MS). The timed-out connection is closed. The pool does not keep it.
  • After a timeout the circuit opens for 1 s. Each request that needs the database then gets 503 at once. After 1 s one request tries the database again. A new timeout opens the circuit again. The query on the PostgreSQL server is not cancelled.
  • GET /healthz never uses the database. GET /readyz waits at most 500 ms (or QUERY_TIMEOUT_MS, if smaller) and answers 503 while the circuit is open.

Maximum stall of /healthz: about QUERY_TIMEOUT_MS. Only one trial request waits at a time. A soak test with a stopped PostgreSQL and QUERY_TIMEOUT_MS of 1000 measured 1001 ms. Suggested liveness probe timeout: at least 2 * QUERY_TIMEOUT_MS + 500 ms (1.5 s with the default), with failureThreshold of 3 or more.

Several processes (WORKERS)

WORKERS=N with N above 1 starts a parent that runs N copies of the executable. Each copy binds the same HOST:PORT with SO_REUSEPORT (net.bind_shared, http.server_listen_fd) and has its own PostgreSQL pool, so PGPOOL_SIZE applies to each copy. STORAGE=memory is refused, because each copy would keep its own store.

  • SIGTERM or SIGINT to the parent sends SIGTERM to every copy. Each copy drains for up to SHUTDOWN_GRACE_MS. The parent kills a copy that stays after the grace plus 2 s.
  • A copy that exits is started again after a delay of 100 ms. The delay doubles on each quick failure up to 5 s, and resets after a copy ran for 10 s.
  • kill -9 of the parent leaves the copies running. Use the process manager to stop the group.
  • The parent starts each copy with /bin/sh, which sets WORKERS=1 and KERN_SERVICE_SHARED_PORT=1.
  • Balance: on Linux SO_REUSEPORT spread connections evenly in a test. On macOS one process got all connections, so use WORKERS above 1 on Linux only.

Local Development (macOS / Linux)

Check, format, and run all unit and loopback HTTP tests:

build/kern check examples/service
build/kern fmt --check examples/service
build/kern test examples/service

Run locally with PostgreSQL:

createdb kern_service
PGHOST=127.0.0.1 PGPORT=5432 PGUSER="$USER" PGDATABASE=kern_service \
  build/kern run examples/service

Quick zero-DB local smoke run (in-memory backend):

STORAGE=memory PORT=8080 build/kern run examples/service

Exercise the endpoints with curl:

# Health & readiness
curl -s http://127.0.0.1:8080/healthz
curl -s http://127.0.0.1:8080/readyz

# Create an item
curl -i -X POST http://127.0.0.1:8080/v1/items \
  -H 'Content-Type: application/json' \
  -d '{"slug":"first-note","title":"Hello Kern","body":"Served from static binary"}'

# List items and fetch by ID
curl -s http://127.0.0.1:8080/v1/items
curl -s http://127.0.0.1:8080/v1/items/1

# Delete by ID
curl -i -X DELETE http://127.0.0.1:8080/v1/items/1

Cross-Building Static Linux Binaries

Kern directly emits static, zero-libc ELF64 executables for Linux x86-64 and arm64 with no external cross-compiler or linker:

# macOS host binary
build/kern build examples/service

# Linux x86-64 static ELF64
build/kern build examples/service --target linux-x64

# Linux arm64 static ELF64
build/kern build examples/service --target linux-arm64

The built executables are written to examples/service/build/service (host), examples/service/build/service-linux-x64, and examples/service/build/service-linux-arm64.

Linux Deployment

  1. Cross-build and copy the static binary to the Linux server:
    build/kern build examples/service --target linux-x64
    scp examples/service/build/service-linux-x64 server:/usr/local/bin/kern-service
    
  2. Install environment and systemd unit files:
    sudo mkdir -p /etc/kern-service
    sudo cp examples/service/deploy/kern-service.env.example /etc/kern-service/service.env
    sudo chmod 0640 /etc/kern-service/service.env
    sudo cp examples/service/deploy/kern-service.service /etc/systemd/system/
    sudo systemctl daemon-reload
    sudo systemctl enable --now kern-service
    sudo journalctl -u kern-service -f
    
  3. Terminate inbound TLS at the edge with Cloudflare Tunnel using deploy/cloudflared.yml (or Caddy/nginx forwarding to http://127.0.0.1:8080).

Option 2: Zero-libc scratch Container

Build a minimal container from the repository root (contains only the static /service binary):

docker build -f examples/service/deploy/Dockerfile -t kern-service:latest .
docker run --rm -p 8080:8080 \
  -e HOST=0.0.0.0 -e PGHOST=10.0.0.5 -e PGUSER=kern_app -e PGPASSWORD=secret \
  kern-service:latest

Using as a Project Template

To bootstrap a new Kern backend service:

  1. Copy examples/service/ to your new project directory.
  2. Keep the layered kern.rules (layers = api > store > config) so every change stays checked, formatted, and tested.
  3. Replace Item / items in src/store/ and src/api/ with your domain model and routes.

Source: examples/service/README.md in the repository.