FFFF Detect problematic pgbouncer setup on startup by ahus1 · Pull Request #53904 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
Diff view
66 changes: 50 additions & 16 deletions docs/guides/server/db.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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

Expand Down
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@
<mysql-jdbc.version>9.7.0</mysql-jdbc.version>
<postgresql.version>18</postgresql.version>
<postgresql.container>mirror.gcr.io/postgres:${postgresql.version}</postgresql.container>
<pgbouncer.version>v1.23.1-p2</pgbouncer.version>
<pgbouncer.container>mirror.gcr.io/edoburu/pgbouncer:${pgbouncer.version}</pgbouncer.container>
<aurora-postgresql.version>17.5</aurora-postgresql.version>
<aws-jdbc-wrapper.version>4.0.1</aws-jdbc-wrapper.version>
<cnpg.major-minor-version>1.29</cnpg.major-minor-version>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -113,6 +118,7 @@ public void postInit(KeycloakSessionFactory factory) {
checkGaleraSyncWait();
checkMSSQLIsolationLevel();
checkUtf8Encoding();
checkPostgreSQLPreparedStatements();

String id = null;
String version = null;
Expand Down Expand Up @@ -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.
* <p>
* 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() {
Comment thread
ahus1 marked this conversation as resolved.
Resolved
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();
Expand Down
1 change: 1 addition & 0 deletions quarkus/tests/integration/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@
<kc.test.storage.database>true</kc.test.storage.database>
<!--DB Container -->
<kc.db.postgresql.container.image>${postgresql.container}</kc.db.postgresql.container.image>
<kc.db.pgbouncer.container.image>${pgbouncer.container}</kc.db.pgbouncer.container.image>
<kc.db.mariadb.container.image>${mariadb.container}</kc.db.mariadb.container.image>
<kc.db.mysql.container.image>${mysql.container}</kc.db.mysql.container.image>
<kc.infinispan.container.image>${infinispan.container}</kc.infinispan.container.image>
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -37,15 +39,26 @@ 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;
}

void start() {
container = createContainer();
if (databaseBehindProxy != null) {
databaseBehindProxy.withStartupTimeout(Duration.ofMinutes(5)).start();
}
container.withStartupTimeout(Duration.ofMinutes(5)).start();
}

Expand All @@ -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() {
Expand All @@ -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) {
Expand All @@ -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));
Expand Down Expand Up @@ -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);
}
}
Loading
0