8000 Asynchronous server initialization by pruivo · Pull Request #47234 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ For more information about brokering, see link:{developerguide_link}#_identity_b
Notable changes may include internal behavior changes that prevent common misconfigurations, bugs that are fixed, or changes to simplify running {project_name}.
It also lists significant changes to internal APIs.

=== Endpoints are opened while Keycloak is initializing

By default, {project_name} now opens its HTTP(S) and Management ports while initialization is still in progress.
If you use a proxy or load balancer, configure an HTTP health check with the path `/health/ready` to ensure traffic is only routed to the server once it is fully ready.

If this behavior is not desired or an HTTP health check is not possible, start {project_name} with `--server-async-bootstrap=false` to revert to the previous behavior where ports are opened only after initialization completes.

=== Dev Mode defaults to localhost

When running the server in dev mode on a platform other than Windows Subsystem For Linux, the `http-host` setting will default to localhost.
Expand Down
10 changes: 9 additions & 1 deletion docs/guides/observability/health.adoc
8
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,16 @@ These endpoints respond with HTTP status `200 OK` on success or `503 Service Una
}
----

.Successful response for endpoints with information on the database connection:
.Successful response for endpoints with additional per-check information:
[source, json]
----
{
"status": "UP",
"checks": [
{
"name": "Keycloak Initialized",
"status": "UP"
},
{
"name": "Graceful Shutdown",
"status": "UP"
Expand Down Expand Up @@ -128,6 +132,10 @@ The table below shows the available checks.
|Will start to return "DOWN" once the pre-shutdown phase started.
|No

|Keycloak Initialized
|Returns the status of the server initialization.
|No

|===

For some checks, you'll need to also enable metrics as indicated by the *Requires Metrics* column. To enable metrics
Expand Down
14 changes: 14 additions & 0 deletions docs/guides/server/configuration-production.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ By default, there is no limit set.
Set the option `http-max-queued-requests` to limit the number of queued requests to a given threshold matching your environment.
Any request that exceeds this limit would return with an immediate `503 Server not Available` response.

== Server bootstrap behavior

Server initialization, such as database migrations, may take a significant amount of time to complete.
By default, {project_name} opens its HTTP(S) and Management endpoints while initialization is still in progress in the background.
This allows the startup and liveness probes to report UP early, preventing orchestrators like Kubernetes from killing the container during a long-running migration, while the readiness probe reports DOWN until initialization completes.

Comment on lines +58 to +60
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say there should be some additional rationale explaining why this is a good thing: A potentially long running initialization or migration will then return on the health endpoints "up" for startup and liveness, and "down" for readiness.

If you run {project_name} behind a proxy or load balancer, configure an HTTP health check with the path `/health/ready` to ensure traffic is routed only to instances that have completed initialization.

If an HTTP health check is not possible, or you prefer the server to accept connections only after initialization completes, start {project_name} with the following option:

<@kc.start parameters="--server-async-bootstrap=false"/>

With this setting, {project_name} opens its endpoints only after the bootstrap is complete and the server is ready to handle requests.

== Production grade database
The database used by {project_name} is crucial for the overall performance, availability, reliability and integrity of {project_name}. For details on how to configure a supported database, see <@links.server id="db"/>.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public enum OptionCategory {
EXPORT("Export", 130, ConfigSupportLevel.SUPPORTED),
IMPORT("Import", 140, ConfigSupportLevel.SUPPORTED),
OPENAPI("OpenAPI configuration", 150, ConfigSupportLevel.SUPPORTED),
SERVER("Server configuration", 160, ConfigSupportLevel.SUPPORTED),
BOOTSTRAP_ADMIN("Bootstrap Admin", 998, ConfigSupportLevel.SUPPORTED),
GENERAL("General", 999, ConfigSupportLevel.SUPPORTED);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.config;

public final class ServerOptions {

private ServerOptions() {}

public static final Option<Boolean> SERVER_ASYNC_BOOTSTRAP = new OptionBuilder<>("server-async-bootstrap", Boolean.class)
.category(OptionCategory.SERVER)
.defaultValue(Boolean.TRUE)
.description("If true, endpoints are opened while the bootstrap runs in the background. If false, endpoints are opened after bootstrap completes, ensuring the server is ready to handle requests.")
.build();
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
import org.keycloak.quarkus.runtime.integration.resteasy.KeycloakHandlerChainCustomizer;
import org.keycloak.quarkus.runtime.integration.resteasy.KeycloakTracingCustomizer;
import org.keycloak.quarkus.runtime.logging.ClearMappedDiagnosticContextFilter;
import org.keycloak.quarkus.runtime.services.health.BoostrapReadyHealthCheck;
import org.keycloak.quarkus.runtime.services.health.KeycloakClusterReadyHealthCheck;
import org.keycloak.quarkus.runtime.services.health.KeycloakReadyHealthCheck;
import org.keycloak.quarkus.runtime.storage.database.jpa.NamedJpaConnectionProviderFactory;
Expand Down Expand Up @@ -838,6 +839,7 @@ void disableHealthCheckBean(BuildProducer<BuildTimeConditionBuildItem> removeBea
if (isHealthDisabled()) {
disableReadyHealthCheck(removeBeans, index);
disableClusterHealthCheck(removeBeans, index);
disableBootstrapReadyHealthCheck(removeBeans, index);
return;
}
if (isMetricsDisabled()) {
Expand All @@ -860,6 +862,11 @@ private static void disableReadyHealthCheck(BuildProducer<BuildTimeConditionBuil
removeBeans.produce(new BuildTimeConditionBuildItem(disabledBean.asClass(), false));
}

private static void disableBootstrapReadyHealthCheck(BuildProducer<BuildTimeConditionBuildItem> removeBeans, CombinedIndexBuildItem index) {
ClassInfo disabledBean = index.getIndex().getClassByName(DotName.createSimple(BoostrapReadyHealthCheck.class.getName()));
removeBeans.produce(new BuildTimeConditionBuildItem(disabledBean.asClass(), false));
}

@BuildStep
void disableMdcContextFilter(BuildProducer<BuildTimeConditionBuildItem> removeBeans, CombinedIndexBuildItem index) {
if (!Configuration.isTrue(LoggingOptions.LOG_MDC_ENABLED)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ public Map<String, String> getConfigOverrides() {
"kc.health-enabled","true",
"kc.metrics-enabled", "true",
"kc.cache", "local",
"kc.server-async-bootstrap", "false",
"quarkus.micrometer.export.prometheus.path", "/prom/metrics",
"quarkus.class-loading.removed-artifacts", "io.quarkus:quarkus-jdbc-oracle,io.quarkus:quarkus-jdbc-oracle-deployment"); // config works a bit odd in unit tests, so this is to ensure we exclude Oracle to avoid ClassNotFound ex
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ public final class PropertyMappers {
new FeaturePropertyMappers(), new ImportPropertyMappers(), new ManagementPropertyMappers(),
new MetricsPropertyMappers(), new OpenApiPropertyMappers(), new LoggingPropertyMappers(), new ProxyPropertyMappers(),
new VaultPropertyMappers(), new TracingPropertyMappers(), new TransactionPropertyMappers(),
new SecurityPropertyMappers(), new TruststorePropertyMappers(), new TelemetryPropertyMappers());
new SecurityPropertyMappers(), new TruststorePropertyMappers(), new TelemetryPropertyMappers(),
new ServerPropertyMappers());
}

public static List<PropertyMapperGrouping> getPropertyMapperGroupings() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.quarkus.runtime.configuration.mappers;

import java.util.List;

import org.keycloak.config.ServerOptions;

import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper.fromOption;

public final class ServerPropertyMappers implements PropertyMapperGrouping {
@Override
public List<? extends PropertyMapper<?>> getPropertyMappers() {
return List.of(
fromOption(ServerOptions.SERVER_ASYNC_BOOTSTRAP)
.paramLabel("enabled")
.build()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
import jakarta.ws.rs.ApplicationPath;

import org.keycloak.config.BootstrapAdminOptions;
import org.keycloak.config.ServerOptions;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.configuration.Configuration;
import org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider;
Expand All @@ -41,9 +41,12 @@
import io.smallrye.common.annotation.Blocking;
import org.jboss.logging.Logger;

import static org.keycloak.common.util.Environment.isDevMode;
import static org.keycloak.common.util.Environment.isNonServerMode;

@ApplicationPath("/")
@Blocking
public class QuarkusKeycloakApplication extends KeycloakApplication {
public class QuarkusKeycloakApplication extends KeycloakApplication<QuarkusKeycloakSessionFactory> {

private static final String KEYCLOAK_ADMIN_ENV_VAR = "KEYCLOAK_ADMIN";
private static final String KEYCLOAK_ADMIN_PASSWORD_ENV_VAR = "KEYCLOAK_ADMIN_PASSWORD";
Expand Down Expand Up @@ -72,10 +75,13 @@ void onShutdownEvent(@Observes ShutdownEvent event) {
}

@Override
public KeycloakSessionFactory createSessionFactory() {
QuarkusKeycloakSessionFactory instance = QuarkusKeycloakSessionFactory.getInstance();
instance.init();
return instance;
public QuarkusKeycloakSessionFactory createSessionFactory() {
return QuarkusKeycloakSessionFactory.getInstance();
}

@Override
protected void initKeycloakSessionFactory(QuarkusKeycloakSessionFactory quarkusKeycloakSessionFactory) {
quarkusKeycloakSessionFactory.init();
}

@Override
Expand Down Expand Up @@ -105,7 +111,16 @@ protected void createTemporaryAdmin(KeycloakSession session) {
}

@Override
protected int getTransactionTimeout(KeycloakSessionFactory sessionFactory) {
protected boolean supportsAsyncInitialization() {
var asyncBootstrap = Configuration.getOptionalKcValue(ServerOptions.SERVER_ASYNC_BOOTSTRAP)
.map(Boolean::parseBoolean)
.orElse(Boolean.TRUE);
// skip async bootstrap in dev and non-server mode
return !isDevMode() && !isNonServerMode() && asyncBootstrap;
}

@Override
protected int getTransactionTimeout(QuarkusKeycloakSessionFactory sessionFactory) {
return ((QuarkusJpaConnectionProviderFactory) sessionFactory.getProviderFactory(JpaConnectionProvider.class)).getMigrationTransactionTimeout();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.keycloak.quarkus.runtime.services;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import org.keycloak.services.resources.KeycloakApplication;

import org.jboss.resteasy.reactive.server.ServerRequestFilter;

/**
* Pre-matching request filter that returns a 503 Service Unavailable response while the server bootstrap is in progress.
*/
@ApplicationScoped
public class BootstrapFilter {

private final long startup;
private boolean ready;

public BootstrapFilter() {
startup = System.currentTimeMillis();
}

@ServerRequestFilter(priority = 1, preMatching = true)
public Response filter(ContainerRequestContext ignored) {
if (ready) {
// JVM branch prediction may optimize this code and saves on reading a static volatile field
return null;
}
if (KeycloakApplication.isBootstrapCompleted()) {
// Return null to continue the request chain normally
ready = true;
return null;
}
// Implement a back-off to wait as long as the current start-up took, but then retry at least once per minute
long retry = Math.min(Math.max((System.currentTimeMillis() - startup) / 1000, 1), 60);
// Return 503 Service Unavailable
return Response
.status(Response.Status.SERVICE_UNAVAILABLE)
.type(MediaType.TEXT_PLAIN)
.entity("Boostrap in progress. Retry in " + retry + " seconds.")
.header(HttpHeaders.RETRY_AFTER, retry)
.header("Refresh", retry)
.build();

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.quarkus.runtime.services.health;

import jakarta.enterprise.context.ApplicationScoped;

import org.keycloak.services.resources.KeycloakApplication;

import io.smallrye.health.api.AsyncHealthCheck;
import io.smallrye.mutiny.Uni;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.HealthCheckResponseBuilder;
import org.eclipse.microprofile.health.Readiness;

/**
* Readiness health check that reports DOWN while the server bootstrap is in progress and UP once initialization completes.
*/
@Readiness
@ApplicationScoped
public class BoostrapReadyHealthCheck implements AsyncHealthCheck {

private static final HealthCheckResponse UP = builder().up().build();
private boolean bootstrapCompleted;

@Override
public Uni<HealthCheckResponse> call() {
// JVM branch prediction may optimize this code and saves on reading a static volatile field
if (bootstrapCompleted) {
return ready();
}
if (KeycloakApplication.isBootstrapCompleted()) {
bootstrapCompleted = true;
return ready();
}
return Uni.createFrom().item(builder().down().build());
}

private Uni<HealthCheckResponse> ready() {
return Uni.createFrom().item(UP);
}

private static HealthCheckResponseBuilder builder() {
return HealthCheckResponse.named("Keycloak Initialized");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReference;

import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
import org.keycloak.connections.infinispan.InfinispanConnectionProviderFactory;
import org.keycloak.infinispan.util.InfinispanUtils;
import org.keycloak.quarkus.runtime.integration.QuarkusKeycloakSessionFactory;

import io.smallrye.health.api.AsyncHealthCheck;
import io.smallrye.mutiny.Uni;
Expand All @@ -34,15 +31,15 @@
public class KeycloakClusterReadyHealthCheck implements AsyncHealthCheck {

private final AtomicReference<Instant> failingSince = new AtomicReference<>();
private final InfinispanConnectionProviderFactory factory;

public KeycloakClusterReadyHealthCheck(InfinispanConnectionProviderFactory factory) {
this.factory = factory;
}

@Override
public Uni<HealthCheckResponse> call() {
var builder = HealthCheckResponse.named("Keycloak cluster health check").up();
if (InfinispanUtils.isRemoteInfinispan()) {
return Uni.createFrom().item(builder.build());
}
var sessionFactory = QuarkusKeycloakSessionFactory.getInstance();
InfinispanConnectionProviderFactory factory = (InfinispanConnectionProviderFactory) sessionFactory.getProviderFactory(InfinispanConnectionProvider.class);
if (factory.isClusterHealthy()) {
failingSince.set(null);
} else {
Expand Down
Loading
Loading
0