ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Core Concepts

Providers and injection

ProvidersTraits and qualifiersCollections and optional dependenciesScopes

Modules

ModulesConfigured modulesDynamic and lazy modules

Running the application

Application phasesLifecycle hooksShutdownStandalone executions

Diagnostics and the value API

The wiring reportWithout macros

Protocols

Integrations

Operating

Reference

Core Concepts

Shutdown

What happens between the signal and the exit: before-shutdown hooks, draining, the timeout cap and the report.

A deploy sends SIGTERM while requests are in flight. The questions are what those requests get, how long they have, and which of your hooks run.

This page follows examples/10-shutdown.

Three triggers, one shutdown

Shutdown is one event per application. The first of three triggers starts it:

  • The signal future passed to serve resolves.
  • close(signal) is called on the app or on any AppHandle.
  • A transport's serve ends while the app is running.

The winner's Signal is the one BeforeApplicationShutdown and OnApplicationShutdown hooks receive. A close called during a running shutdown starts nothing: it waits for the same shutdown and returns the same outcome.

The sequence

  1. BeforeApplicationShutdown hooks, in reverse connect order, while the app still serves. Traffic is normal here. A service that deregisters from discovery and waits for the last routed request does it in this step.
  2. Stop accepting. draining() resolves and is_draining() turns true on every execution and every AppHandle. Each transport does its protocol's equivalent: HTTP/2 and gRPC send GOAWAY, HTTP/1 closes idle keep-alive connections, and WebSocket closes idle connections with 1001 and lets busy ones finish their messages first.
  3. Drain. The app waits for live executions to end, up to drain_timeout. Nothing is cancelled in this window. New executions are refused with Closed.
  4. Cancel and abandon the rest. At the timeout, cancellation fires on every execution still alive, and each is abandoned and counted. A request still held answers 503 with the server is shutting down.
  5. OnModuleDestroy hooks, in reverse connect order. From here on a fresh singleton lookup from an abandoned execution answers LookupError::Closed.
  6. Transports close their sockets. The closes start in reverse bind order and run concurrently, each bounded by what is left of shutdown_timeout, or by hook_timeout when no cap is set. This is where TLS close-notify and broker acknowledgements happen, and a drop does none of them.
  7. OnApplicationShutdown hooks, in reverse connect order.

Lazily loaded modules are torn down before the base graph, latest load first.

PhaseNew executionsSingleton lookupsload
Runningallowedallowedallowed
Stopping (step 1)allowedallowedrefused, LoadError::Closed
Draining (steps 2 to 4)refused with Closed; a transport's cleanup executions are allowedallowedrefused
Destroying (steps 5 to 7)refusedLookupError::Closedrefused

is_draining() is false throughout Stopping. A stream told to end during step 1 would end before the discovery hook had deregistered the instance, which is what that hook's position prevents. For early notice, use BeforeApplicationShutdown.

Bounds

pub fn builder() -> AppBuilder {
    App::builder(AppModule).drain_timeout(DRAIN).shutdown_timeout(SHUTDOWN_CAP)
}

DRAIN is 5 seconds and SHUTDOWN_CAP 25 seconds in the example.

  • drain_timeout (10 s unset) is the window in-flight executions get.
  • shutdown_timeout caps the whole sequence from its trigger. It is unset by default.
  • Each hook runs under its own TIMEOUT, or hook_timeout (10 s).

Hooks run one after another. Twenty hooks at ten seconds each take more than three minutes. An orchestrator kills the process at its grace period, 30 seconds by default in Kubernetes, mid-hook and with nothing reported. Set shutdown_timeout a few seconds under the grace period. When the cap expires:

  • hooks that have not run are recorded as Skipped;
  • a hook mid-run is dropped and recorded as TimedOut with limit: ShutdownCap;
  • a drain still open cancels and abandons at once;
  • stop-accepting still runs, since it runs no user code;
  • each transport's close still starts, under what is left of the cap.

A hook that times out or is skipped is recorded and the sequence continues. A hook that is dropped stops at its next await with its state as it was, and anything it spawned keeps running.

All of these waits are timed by the app's Timer. With no timer, close runs a zero-length drain and cancels live executions at once, while hooks run unbounded.

A handler that notices the drain

ExecutionRef::draining() resolves when the app stops accepting. A long-running handler awaits it and ends its own work.

/// Answers when released. A request still here when the drain window ends is abandoned.
#[ulo_http::get("/work")]
async fn work(&self) -> &'static str {
    self.gate.entered.add_permits(1);
    self.gate.release.acquire().await.expect("the gate is never closed").forget();
    "finished"
}

/// A handler that watches for the drain and ends its own work early.
#[ulo_http::get("/watch")]
async fn watch(&self, exec: ExecutionRef) -> &'static str {
    self.gate.entered.add_permits(1);
    exec.draining().await;
    "stopped early"
}

The test releases /work inside the window and /watch ends on its own:

let closing = tokio::spawn(server.handle.close(Signal::new("deploy")));
server.handle.draining().await;

// The app has stopped accepting: a new connection is refused, and the handler watching for the
// drain has ended.
let late = std::net::TcpStream::connect(server.addr).map(drop).map_err(|e| e.kind());
assert_eq!(late, Err(std::io::ErrorKind::ConnectionRefused));

A request still held when the window ends is refused with a 503 and counted:

let report = advancing(&clock, DRAIN, closing).await.unwrap().unwrap();
assert_eq!(report.signal.name(), "deploy");
assert_eq!((report.abandoned, report.terminal_skipped), (1, 0));

let refused = work.await.unwrap();
assert_eq!(refused.status, 503);
assert!(refused.body.contains("the server is shutting down"), "{}", refused.body);

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

The outcome

serve and every close caller receive Result<Shutdown, ShutdownError>.

FieldMeaning
signalThe trigger that won.
abandonedExecutions still alive when the drain ended.
terminal_skippedCleanup executions a transport opened for a connection that were refused or abandoned.

ShutdownError carries the same report and a list of ShutdownFailure:

  • Hook { hook, key, reason }: a destroy or shutdown hook timed out, was skipped, panicked, or failed to read a parameter.
  • Close { transport, reason }: a transport's close failed, panicked or exceeded its bound.
  • Serve { transport, end }: a transport's serve ended while the app ran.
  • Dropped: the App was dropped before its shutdown closed the servers, so no hook ran.

The example's binary prints closed on SIGINT: 1 abandoned when interrupted with a request held.

A transport that dies

If one transport's serve returns, fails or panics before any other trigger, the app does not go on serving the others while reporting healthy. That end is the third trigger. The signal names the transport, for example transport `Doomed` failed: the listener was lost. The healthy servers drain, the phase reaches Closed, and serve returns Err whose first failure is ShutdownFailure::Serve with a ServeEnd of Errored, Panicked or Returned.

The example's src/dying.rs is a hand-written Server whose serve fails on command, with the Transport marker it needs. A held request on the healthy HTTP server still finishes inside the window:

let [ShutdownFailure::Serve { transport, end: ServeEnd::Errored(reason) }] = &*error.failures else {
    panic!("expected the one `Serve` failure: {error}");
};
assert_eq!(*transport, TypeName::of::<Doomed>());
assert_eq!(reason.to_string(), "the listener was lost");

Disconnect handlers are best effort

A transport opens a cleanup execution for a connection that ends during the drain. Such an execution follows the drain's rules: one opened a moment before drain_timeout is cancelled almost at once, and a connection still busy at the timeout has its cleanup refused. The handler also never runs on SIGKILL, an out-of-memory kill or a lost node. State that outlives the process, such as presence in Redis or room membership in a shared store, belongs in TTL or heartbeat storage that cleans itself up.

Wiring signals

The framework installs no signal handler. Pass a future that resolves with a Signal to serve. ulo_runtime_tokio::shutdown_signal() does this for SIGINT and SIGTERM on Unix.

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

Running the example

cargo run -p ex-10-shutdown
curl http://127.0.0.1:3000/work    # held: nothing in the running binary releases it

Interrupt the server while the curl waits. After the 5-second window the curl gets 503 the server is shutting down, and the server prints closed on SIGINT: 1 abandoned.

The tests run the window on a scripted clock (ulo::testing::ScriptedTimer), not tokio's paused one. See Clocks in tests.

Lifecycle hooks

Init, bootstrap, destroy and shutdown hooks, readiness checks with retries, and the order they run in.

Standalone executions

Running a job or a command with no server: execute, per-execution data, deadlines and close.

On this page

Three triggers, one shutdownThe sequenceBoundsA handler that notices the drainThe outcomeA transport that diesDisconnect handlers are best effortWiring signalsRunning the example