Kest

Search

Search the documentation

Fundamentals

Asynchronous providers

Wait for a connection or a download before the application starts.

Some things must be ready before the first request: a database pool, a remote configuration, a search client that connects over the network, a cache warm-up. If you build them in a normal constructor you either block, or hand out half-ready objects. An asynchronous provider is built with a future (or a suspend block); the container waits for it while starting, so every class that depends on it receives the finished value.

Kest.run<AppModule> {
    provideAsync<SearchClient> { r -> SearchClient.connectAsync(r.get(ConfigService::class).getOrThrow<String>("search.url")) }
    provideSuspend<FeatureFlags>(timeout = Duration.ofSeconds(5)) { r -> loadFlags(r.get(HttpClientService::class)) }
}
 
@Injectable class Search(private val client: SearchClient)       // sees a connected client: it never gets an unfinished one
Loading diagram…
FormUse it when
provideAsync<T> { r -> CompletableFuture<T> }a library gives you a future / CompletionStage
provideSuspend<T> { r -> ... }you want to write straight-line suspend code
provideAsync(TOKEN) { ... }the provider lives under a token
Java: o.provideAsync(SearchClient.class, r -> ...)Java

Failure and time limits

  • A failed future stops start-up with the original exception, not a wrapper, so the stack trace points at the real cause (wrong password, host unreachable).
  • A future that does not finish within timeout (60 seconds by default) stops start-up with a message that names the provider. Set a smaller limit for things that should be fast.
  • Fail fast on purpose: an application that starts without its database is worse than one that refuses to start. The orchestrator (Kubernetes) restarts it, and the readiness probe never reports it ready.

Good practice

  • Mark the type @Provided so the build knows it is supplied at start-up: @Provided class SearchClient(...).
  • Do slow, essential work here (connect, load). Do optional work later, in a lifecycle hook or a background job, so start-up stays quick.
  • Provide a small timeout in tests and use a fake: overrideProvider(SearchClient::class, FakeSearch()).

Read more