From 9c244813c918f082417f2afce5bb086778d35dac Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Tue, 13 Oct 2026 11:10:46 +0200 Subject: [PATCH 1/2] Detect problematic pgbouncer setup on startup Closes #53903 Signed-off-by: Alexander Schwartz Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/guides/server/db.adoc | 66 ++++++++++++++----- .../QuarkusJpaConnectionProviderFactory.java | 64 ++++++++++++++++++ 2 files changed, 114 insertions(+), 16 deletions(-) diff --git a/docs/guides/server/db.adoc b/docs/guides/server/db.adoc index b0e7d047012..36e11890fc7 100644 --- a/docs/guides/server/db.adoc +++ b/docs/guides/server/db.adoc @@ -317,22 +317,6 @@ You can override this behavior by setting your own value for `targetServerType` The `targetServerType` is only applied automatically to the primary datasource, as requirements might be different for additional datasources. ==== -==== Using PgBouncer - -When {project_name} connects to PostgreSQL through PgBouncer, connections can fail after a failover or switchover. -PgBouncer caches the `in_hot_standby` value it reports to new client connections, and it can keep reporting `in_hot_standby=on` after the switch. -Because `targetServerType` is set to `primary`, the PostgreSQL JDBC driver then treats the connection as a reader instance and refuses it with the error `Could not find a server with specified targetServerType: primary`. - -This is a known PgBouncer issue, tracked in https://github.com/pgbouncer/pgbouncer/issues/859[pgbouncer/pgbouncer#859]. -Reloading PgBouncer after a failover or switchover makes it report the current value again. - -Setting `targetServerType` to `any` avoids the error, but it also removes the protection described above, so {project_name} might connect to a reader instance. -Only use it if your routing in PgBouncer sends database connections exclusively to the writable primary database. - -Set `targetServerType=any` via `db-url-properties`: - -<@kc.start parameters="--db postgres --db-url-properties='?targetServerType=any'"/> - === Permissions of the database user Ensure that the database user has `SELECT` permissions to the following tables to ensure an efficient upgrade: `pg_class`, `pg_namespace`. @@ -358,6 +342,56 @@ Secure the connection by adding the options: * `db-tls-mode=verify-server`: Forces TLS and verifies the server's identity against the trusted certificate. * `db-tls-trust-store-file=/path/to/certificate`: The path to the server's public certificate file on the client machine. +=== Using PgBouncer + +[WARNING] +==== +{project_name} has its own database connection pool, so it does not need a database proxy like PgBouncer. +Do not use PgBouncer. +Connect {project_name} directly to PostgreSQL. +==== + +A proxy adds an additional network hop to every query and makes the setup harder to operate. +As described in this section, it also causes failures during failover and during upgrades that are hard to diagnose. +Use PgBouncer only if you cannot avoid it, and test it with your workload and with an upgrade of {project_name} before using it in production. + +==== Prepared statements + +The PostgreSQL JDBC driver switches to server-side prepared statements for statements that are executed repeatedly. +After the number of executions configured in `prepareThreshold` (default: `5`), the driver names the statement on the database connection and from then on sends only the name and the parameters. + +In PgBouncer's `transaction` pool mode, each transaction can be served by a different database connection. +If PgBouncer does not track prepared statements, the named statement does not exist on the other connection. +{project_name} then fails with errors like `prepared statement "S_1" does not exist` or `prepared statement "S_1" already exists`. +These errors can appear randomly at runtime, and they can abort for example a database migration. + +To use PgBouncer in `transaction` pool mode, choose one of the following options: + +* Use PgBouncer 1.21 or later and set `max_prepared_statements` to a value greater than `0`. +PgBouncer then tracks the prepared statements of each client and prepares them again on the database connection it assigns. +If the value is too low, PgBouncer evicts and prepares statements repeatedly, which increases the CPU usage of PostgreSQL but does not cause errors. +* Disable server-side prepared statements by adding `prepareThreshold=0` to the JDBC URL. +PostgreSQL then needs to parse and plan every statement again, which increases its CPU usage. +* Use the `session` pool mode, where a client keeps its database connection. + +<@kc.start parameters="--db postgres --db-url-properties='?prepareThreshold=0'"/> + +==== Failover and switchover + +When {project_name} connects to PostgreSQL through PgBouncer, connections can fail after a failover or switchover. +PgBouncer caches the `in_hot_standby` value it reports to new client connections, and it can keep reporting `in_hot_standby=on` after the switch. +Because `targetServerType` is set to `primary`, the PostgreSQL JDBC driver then treats the connection as a reader instance and refuses it with the error `Could not find a server with specified targetServerType: primary`. + +This is a known PgBouncer issue, tracked in https://github.com/pgbouncer/pgbouncer/issues/859[pgbouncer/pgbouncer#859]. +Reloading PgBouncer after a failover or switchover makes it report the current value again. + +Setting `targetServerType` to `any` avoids the error, but it also removes the protection described above, so {project_name} might connect to a reader instance. +Only use it if your routing in PgBouncer sends database connections exclusively to the writable primary database. + +Set `targetServerType=any` via `db-url-properties`: + +<@kc.start parameters="--db postgres --db-url-properties='?targetServerType=any'"/> + [[preparing-keycloak-for-amazon-aurora-postgresql]] == Preparing for Amazon Aurora PostgreSQL diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/jpa/QuarkusJpaConnectionProviderFactory.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/jpa/QuarkusJpaConnectionProviderFactory.java index 80c38f83489..707b369f451 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/jpa/QuarkusJpaConnectionProviderFactory.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/jpa/QuarkusJpaConnectionProviderFactory.java @@ -20,6 +20,7 @@ import java.io.File; import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -57,6 +58,8 @@ import io.quarkus.arc.Arc; import io.quarkus.runtime.configuration.DurationConverter; import org.jboss.logging.Logger; +import org.postgresql.PGConnection; +import org.postgresql.PGStatement; import static org.keycloak.config.TransactionOptions.MIGRATION_TRANSACTION_TIMEOUT; import static org.keycloak.connections.jpa.util.JpaUtils.configureNamedQuery; @@ -71,6 +74,8 @@ public class QuarkusJpaConnectionProviderFactory extends AbstractJpaConnectionPr public static final String QUERY_PROPERTY_PREFIX = "kc.query."; private static final Logger logger = Logger.getLogger(QuarkusJpaConnectionProviderFactory.class); private static final String SQL_GET_LATEST_VERSION = "SELECT ID, VERSION FROM %sMIGRATION_MODEL ORDER BY UPDATE_TIME DESC"; + private static final String PSQL_INVALID_SQL_STATEMENT_NAME = "26000"; + private static final String PSQL_DUPLICATE_PREPARED_STATEMENT = "42P05"; private static final String MIGRATION_TRANSACTION_TIMEOUT_KEY = "migrationTransactionTimeout"; enum MigrationStrategy { @@ -113,6 +118,7 @@ public void postInit(KeycloakSessionFactory factory) { checkGaleraSyncWait(); checkMSSQLIsolationLevel(); checkUtf8Encoding(); + checkPostgreSQLPreparedStatements(); String id = null; String version = null; @@ -338,6 +344,64 @@ private void export(Connection connection, String schema, File databaseUpdateFil } } + /** + * Verifies that server-side prepared statements survive a change of the server connection behind a database proxy. + * Proxies like PgBouncer in transaction mode without prepared statement support (PgBouncer before 1.21 or + * {@code max_prepared_statements=0}) hand out a different server connection per transaction. Then the statements + * named by the JDBC driver are missing, which fails randomly at runtime and, for example, aborts a database migration halfway. + *

+ * The check needs two concurrent connections to the database: one is held busy in an open transaction while the other + * runs the probe. This is no additional requirement, as the database migration holds the lock in an open transaction on + * one connection while it uses a second one. If the proxy offers only a single server connection, the probe waits until + * its query timeout expires and the result is treated as inconclusive. + */ + private void checkPostgreSQLPreparedStatements() { + String db = Configuration.getConfigValue(DatabaseOptions.DB).getValue(); + if (Database.Vendor.POSTGRES != Database.getVendor(db).orElseThrow()) { + return; + } + + try (Connection probe = getConnection(); Connection blocker = getConnection()) { + if (!probe.isWrapperFor(PGConnection.class)) { + return; + } + int prepareThreshold = probe.unwrap(PGConnection.class).getPrepareThreshold(); + if (prepareThreshold <= 0) { + // the driver doesn't use named statements, nothing to verify + return; + } + + try (PreparedStatement statement = probe.prepareStatement("SELECT 1")) { + statement.unwrap(PGStatement.class).setPrepareThreshold(prepareThreshold); + // The driver switches to a named server-side statement after the threshold is reached. + for (int i = 0; i <= prepareThreshold; i++) { + statement.executeQuery().close(); + } + + // Keep the server connection that was just used busy in an open transaction. A proxy in transaction + // mode needs to serve the probe from a different server connection, where the named statement doesn't exist. + blocker.setAutoCommit(false); + try (Statement blockerStatement = blocker.createStatement()) { + blockerStatement.execute("SELECT 1"); + } + statement.setQueryTimeout(10); + statement.executeQuery().close(); + } finally { + blocker.rollback(); + } + } catch (SQLException e) { + if (PSQL_INVALID_SQL_STATEMENT_NAME.equals(e.getSQLState()) || PSQL_DUPLICATE_PREPARED_STATEMENT.equals(e.getSQLState())) { + throw new ServerStartupError("The database connection doesn't support server-side prepared statements, which is typical for a database proxy like PgBouncer in transaction mode. " + + "Keycloak's connection pool doesn't need a database proxy, so connect directly to the database. " + + "If you can't avoid the proxy, use PgBouncer 1.21 or later with 'max_prepared_statements' set to a value greater than 0, " + + "use the session pool mode, or disable server-side prepared statements by adding 'prepareThreshold=0' to the JDBC URL. " + + "See the 'Configuring the database' guide for details. " + + "Failure: " + e.getMessage(), false); + } + logger.debugf(e, "Unable to verify prepared statement support due to database exception"); + } + } + private void checkMySQLWaitTimeout() { String db = Configuration.getConfigValue(DatabaseOptions.DB).getValue(); Database.Vendor vendor = Database.getVendor(db).orElseThrow(); From ffa479c41daf9423715227219b61ff9362d67dd6 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Tue, 13 Oct 2026 12:08:05 +0200 Subject: [PATCH 2/2] Added a test Signed-off-by: Alexander Schwartz Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pom.xml | 2 + quarkus/tests/integration/pom.xml | 1 + .../dist/PostgreSQLPgBouncerDistTest.java | 49 ++++++++++++++++++ .../junit5/extension/DatabaseContainer.java | 51 ++++++++++++++++++- 4 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/PostgreSQLPgBouncerDistTest.java diff --git a/pom.xml b/pom.xml index 84f2a8fd591..b0db261093e 100644 --- a/pom.xml +++ b/pom.xml @@ -149,6 +149,8 @@ 9.7.0 18 mirror.gcr.io/postgres:${postgresql.version} + v1.23.1-p2 + mirror.gcr.io/edoburu/pgbouncer:${pgbouncer.version} 17.5 4.0.1 1.29 diff --git a/quarkus/tests/integration/pom.xml b/quarkus/tests/integration/pom.xml index de67ac64f1e..2ee2923f84b 100644 --- a/quarkus/tests/integration/pom.xml +++ b/quarkus/tests/integration/pom.xml @@ -186,6 +186,7 @@ true ${postgresql.container} + ${pgbouncer.container} ${mariadb.container} ${mysql.container} ${infinispan.container} diff --git a/quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/PostgreSQLPgBouncerDistTest.java b/quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/PostgreSQLPgBouncerDistTest.java new file mode 100644 index 00000000000..46968b544f7 --- /dev/null +++ b/quarkus/tests/integration/src/test/java/org/keycloak/it/storage/database/dist/PostgreSQLPgBouncerDistTest.java @@ -0,0 +1,49 @@ +/* + * 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.it.storage.database.dist; + +import org.keycloak.it.junit5.extension.CLIResult; +import org.keycloak.it.junit5.extension.DistributionTest; +import org.keycloak.it.junit5.extension.WithDatabase; +import org.keycloak.quarkus.runtime.cli.command.AbstractAutoBuildCommand; + +import io.quarkus.test.junit.main.Launch; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +/** + * Runs against PostgreSQL behind PgBouncer in transaction mode, which doesn't support prepared statements. + */ +@DistributionTest +@WithDatabase(alias = "postgresql-pgbouncer-transaction-no-prepared-statements", buildOptions = "db=postgres") +@Tag(DistributionTest.STORAGE) +public class PostgreSQLPgBouncerDistTest { + + @Test + @Launch({ "start", AbstractAutoBuildCommand.OPTIMIZED_BUILD_OPTION_LONG, "--http-enabled=true", "--hostname-strict=false" }) + void testStartupFailsWithoutPreparedStatementSupport(CLIResult cliResult) { + cliResult.assertMessage("The database connection doesn't support server-side prepared statements"); + cliResult.assertNoMessage("started in"); + } + + @Test + @Launch({ "start", AbstractAutoBuildCommand.OPTIMIZED_BUILD_OPTION_LONG, "--http-enabled=true", "--hostname-strict=false", "--db-url-properties=?prepareThreshold=0" }) + void testStartupSucceedsWithoutServerSidePreparedStatements(CLIResult cliResult) { + cliResult.assertStarted(); + } +} diff --git a/quarkus/tests/junit5/src/main/java/org/keycloak/it/junit5/extension/DatabaseContainer.java b/quarkus/tests/junit5/src/main/java/org/keycloak/it/junit5/extension/DatabaseContainer.java index 45a61aa9d39..b152b7035f4 100644 --- a/quarkus/tests/junit5/src/main/java/org/keycloak/it/junit5/extension/DatabaseContainer.java +++ b/quarkus/tests/junit5/src/main/java/org/keycloak/it/junit5/extension/DatabaseContainer.java @@ -26,6 +26,8 @@ import org.jboss.logmanager.LogManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.JdbcDatabaseContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.mariadb.MariaDBContainer; import org.testcontainers.mssqlserver.MSSQLServerContainer; import org.testcontainers.mysql.MySQLContainer; @@ -37,8 +39,16 @@ public class DatabaseContainer { static final String DEFAULT_PASSWORD = "Password1!"; + // PostgreSQL behind PgBouncer in transaction mode, without support for prepared statements + static final String POSTGRES_PGBOUNCER_NO_PREPARED_STATEMENTS_ALIAS = "postgresql-pgbouncer-transaction-no-prepared-statements"; + private static final String PGBOUNCER_UPSTREAM_HOST = "postgres"; + private static final int PGBOUNCER_PORT = 5432; + private final String alias; private GenericContainer container; + // only set when the tests connect through a proxy, then 'container' is the proxy + private GenericContainer databaseBehindProxy; + private Network network; DatabaseContainer(String alias) { this.alias = alias; @@ -46,6 +56,9 @@ public class DatabaseContainer { void start() { container = createContainer(); + if (databaseBehindProxy != null) { + databaseBehindProxy.withStartupTimeout(Duration.ofMinutes(5)).start(); + } container.withStartupTimeout(Duration.ofMinutes(5)).start(); } @@ -56,7 +69,14 @@ boolean isRunning() { void configureDistribution(RawKeycloakDistribution dist) { dist.setProperty("db-username", getUsername()); dist.setProperty("db-password", getPassword()); - dist.setProperty("db-url", getJdbcUrl()); + if (databaseBehindProxy != null) { + // not using db-url, as it would cause db-url-properties to be ignored + dist.setProperty("db-url-host", container.getHost()); + dist.setProperty("db-url-port", String.valueOf(container.getMappedPort(PGBOUNCER_PORT))); + dist.setProperty("db-url-database", "keycloak"); + } else { + dist.setProperty("db-url", getJdbcUrl()); + } } private String getJdbcUrl() { @@ -80,6 +100,12 @@ String getPassword() { void stop() { container.stop(); container = null; + if (databaseBehindProxy != null) { + databaseBehindProxy.stop(); + databaseBehindProxy = null; + network.close(); + network = null; + } } private JdbcDatabaseContainer configureJdbcContainer(JdbcDatabaseContainer jdbcDatabaseContainer) { @@ -101,11 +127,31 @@ private GenericContainer createContainer() { String MYSQL_IMAGE = System.getProperty("kc.db.mysql.container.image"); String MSSQL_IMAGE = System.getProperty("kc.db.mssql.container.image"); String TIDB_IMAGE = System.getProperty("kc.db.tidb.container.image"); + String PGBOUNCER_IMAGE = System.getProperty("kc.db.pgbouncer.container.image"); switch (alias) { case "postgres": DockerImageName POSTGRES = DockerImageName.parse(POSTGRES_IMAGE).asCompatibleSubstituteFor("postgres"); return configureJdbcContainer(new PostgreSQLContainer(POSTGRES)); + case POSTGRES_PGBOUNCER_NO_PREPARED_STATEMENTS_ALIAS: + network = Network.newNetwork(); + DockerImageName POSTGRES_BEHIND_PROXY = DockerImageName.parse(POSTGRES_IMAGE).asCompatibleSubstituteFor("postgres"); + databaseBehindProxy = configureJdbcContainer(new PostgreSQLContainer(POSTGRES_BEHIND_PROXY)) + .withNetwork(network) + .withNetworkAliases(PGBOUNCER_UPSTREAM_HOST); + return new GenericContainer<>(DockerImageName.parse(PGBOUNCER_IMAGE)) + .withNetwork(network) + .withEnv("DB_HOST", PGBOUNCER_UPSTREAM_HOST) + .withEnv("DB_NAME", "keycloak") + .withEnv("DB_USER", getUsername()) + .withEnv("DB_PASSWORD", getPassword()) + .withEnv("AUTH_TYPE", "scram-sha-256") + .withEnv("POOL_MODE", "transaction") + .withEnv("DEFAULT_POOL_SIZE", "5") + // The default of PgBouncer doesn't track prepared statements, which is the problematic setup to test for + .withEnv("MAX_PREPARED_STATEMENTS", "0") + .withExposedPorts(PGBOUNCER_PORT) + .waitingFor(Wait.forListeningPort()); case "mariadb": DockerImageName MARIADB = DockerImageName.parse(MARIADB_IMAGE).asCompatibleSubstituteFor("mariadb"); return configureJdbcContainer(new MariaDBContainer(MARIADB)); @@ -137,6 +183,7 @@ public void start() { } private String resolveInitScript() { - return String.format("database/scripts/init-%s.sql", alias); + String script = POSTGRES_PGBOUNCER_NO_PREPARED_STATEMENTS_ALIAS.equals(alias) ? "postgres" : alias; + return String.format("database/scripts/init-%s.sql", script); } }