8000 Use READ COMMITTED transaction isolation for all databases by ahus1 · Pull Request #55792 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
3 changes: 2 additions & 1 deletion docs/documentation/tests/src/test/resources/ignored-links
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ https://developer.linkedin.com*
https://www.keycloak.org/guides#authorization-services
https://www.keycloak.org/authorization-services/policies
https://www.keycloak.org/authorization-services/services#obtaining-permissions
https://www.keycloak.org/authorization-services/services#discovering-endpoints-and-metadata
https://www.keycloak.org/authorization-services/services#discovering-endpoints-and-metadata
https://www.keycloak.org/server/db#mysql-mariadb-transaction-isolation-level
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ This prevents deadlocks that occur under concurrent logins.
If binary logging is enabled with `binlog_format = STATEMENT`, this change will cause write operations to fail.
{project_name} logs an error at startup when it detects this incompatible setting.

See the link:https://www.keycloak.org/server/db#mysql-mariadb-transaction-isolation-level-in-stateless-mode[Transaction isolation level in stateless mode] section in the database configuration guide for details on `binlog_format` requirements.
See the link:https://www.keycloak.org/server/db#mysql-mariadb-transaction-isolation-level[Transaction isolation level in stateless mode] section in the database configuration guide for details on `binlog_format` requirements.

Changing the default transaction isolation level for all modes is being considered for a future release.

Expand Down
10 changes: 10 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@ Existing client scope assignments are not removed by this change.
Administrators should review dynamically registered clients for unintended scope assignments and remove them through the Admin Console or Admin REST API.
All nodes handling client registration requests must be upgraded for the check to apply consistently.

=== READ COMMITTED transaction isolation for all databases
// https://github.com/keycloak/keycloak/issues/54133

{project_name} now explicitly sets the JDBC transaction isolation level to `READ COMMITTED` for all supported databases and refuses to start if the effective isolation level differs.
This was already the default for PostgreSQL, Oracle, and SQL Server; for MySQL, MariaDB, and TiDB it was only applied when the `stateless` feature was enabled.
The change prevents gap-lock deadlocks and stale-snapshot conflicts (MariaDB `innodb_snapshot_isolation`) that occur under `REPEATABLE READ`.

No action is required for PostgreSQL, Oracle, or SQL Server users because they already use `READ COMMITTED`.
MySQL and MariaDB users must verify that `binlog_format` is set to `ROW` or `MIXED`, not `STATEMENT`, because statement-based replication is incompatible with `READ COMMITTED`.

=== Redirect URI loopback exceptions require literal IP addresses
// https://github.com/keycloak/keycloak/issues/54413

Expand Down
13 changes: 7 additions & 6 deletions docs/guides/server/db.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -414,15 +414,16 @@ Beginning with MySQL 8.0.30, MySQL supports generated invisible primary keys for
If this feature is enabled, the database schema initialization and also migrations will fail with the error message `Multiple primary key defined (1068)`.
You then need to disable it by setting the parameter `sql_generate_invisible_primary_key` to `OFF` in your MySQL server configuration before installing or upgrading {project_name}.

[#mysql-mariadb-transaction-isolation-level-in-stateless-mode]
=== Transaction isolation level in stateless mode
[#mysql-mariadb-transaction-isolation-level]
=== Transaction isolation level

When the `stateless` feature is enabled, {project_name} automatically sets the transaction isolation level to `READ COMMITTED` for MySQL and MariaDB.
The default `REPEATABLE READ` isolation level acquires gap locks on upsert statements, which causes deadlocks under concurrent logins.
`READ COMMITTED` is the default isolation level used by PostgreSQL, Oracle, and Microsoft SQL Server.
{project_name} sets the transaction isolation level to `READ COMMITTED` for all databases via JDBC.
MySQL and MariaDB default to `REPEATABLE READ`, which acquires gap locks on upsert statements and can cause deadlocks.
MariaDB additionally enables `innodb_snapshot_isolation` by default starting with 11.6.2, which under `REPEATABLE READ` can fail concurrent attribute updates with error 1020 ("Record has changed since last read").
`READ COMMITTED` avoids both issues and matches the isolation level used by PostgreSQL, Oracle, and Microsoft SQL Server.

This requires that binary logging is not configured with `binlog_format = STATEMENT`.
MySQL 8.0 and later default to `binlog_format = ROW`, and MariaDB 10.6 and later defaults to `binlog_format = MIXED`, both of which are compatible.
MySQL 8.0 and later default to `binlog_format = ROW`, and MariaDB 10.6 and later default to `binlog_format = MIXED`, both of which are compatible.

To verify your current setting, run:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,8 @@ public List<ProviderConfigProperty> getConfigMetadata() {
@Override
public void postInit(KeycloakSessionFactory factory) {
if (writeSessionUpdatesInMainTransaction) {
// Only when read-committed is enabled, it is safe to opportunistically upgrade a read lock to a write lock.
// Should work for PostgreSQL, Oracle and MSSQL that use read committed by default.
// In all other isolation levels this can lead to a deadlock as seen for example with MariaDB (SnapshotIsolationException / "Record has changed since last read")
// Keycloak configures READ COMMITTED for all databases; verify at runtime before enabling
// opportunistic read-to-write lock upgrades (other isolation levels cause deadlocks).
prepareEnabled = KeycloakModelUtils.runJobInTransactionWithResult(factory, session -> {
EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
return em.unwrap(Session.class).doReturningWork(connection -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.util.function.Supplier;
import java.util.stream.Collectors;

import org.keycloak.common.Profile;
import org.keycloak.common.util.DurationConverter;
import org.keycloak.config.DatabaseOptions;
import org.keycloak.config.Option;
Expand Down Expand Up @@ -295,10 +294,6 @@ public List<PropertyMapper<?>> getPropertyMappers() {
fromOption(SYNTHETIC_RUNTIME_DB_OPTION).mapFrom(DB, (name, value, context) -> "false")
.to(MSSQL_SEND_STRING_PARAMETER_AS_UNICODE)
.isEnabled(DatabasePropertyMappers::isMssqlSendStringParametersAsUnicode)
.build(),
fromOption(SYNTHETIC_RUNTIME_DB_OPTION).mapFrom(DB, (name, value, context) -> "read-committed")
.to("quarkus.datasource.jdbc.transaction-isolation-level")
.isEnabled(DatabasePropertyMappers::isReadCommittedIsolationRequired)
.build()
));

Expand Down Expand Up @@ -427,22 +422,6 @@ public static boolean isMssqlSendStringParametersAsUnicode() {
!dbUrlProperties.contains("sendStringParametersAsUnicode");
}

/**
* MySQL and MariaDB default to REPEATABLE READ transaction isolation, which acquires gap locks on
* {@code INSERT ... ON DUPLICATE KEY UPDATE} statements. When the stateless feature is enabled,
* concurrent login requests execute such upserts on authentication session and login failure tables,
* causing deadlocks under load. Switching to READ COMMITTED eliminates gap locks and resolves
* these deadlocks. This matches the isolation level PostgreSQL, Oracle, and SQL Server use by default.
*/
public static boolean isReadCommittedIsolationRequired() {
String db = Configuration.getConfigValue(DB).getValue();
Database.Vendor vendor = Database.getVendor(db).orElse(null);
if (vendor != Database.Vendor.MYSQL && vendor != Database.Vendor.MARIADB && vendor != Database.Vendor.TIDB) {
return false;
}
return Profile.isFeatureEnabled(Profile.Feature.STATELESS);
}

private static ValueMapper getConnectTimeout(Collection<Database.Vendor> validForVendors, String timeoutProperty) {
return (String datasource, String value, ConfigSourceInterceptorContext context) -> {
String db = getDatasourceOptionValue(DB, datasource).orElse(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ public void postInit(KeycloakSessionFactory factory) {
checkMySQLWaitTimeout();
checkMySQLBinlogFormat();
checkGaleraSyncWait();
checkIsolationLevel();
checkMSSQLIsolationLevel();
checkUtf8Encoding();

Expand Down Expand Up @@ -414,6 +415,25 @@ private void checkGaleraSyncWait() {
}
}

private void checkIsolationLevel() {
String db = Configuration.getConfigValue(DatabaseOptions.DB).getValue();
Database.Vendor vendor = Database.getVendor(db).orElseThrow();

try (Connection connection = getConnection()) {
int isolation = connection.getTransactionIsolation();
if (isolation != Connection.TRANSACTION_READ_COMMITTED) {
throw new ServerStartupError(String.format(
"%s transaction isolation level is %d, but Keycloak requires READ COMMITTED (%d). "
+ "Check the database configuration and the 'transaction-isolation-level' JDBC setting.",
vendor, isolation, Connection.TRANSACTION_READ_COMMITTED), false);
}
} catch (ServerStartupError e) {
throw e;
} catch (SQLException e) {
logger.warnf(e, "Unable to validate %s transaction isolation level due to database exception", vendor);
}
}

private void checkMSSQLIsolationLevel() {
String db = Configuration.getConfigValue(DatabaseOptions.DB).getValue();
Database.Vendor vendor = Database.getVendor(db).orElseThrow();
Expand Down
5 changes: 5 additions & 0 deletions quarkus/runtime/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ quarkus.http.access-log.log-directory=${kc.home.dir:default}${file.separator}dat
# Enables metrics from other extensions if metrics is enabled
quarkus.datasource.metrics.enabled=${quarkus.micrometer.enabled:false}

# Keycloak requires READ COMMITTED isolation for all databases. MySQL and MariaDB default to
# REPEATABLE READ, which causes gap-lock deadlocks and stale-snapshot conflicts. Setting this
# via JDBC ensures consistent behavior regardless of server defaults.
quarkus.datasource.jdbc.transaction-isolation-level=read-committed

quarkus.hibernate-orm.persistence-xml.ignore=true
quarkus.hibernate-orm.mapping-files=no-file

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ protected void testSuccessful(CLIResult cliResult) {
cliResult.assertNoMessage("charset encoding");
}

@Test
@Launch({ "start", AbstractAutoBuildCommand.OPTIMIZED_BUILD_OPTION_LONG, "--http-enabled=true", "--hostname-strict=false",
"-Dquarkus.datasource.jdbc.transaction-isolation-level=serializable" })
protected void testFailsWithWrongIsolationLevel(CLIResult cliResult) {
cliResult.assertError("Keycloak requires READ COMMITTED");
cliResult.assertNoMessage("Listening on:");
}

@Test
@Launch({ "start", AbstractAutoBuildCommand.OPTIMIZED_BUILD_OPTION_LONG, "--http-enabled=true", "--hostname-strict=false", "--db-username=wrong" })
protected void testWrongUsername(CLIResult cliResult) {
Expand Down
Loading
0