Recipes
Async local storage
Values that follow a request without being passed around.
In Node the AsyncLocalStorage class carries a request id or the current tenant through every function the request touches. Kest has RequestContext for the same job:
app.http(adapter) {
useRequestContext { request -> mapOf("requestId" to (request.header("x-request-id") ?: UUID.randomUUID().toString())) }
}
@Injectable class Audit {
fun log(msg: String) = println("[${RequestContext["requestId"]}] $msg") // deep in a service, no parameter needed
}RequestContext["key"]reads,RequestContext["key"] = valuewrites (inside a request).- Values live as long as the request and are visible to threads it starts (it uses an inheritable thread-local), including the virtual threads Kest handlers run on.
- Requests never see each other's values.
- Outside a request (a scheduled job, a command) the context is empty: open one with
RequestContext.run(mapOf("job" to "nightly")) { ... }. RequestContext.snapshot()copies everything, for passing to a thread pool that does not inherit.
For per-request objects (not just values) use request-scoped providers instead: they are built once per request and injected like any other provider.