What Happens to Your Database During a Keycloak Upgrade. Keycloak migrates its own schema with Liquibase when the first new node starts. See how it works on PostgreSQL, the manual SQL option, timing and rollback.
Keycloak migrates its own database schema when you upgrade, and by default it does this automatically the first time you start the new version. In the guide’s words, “By default, the database is automatically migrated when you start the new installation for the first time” (Keycloak Upgrading Guide). Back up the database first and read the migration notes for every release you cross, because there is no downgrade: “Keycloak does not support rolling back the database changes”, so rolling back means restoring the backup and starting the old version again (Keycloak Upgrading Guide).
Our other upgrade posts, such as the best strategy to upgrade a Keycloak cluster and upgrading Keycloak from 8 to 24, give the database a paragraph each. This one covers only the database step, on PostgreSQL, in the order you would do it: how Keycloak decides what to change, the automatic and manual ways to apply it, what has to wait on what, how long it takes on big tables, and what to do when it goes wrong. The option names below come from the Upgrading Guide for Keycloak 26.8.2, the current release when this was written, so check them against the guide for your target version.
How does Keycloak decide which schema changes to run?
Keycloak describes its schema changes as Liquibase changesets: the Upgrading Guide notes that its migration script “creates the Liquibase DATABASECHANGELOG table, which it records the applied changesets in” (Keycloak Upgrading Guide). A changeset is one small, named change, such as adding a column or creating an index, and Liquibase records each changeset it applies in a tracking table so it can tell which changes a database still lacks (Liquibase tracking tables).
The record lives in Liquibase’s tracking table, DATABASECHANGELOG, inside Keycloak’s own schema. Each row is one changeset that has run, “identified by a combination of the id, author, and filename columns”, and an MD5SUM column holds the “Checksum of the changeset when it was executed” so Liquibase can spot a changeset that was edited after it ran (Liquibase DATABASECHANGELOG table). A changeset with no row yet has not run. You can see the last changesets your database recorded with a query like this:
SELECT id, author, filename, dateexecuted
FROM databasechangelog
ORDER BY orderexecuted DESC
LIMIT 10;
The second tracking table, DATABASECHANGELOGLOCK, makes sure only one process migrates at a time. Liquibase “uses the DATABASECHANGELOGLOCK (DBCLL) table to ensure only one instance of Liquibase runs at a time”, sets its LOCKED column while an update runs, and any other process “waits until the lock releases before running it” (Liquibase DATABASECHANGELOGLOCK table). That lock is what keeps two new nodes from applying the same change at once, and it is also the source of the most common stuck upgrade, which we cover in the troubleshooting section.
Automatic or manual migration?
Keycloak can apply the changes itself or write them to a SQL file for someone to review. In the guide’s words, “By default, the database is automatically migrated when you start the new installation for the first time” (Keycloak Upgrading Guide).
Automatic is what most teams use. You start one node on the new version with your usual configuration, it takes the lock, runs the pending changesets, releases the lock and carries on starting. Nothing extra needs configuring, which is why it suits teams that rehearse the upgrade on a copy of production first.
Manual suits teams whose database changes have to go through a DBA or a change process. You set the JPA migration strategy to manual, and Keycloak writes the SQL to keycloak-database-update.sql in its working directory instead of running it (Keycloak Upgrading Guide):
bin/kc.sh start \
--spi-connections-jpa--quarkus--migration-strategy=manual \
--spi-connections-jpa--quarkus--migration-export=/tmp/keycloak-database-update.sql
“After the changes have been written to the file, the server exits”, so this run does not serve traffic (Keycloak Upgrading Guide). Your DBA reviews and applies the file, then you start the new version normally. Two details from the guide matter here. When the database user is not allowed to create tables, the Liquibase tables should exist on both databases, so “Have an administrator create them up front, both on the database used to generate the script and on the database the script is applied to”, and “On the first startup, it might perform additional data migrations that are required in addition to the schema migrations”, so the first real start can still take longer than usual. Generate the file against a database at the same version as production, or it will describe the wrong set of changes.
The same option lists manual, update and validate as its values (Keycloak database guide).
In what order do you upgrade, and what waits on what?
The order is backup, then the schema change, then the rest of the nodes, and each step waits for the one before it to finish.
You back up the database (1), stop every old node (2), start one new node that runs the pending changesets before it serves traffic (3), then start the other new nodes, which find nothing left to migrate (4). If anything fails, you restore the backup and start the old version.
- Back up the database. The guide asks you to back up the old installation (configuration, themes and so on) and to “Back up the database using the instructions in the documentation for your relational database” (Keycloak Upgrading Guide). On PostgreSQL, pg_dump is “a utility for exporting a PostgreSQL database” that “makes consistent exports even if the database is being used concurrently”, which suits a snapshot taken right before the upgrade, and our Keycloak backup and restore guide explains why the database, not a realm export, is the backup. A realm export is not enough on its own, since “Exported data does not include user and admin events, persisted sessions, workflow state or revoked tokens” (Keycloak import and export).
- Stop every node on the old version. The guide says “Before you migrate the database, shut down all Keycloak nodes running the old version of Keycloak” (Keycloak Upgrading Guide), because “The database schema will no longer be compatible with the old server after the upgrade” (Keycloak Upgrading Guide).
- Start one node on the new version and watch its log until it has finished starting. This is the node that migrates, and starting only one keeps the migration in a single place that is easy to follow.
- Start the remaining nodes. They find no pending changesets and start normally.
Two versions should share one schema only when Keycloak says a rolling update is safe. The 26.6.0 notes say “Zero-downtime patch releases are now enabled by default”, which allows rolling updates “when upgrading to a newer patch version within the same” major and minor release stream (Keycloak Upgrading Guide), and the guide’s first step is “Shut down Keycloak if no rolling update is supported, for example if you perform a minor or major upgrade” (Keycloak Upgrading Guide). To check a specific change, run kc.sh update-compatibility metadata with the old version and configuration, then kc.sh update-compatibility check with the new one. Exit code 0 means “Rolling Update is possible”, and 3 means “The deployment must be shut down before applying the new configuration” (Keycloak rolling updates guide). Release notes can also forbid mixing versions for other reasons. For example, after a change to how client sessions are stored, the 26.4.0 notes say “you should not run 26.4.x concurrently in a cluster with previous versions” (Keycloak Upgrading Guide).
When you are several releases behind, upgrade one major version at a time, through the latest patch of each intermediate major, and back up before each step, as our Keycloak upgrade risk checker recommends. Read every “Migrating to” section between your current and target versions too. Some releases change behavior as well as the schema, and some have asked for a specific intermediate stop: the 2.0.0 notes, for example, say “To upgrade to this version upgrade to 1.9.8.Final prior to upgrading to 2.0.0” (Keycloak Upgrading Guide). Our posts on the Keycloak 26.0.0 migration steps and on finding and replacing deprecated options cover the configuration side of the same jump.
How long does the migration take on large tables?
Nobody can give you a fixed number, and the guide says so: “The migration time of the database schema and its contents can vary depending on hardware, release and the amount of data” (Keycloak Upgrading Guide). The reliable way to know is to restore last night’s backup into a test environment and time the upgrade there, as in our walkthrough on testing Keycloak and PostgreSQL upgrades with Docker Compose.
Before that rehearsal, look at which of your tables are big, because those are the ones a changeset can slow down. PostgreSQL keeps approximate row counts in its statistics views, where n_live_tup is the “Estimated number of live rows” (PostgreSQL statistics views):
SELECT relname, n_live_tup
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC
LIMIT 10;
Compare the list with the tables the release notes name for your versions. Some releases avoid a long index build on a big table: for a new index on EVENT_ENTITY, the 26.4.0 notes say that if the table “contains more than 300,000 entries, Keycloak skips the index creation during the automatic schema migration”, and that “the SQL statement appears on the console during migration so you can apply it manually after Keycloak startup” (Keycloak Upgrading Guide). The 26.8.0 notes do the same for rebuilt indexes on large offline session tables (Keycloak Upgrading Guide). Check the startup log of the migrating node for that SQL and plan to run it at a quiet time, because until you do, the queries it was meant to speed up stay slow. Our PostgreSQL tuning guide for Keycloak has more on indexes and table maintenance.
Two timeouts can end a long migration early. The first is Keycloak’s own: transaction-setup-timeout “Controls the timeout for transactions used by database schema migration, import, and export commands. The default value is 30 minutes” (Keycloak database guide). If your rehearsal comes close to that, raise it for the migrating node, for example --transaction-setup-timeout=60m.
The second, on Kubernetes, is the startup probe. Keycloak’s /health/started endpoint is the “Startup probe used for initial startup of Keycloak before the liveness probe takes over”, served on the management port 9000 once you build with --health-enabled=true (Keycloak health checks). Kubernetes gives a container failureThreshold times periodSeconds to pass its startup probe: with the documented values of 30 and 10, “the application will have a maximum of 5 minutes (30 * 10 = 300s) to finish its startup”, and “If the startup probe never succeeds, the container is killed after 300s and subject to the pod’s restartPolicy” (Kubernetes probe documentation). If that window is shorter than your migration, the pod is killed halfway through, the lock can be left behind, and the next pod waits on it. Size the window from your rehearsal with plenty of room, for example:
startupProbe:
httpGet:
path: /health/started
port: 9000
periodSeconds: 10
failureThreshold: 360 # 60 minutes for the migrating start
You can lower it again after the upgrade if you prefer faster failure detection on ordinary restarts.
The cluster, without the on-call
Skycloak runs real upstream Keycloak in the region you choose, and takes the upgrades, backups, certificate rotation and patching off your team. No fork, so you can export and self-host whenever you want.
What goes wrong, and how do you fix it?
- The new node waits forever on the lock. A previous migration was killed, often by a probe or an out-of-memory kill, and left the lock row set. Liquibase’s documentation says “If Liquibase does not exit cleanly, the lock row may be left as locked”, and its fix is
release-locks, which “runsUPDATE DATABASECHANGELOGLOCK SET LOCKED=0” (Liquibase DATABASECHANGELOGLOCK table). Before clearing it by hand, make sure no Keycloak process is running against the database, look at the rows withSELECT * FROM databasechangeloglock;, and clear only a row that is still locked. Then decide whether to start again or restore the backup, because a migration that died halfway may have applied only part of its changes. - The migration stops with a transaction timeout. The migration ran longer than
transaction-setup-timeout. Restore the backup, raise the timeout and try again. - Old nodes start failing after the new one starts. An old node was still running, or restarted, against the migrated schema. Stop them all; “The database schema will no longer be compatible with the old server after the upgrade” (Keycloak Upgrading Guide).
- The pod restarts in a loop during the upgrade. The startup probe window is shorter than the migration. Widen it as shown above, then deal with the lock left by the last attempt.
- Requests time out after the upgrade even though it finished. The migrating node may have skipped an index on a large table. Look for the logged SQL and apply it. If the database is simply short of connections while every node starts at once, our post on Keycloak connection pool exhaustion covers the pool settings.
How do you roll back?
You restore. Keycloak has no down migrations, so the guide’s instruction is: “if you need to roll back to the previous version, first restore the old installation, and then restore the database from the backup copy” (Keycloak Upgrading Guide). With a custom-format dump that means stopping every Keycloak node, restoring with pg_restore, whose --clean option is “useful for overwriting an existing database”, and starting the old version’s image with its old configuration.
Anything that changed in Keycloak between the backup and the rollback is lost, including new users, password changes and sessions. That is why the backup belongs right before step 2, when the old nodes stop, and why it pays to agree before the upgrade how long you will spend fixing forward before you restore. Our production readiness checklist lists the backup and restore drills worth having in place before you need them.
FAQ
Does Keycloak migrate the database automatically?
Yes. By default the database is migrated automatically when you start the new version for the first time (Keycloak Upgrading Guide). Set the migration strategy to manual if you want the SQL written to a file for review instead (Keycloak Upgrading Guide).
Can I downgrade Keycloak after the database has been migrated?
No. “Keycloak does not support rolling back the database changes”, and the migrated schema is not compatible with the old version (Keycloak Upgrading Guide). To go back, stop Keycloak, restore the database from the backup you took before the upgrade and start the old version.
Can old and new Keycloak versions run against the same database?
Only when a rolling update is supported, which since 26.6.0 means patch releases in the same minor line (Keycloak Upgrading Guide), and kc.sh update-compatibility check confirms it (Keycloak rolling updates guide). For minor and major upgrades, stop every old node first (Keycloak Upgrading Guide).
How do I generate the SQL for a DBA to review?
Start the new version with --spi-connections-jpa--quarkus--migration-strategy=manual and, optionally, --spi-connections-jpa--quarkus--migration-export with a file path. Keycloak writes the SQL and exits without serving traffic (Keycloak Upgrading Guide).
Why is my Keycloak upgrade stuck on startup?
Usually because a previous attempt was killed and left the Liquibase lock set in databasechangeloglock, or because a long migration is still running. Check the log of the migrating node first, and clear the lock only when no Keycloak process is running.
Next steps
Before you touch the database, run your current and target versions through our Keycloak upgrade risk checker, which lists the breaking changes between them, then rehearse the upgrade on a restored copy of production and time it. If you would rather not plan upgrades and backups at all, Skycloak’s managed Keycloak hosting handles both for you.
Sources
- Keycloak, “Upgrading Guide”, https://www.keycloak.org/docs/latest/upgrading/
- Keycloak, “Configuring the database”, https://www.keycloak.org/server/db
- Keycloak, “Importing and exporting realms”, https://www.keycloak.org/server/importExport
- Keycloak, “Update compatibility (rolling updates)”, https://www.keycloak.org/server/update-compatibility
- Keycloak, “Tracking instance status with health checks”, https://www.keycloak.org/observability/health
- Liquibase, “DATABASECHANGELOG table”, https://docs.liquibase.com/concepts/databasechangelog-table.html
- Liquibase, “DATABASECHANGELOGLOCK table”, https://docs.liquibase.com/concepts/databasechangeloglock-table.html
- PostgreSQL, “pg_dump”, https://www.postgresql.org/docs/current/app-pgdump.html
- PostgreSQL, “pg_restore”, https://www.postgresql.org/docs/current/app-pgrestore.html
- PostgreSQL, “The Cumulative Statistics System”, https://www.postgresql.org/docs/current/monitoring-stats.html
- Kubernetes, “Configure Liveness, Readiness and Startup Probes”, https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/




