ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

Operating

DeploymentProductionDockerSocket activation

Reference

Deployment

Production

Release builds, configuration, graceful shutdown, health probes, systemd and a reverse proxy.

Release build

cargo build --release

The binary is target/release/<package-name>. The application's main chooses the runtime and the servers, so the binary needs no separate server process.

Configuration

A project made by ulo new reads config/app.toml from the working directory and layers environment variables named APP_<SECTION>__<KEY> over it. In a deployment the file holds defaults and the environment holds what differs:

APP_SERVER__ADDRESS=0.0.0.0:8080 ./my-app

The config/ directory has to be present in the working directory at run time. A source that cannot be read is reported by wire() with every other problem, and the process exits before any socket opens. See Configuration and Project Structure.

The examples read a single PORT variable instead and bind 127.0.0.1.

Listening on all interfaces

A server binds the endpoint it is given. Inside a container or behind a proxy, bind 0.0.0.0:

use ulo_http_hyper::Server;

.bind(Server::new("0.0.0.0:8080"))

listen() prepares every server first, then acquires the sockets. Every server's configuration problem (a bad address, a TLS key that does not match its certificate) is reported together as one StartupError, before any port conflict can be. If any server fails to bind, the ones already bound are closed and the application does not serve.

Graceful shutdown

serve(signal) runs until the signal future resolves or close is called. ulo_runtime_tokio::shutdown_signal() resolves on the first SIGINT or SIGTERM (Ctrl-C and Ctrl-Close on Windows) and yields a Signal named after it. docker stop, systemd and Kubernetes all send SIGTERM first, so the signal future is the whole wiring.

examples/10-shutdown shows the knobs and the report:

examples/10-shutdown/src/lib.rs
pub fn builder() -> AppBuilder {
    App::builder(AppModule).drain_timeout(DRAIN).shutdown_timeout(SHUTDOWN_CAP)
}
examples/10-shutdown/src/main.rs
use ulo_runtime_tokio::shutdown_signal;

let shutdown = app.serve(shutdown_signal()).await?;
println!("closed on {}: {} abandoned", shutdown.signal, shutdown.abandoned);

The example sets DRAIN to 5 seconds and SHUTDOWN_CAP to 25 seconds.

The sequence runs once per application, started by whichever trigger arrives first: the signal future, close(signal) on the application or on an AppHandle, or a server's serve ending while the application runs.

  1. BeforeApplicationShutdown hooks run in reverse connect order, while the application still serves normally. A service that deregisters from discovery does it here.
  2. Servers stop accepting. HTTP/2 and gRPC send GOAWAY, HTTP/1 closes idle keep-alive connections, and WebSocket closes idle connections with code 1001.
  3. The application waits for live executions to end on their own, up to drain_timeout (10 seconds when unset). Nothing is cancelled in this window, and new executions are refused.
  4. At the timeout, cancellation fires on every execution still alive and each is counted as abandoned. A request still held is answered 503 with the server is shutting down.
  5. OnModuleDestroy hooks run.
  6. Servers close their sockets, concurrently, each bounded by what is left of shutdown_timeout.
  7. OnApplicationShutdown hooks run.

A handler can end its own work early by awaiting ExecutionRef::draining() (the /watch route of example 10).

Sizing the timeouts

drain_timeout bounds step 3. shutdown_timeout caps the whole sequence, counted from the trigger, and is unset by default. Hooks run one after another, so twenty hooks at the default 10-second hook_timeout can outlast an orchestrator's grace period. The process is then killed mid-hook and nothing is reported. Set shutdown_timeout a few seconds under the grace period: Kubernetes defaults to 30 seconds, so the example uses 25. When the cap expires, hooks not yet run are skipped, a drain still open cancels and abandons at once, and each server's close still starts with what time is left.

The exit status

serve returns Result<Shutdown, ShutdownError>. Shutdown carries the trigger's signal, the count of abandoned executions and terminal_skipped. Abandoned executions alone do not make the result an Err. A failure in the sequence does: a hook that timed out or panicked, a server whose close failed, or a server whose serve ended while the application was running. Because main in the examples returns Result and ends with app.serve(..).await?, such a shutdown exits non-zero.

A server that dies at runtime starts the same sequence a signal would. The healthy servers drain, and serve returns Err naming the dead transport. examples/10-shutdown exercises this with a hand-written server (src/dying.rs).

A Restart=on-failure policy therefore restarts an application whose transport died. A panic inside a server's serve is the exception: it is caught and starts the shutdown, as an Err does.

Detached tasks

The drain tracks executions, not tasks. A background loop holding an AppHandle reads handle.draining() to stop pulling work, and runs each unit of work through execute so the drain waits for it.

Disconnect handlers at shutdown are best effort: a connection still busy at the timeout has its cleanup refused, and none run on SIGKILL or an out-of-memory kill. State that outlives the process belongs in storage with a time to live.

Health probes

HealthModule collects every health check that any module contributes, and HealthHttp serves /health/live, /health/ready and /health/started as application/health+json, with 200 for a pass and 503 for a failure. ulo new imports both for an HTTP project.

use ulo_health::HealthModule;
use ulo_health_http::HealthHttp;

m.import(HealthModule::new());
m.import(HealthHttp::new());

When a shutdown begins, HealthModule's before-shutdown hook turns readiness false, then waits its lag before servers stop accepting, so a load balancer can stop routing first. The lag defaults to zero. Leave it at zero when the pod has a preStop sleep, and set it to a few seconds when it has none. examples/34-health shows the module, lag and the checks. See Health checks.

Load limits

Each server bounds the calls it holds in flight. max_inflight defaults to 1,024 on the HTTP, gRPC and RPC servers, and Count::Unlimited removes the bound. A call over the limit is refused with a hint for when to retry, taken from the server's shed_retry_after (one second when unset): HTTP answers 503 with Retry-After before routing, gRPC answers UNAVAILABLE with grpc-retry-pushback-ms, and an RPC request is answered unavailable with a RetryAfter detail. An RPC event over the bound has no reply to carry one and is left unacknowledged for the broker to redeliver. A link with native backpressure (AMQP, Kafka) stops taking messages instead. max_body, header_timeout and handshake_timeout are further HTTP Server options; see HTTP Servers.

systemd

A service unit for a binary that handles SIGTERM through shutdown_signal():

[Unit]
Description=My Ulo API
After=network.target

[Service]
Type=simple
User=api
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/my-app
Environment=APP_SERVER__ADDRESS=0.0.0.0:8080
Restart=on-failure
RestartSec=5s
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target

systemctl stop sends SIGTERM and waits TimeoutStopSec before SIGKILL, so shutdown_timeout belongs a few seconds under it. The default tracing subscriber of a ulo new project writes to stderr, which journald collects; RUST_LOG in the environment sets the filter.

To keep the port open across restarts, let systemd own the socket. See Socket activation.

Reverse proxy

Run the application on a local port and proxy from nginx:

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /ws {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

TLS can end at the proxy, or at the application with Server::tls (see HTTP Servers and examples/20-http-tls).

Deployment

Release builds, graceful shutdown, containers, and socket activation.

Docker

A multi-stage image for an Ulo binary, the signals a container delivers, and compose for local dependencies.

On this page

Release buildConfigurationListening on all interfacesGraceful shutdownSizing the timeoutsThe exit statusDetached tasksHealth probesLoad limitssystemdReverse proxy