Moving Keycloak to a different database such as PostgreSQL

A practical guide to changing the database under an existing Keycloak, from choosing a supported target to a full realm export and import with the server stopped, including what exports leave out and how to plan the cutover window.

On this page

Moving Keycloak to PostgreSQL: what the move involves and how long it takes

This is a planned export, import and cutover, not a live copy of a running database. Keycloak does not replicate its data from MySQL to PostgreSQL while it serves logins. Instead, you export the realms with the server stopped, import them into a Keycloak pointed at the new database, and then send traffic there. The effort depends on three things: how many users you hold, whether you run custom providers that must be rebuilt, and how long a login outage the business will accept. Exact duration has to be estimated from your own environment, using a rehearsal on a copy of production data.

The Keycloak database guide lists the supported production databases, and PostgreSQL 14 to 18 is among them. Confirm that your target version is on that list when you choose it, and check the PostgreSQL support dates before you commit, since PostgreSQL 14 is scheduled to leave support in November 2026. Your choice of target also decides who operates the database: high availability, backups and point-in-time recovery are your responsibility, and Keycloak's supported high availability designs assume a synchronously replicated database. Agree those capabilities with your database team before the cutover plan is written.

Ask for the cutover plan in writing before work starts. It should name the export directory and its size, the rehearsal count, the stop and start steps for the server and the old database, the post-import checks (realm counts, client redirect URIs, admin login and a test sign-in per application), and the rollback point. Confirm with the vendor or your own tests which realm data is excluded from exports, because the import and export guide lists items such as user events and persisted sessions that do not carry over, and plan for users to sign in again. The cost is mostly skilled hours for planning, rehearsal and verification, plus the outage window itself, which is a one-time cost, while the new database's operating cost recurs.

Choosing a supported target database

Running PostgreSQL on servers, virtual machines or Kubernetes that you control gives the most direct control over versions, extensions, network placement and backup tooling. Keycloak supports PostgreSQL 14 to 18, so the target version should be chosen from the supported list before the build starts. Per the PostgreSQL versioning policy, version 18 was first released September 25, 2025 and is supported until November 14, 2030, version 17 until November 8, 2029, version 16 until November 9, 2028, version 15 until November 11, 2027 and version 14 until November 12, 2026. Your team carries every operational duty.

  • Version window: Choose a major version with a support end date that outlasts your planned Keycloak life cycle, and note that version 14 ends November 12, 2026.
  • Licensing: The PostgreSQL License is a liberal open source license similar to the BSD or MIT licenses, so there is no per-core database license fee to plan for.
  • Backups: Your team must set up and test continuous archiving and point-in-time recovery.
  • High availability: Hot standby, synchronous replication and an external failover tool are your responsibility, since PostgreSQL does not detect primary failure on its own.
  • Patching: Minor releases arrive at least every three months and must be applied by your team.

Confirm that your team has staff who can operate PostgreSQL failover and restore procedures before you commit to this path.",

What maps cleanly from the old database and what does not

This table compares each part of a Keycloak installation against what a full realm export carries and what it leaves out, then names the target-side equivalent. Read it as a checklist for a test export: anything marked as omitted or masked needs a manual rebuild or a decision before cutover. The main takeaway is that configuration generally moves across, while runtime state, event history and secret values do not.

ComponentWhat a full export carriesWhat to verify or rebuild on the target
RealmsRealm settings, authentication flows, and realm configuration are included in a full realm exportCompare realm count and settings after import, including token lifetimes and browser flow bindings
Users and credentialsUser records are exported, and the export guide advises a directory output above 50,000 usersTest a login with a sample of migrated accounts, and confirm password hashes and OTP credentials carried over as expected in your test
Clients and secretsClient definitions are included, but secret values are masked on exportReset or re-enter every confidential client secret and update each application before cutover
Roles and groupsRealm roles, client roles, and group memberships are part of the realm representationSpot-check composite roles and default roles, since membership errors surface as access failures
Identity providers and federation linksIdentity provider configuration is exported, and federated user links are carried with users in the realm dataConfirm upstream client secrets for each identity provider are re-entered, and test brokered sign-in for each one
Realm keysKey material is handled through the export, but private values may be maskedVerify token signing still works and that relying parties accept the realm's public keys after import
SessionsPersisted sessions are not included in exportsExpect every user to sign in again after cutover and plan the communication for that
User and admin eventsEvents are not included in exportsArchive or export event data from the old database separately if your audit process needs it
Workflow stateWorkflow state is not included in exportsCheck for in-flight workflows at the cutover window and let them finish or restart them deliberately
Revoked tokensRevoked token records are not included in exportsAssume revocations do not carry over and review any access that was revoked just before cutover
Database schemaNot exported. Keycloak creates and migrates the schema automatically at startup on the target by defaultConfirm the target PostgreSQL version is supported (14 to 18) and that startup completes before import

Documented export, import and migration paths

Keycloak's documented tools for moving realm data are launches of the server itself, not a database-to-database copy. The cards below cover the constraints that shape a database change: when the export and import commands may run, how large exports are handled, how the schema is built, and where PostgreSQL's own tools fit.

Export and import need a stopped server

The kc.sh export and kc.sh import commands run as server launches that exit when they finish. They must not run while the Keycloak server is running against the source or target database. Plan the cutover window around this, because a live server can write changes that an export will not capture. Confirm the exact flags for your Keycloak version in the import and export guide before you script the procedure.

Import and export guide

Export to a directory at scale

For more than 50,000 users, the import and export guide advises exporting to a directory rather than a single file. A single large file is harder to verify, restart and move between hosts. Ask your team to measure user count, client count and realm count before choosing the format, and keep the exported directory as the rollback artifact until the new database is confirmed.

Automatic schema migration at startup

Keycloak migrates its database schema automatically at startup by default. That is convenient for small installs, but it means the first start against an empty PostgreSQL database builds the schema for you. Confirm that the target database user has the rights the schema build needs, and that the Keycloak version that builds the schema matches the version that exported the realms.

Manual SQL for large deployments

The upgrading guide suggests manual migration, where administrators apply the schema SQL themselves, for large deployments. Reviewing the SQL before it runs gives your database administrators control over tablespaces, indexes and change records. Ask the implementation team to produce the SQL for the exact target version and to store it with the cutover runbook.

PostgreSQL tools only within PostgreSQL

pg_dumpall, pg_upgrade and logical replication move data between PostgreSQL versions, not between unrelated engines. They do not help when the source is MySQL or MariaDB. Use them only for a PostgreSQL-to-PostgreSQL major upgrade underneath Keycloak. For a change of engine, the Keycloak realm export and import is the documented path.

Keycloak database guide

Admin REST API reads are limited

The Administration REST API can read realms, users and clients while Keycloak runs, which helps with inventory and reconciliation. It is not a complete backup. Events, persisted sessions, workflow state and revoked tokens are not part of the realm export, so teams must decide separately how to handle them. Confirm which data your applications and audit requirements depend on before relying on the API alone.

What a Keycloak export leaves out and how to restore it

A realm export does not carry everything that makes a running Keycloak useful, so the cutover plan has to account for each gap. The Keycloak import and export guide states that exports omit user and admin events, persisted sessions, workflow state and revoked tokens. For the target database, that means every user with an active session must sign in again after cutover, because no session rows arrive with the realm. Audit history stays on the source database: user events and admin events remain queryable only where they were written, so the team should archive or query the source before it is decommissioned and record where compliance evidence now lives.

Revocation state also needs a deliberate review. Revoked tokens are not carried over, so any access or refresh token revoked on the source before the export may be honored on the target until it expires. Ask the security team to decide whether the token lifetimes in the realm are short enough to accept that window or whether a forced sign-out is needed for affected accounts. Workflow state is in the same category: any in-flight workflow or scheduled action should be listed and either completed or recreated before the final export is taken.

Secrets are the second gap. Client secrets, identity provider client secrets, LDAP bind credentials and SMTP passwords may come back masked in the export, so they cannot be treated as restored. Plan to re-enter each one from the secrets store, then confirm that the target actually uses it. Afterwards, re-test every social provider and brokered identity provider, plus LDAP or Kerberos user federation, with a test account from each path. Check group and role mappers as well, since a broker that signs in successfully can still assign the wrong access. Confirm the exact export behavior for your Keycloak version against the Keycloak import and export guide before you write the runbook.

The sequence: inventory, rehearsal, parallel run, cutover and decommission

This sequence moves a working Keycloak from one database engine to another with a known set of realms, clients and providers, a rehearsed import, a tested target, and a short, agreed stop of the server. Each step closes with a check that tells the team whether it can move on.

  1. Inventory realms, clients, providers and the Keycloak version

    The Keycloak administrator and the application owners list every realm, client, redirect URI, identity provider, user federation link, custom SPI provider, theme, and any secret or certificate the server holds. They record the exact Keycloak version and the current database engine and version, and confirm the target is on the supported list in the Keycloak database guide. The inventory is done when every realm has an owner and every item that an export will not carry (user and admin events, persisted sessions, revoked tokens, workflow state) has a documented plan, such as a session reset or a notice to users.

  2. Rehearse the export and import on non-production

    The platform team builds a non-production Keycloak on the same Keycloak version as production, with the target PostgreSQL major version and the same custom providers and themes deployed. They run a full export from a recent copy of production and import it into the rehearsal database, then log every error, warning and manual fix. Keep a written record of the commands, the export directory layout, and how long the stopped-server steps took on this data set. The rehearsal is complete when a clean import runs twice in a row from the same procedure.

  3. Validate the target with a parallel run

    The new database and a Keycloak instance connected to it run alongside production, using the real redirect URIs, identity provider callbacks, LDAP or Active Directory federation, and SMTP settings, with test accounts and a small set of pilot applications. Testers confirm login, MFA, token refresh, logout, admin console access, and the connection behavior under the proxy and load balancer in front of Keycloak. Read the target database's backup and monitoring setup at the same time. The step closes when the team signs off each application in writing and the open issues are either fixed or accepted with an owner.

  4. Confirm the cutover window and freeze changes

    The change owner agrees a window with the application owners and the service desk, then announces it with the expected sign-in interruption. Administrators stop configuration changes in production, take a fresh backup of the current database, and confirm that the rehearsed export procedure still matches the production environment. The window is confirmed when every stakeholder has acknowledged it and the rollback decision point and the person who makes it are written down.

  5. Export with the server stopped and import into the target

    Administrators stop every Keycloak node, because the export and import commands run as separate launches that must not run while the server is active. They run the full realm export to a directory, which the Keycloak import and export guide advises for large user counts, then import into the target database using the rehearsed procedure. Compare realm, client, user and provider counts between source and target, then start the new instance and check that the administrator and a test user can sign in. The step is done when the counts match and the smoke tests pass.

  6. Switch DNS or the load balancer to the new instance

    The network team moves the public hostname or load balancer pool to the Keycloak nodes connected to the new database, keeping the old pool ready for rollback. The team runs the same smoke tests against the public endpoint, checks the admin hostname and reverse proxy path restrictions, and reviews the metrics and logs for errors in the first hours. Application owners confirm sign-in and token flows from their own systems. The step closes when the public path is verified and the rollback has been tested or the team has confirmed it can be run quickly.

  7. Decommission the old database after backup retention

    After the agreed post-cutover period, the team keeps the old database and its final backup for the retention period set by the organization's backup and records policy. They confirm that no node still connects to the old database, remove its credentials and network access, and then retire it according to the decommissioning procedure. The record includes the export archive, the final backup location, the rollback decision, and the names of the people who approved retirement. The step is done when the audit record is complete and the old instance is no longer reachable.

How the cutover flow moves data from the old database to PostgreSQL

The flow starts with the source Keycloak stopped, because the export command runs as a server launch that must not overlap a running server. The export writes to a directory in the client's environment, the target PostgreSQL is provisioned at a version on Keycloak's supported list, and the import loads the data into it. Test realm checks then decide whether the team cuts over to the new database or returns to the source. Partner access, if any, should stay inside the client's trust boundary and be limited to the work window.

Phases of a database change, with the partner access boundary shown around the client environment.

What drives the cost and duration of the move

This table lists the factors that change how much work a Keycloak database move takes, what raises each one and what lowers it. Use it to read a quote: each row is a question the partner should answer in the written scope. No price is given here, because cost follows from the scope you agree.

DriverWhat raises effortWhat lowers effort
User countAbove 50,000 users the export should go to a directory rather than one file, and verifying a large import takes longerSmaller user base, or a confirmed export and import test on a copy of production data
Realms and clientsMany realms, each with its own clients, redirect URIs and role mappings that must be checked after importFew realms with documented client inventories and a verified list of redirect URIs
Custom SPI providers and themesProviders and themes that must be rebuilt and tested against the target Keycloak version and its database driverStandard providers only, or custom code already tested on the current release
LDAP, Kerberos and brokered identity providersFederation settings, bind credentials and brokered client secrets that need re-entry or validation after import, plus live directory testsRead-only federation with documented bind accounts, and a test login for each upstream provider
High availability topologyA clustered deployment needs a synchronously replicated target database, so replication design and failover tests are added workSingle node in a non-production window, or an existing synchronous replication setup on the target
Cutover windowA short agreed window with a fixed server stop leaves little room for retries and forces rehearsalsA longer window with a rehearsed runbook and a named go or no-go decision point
Backup and rollback requirementsRequirements to restore the original MySQL or other source database and prove it works, plus retention rules for exportsExisting tested backups of the source database and a documented rollback step that does not depend on the new database
Client change controlFormal approval steps, change records and evidence that each step ran as planned, with multiple approval roundsA standing change process with pre-approved standard changes and a named approver for the window

What usually goes wrong and how to prevent it

Most failed database moves for Keycloak come from a short list of avoidable mistakes made during the export, the import or the switch. Each card below names one failure, why it matters for this move, and the check that prevents it.

Exporting while the server runs

The export and import commands are server launches that exit when done and must not run while the server is running. Running an export against a live node can produce an inconsistent snapshot, and a team that skips the stop step may not notice until users report missing data. Prevent it by scripting the stop, confirming no node answers on its health endpoint, and only then starting the export. For large user bases, export to a directory rather than a single file, as the import and export guide advises.

Import and export guide

Losing realm keys and masked secrets

A realm export does not carry every value you need to run the realm. Client secrets and some provider credentials can come out masked, and the keys used to sign tokens must be present in the target or every issued token becomes invalid. Before cutover, record the realm signing keys, list every client and identity provider secret, and confirm each one is restored from your own secret store. Test a token signed before the move against the new instance so you know the keys survived.

Version mismatch between export and import

The export and import must run on the same Keycloak version, and the new database must be a supported target such as PostgreSQL 14 to 18. Starting a newer server against an old export, or a different build against the new database, can fail schema checks or change behavior silently. Pin the exact release in your deployment manifest, run the export and import with that same build, and record the version in the cutover runbook before the window opens.

Users locked out after cutover

Exports omit user and admin events, persisted sessions, workflow state and revoked tokens. Every user who was signed in before the cutover will need to authenticate again, and any revoked-token list starts empty, so a token revoked on the old system can work on the new one. Plan the cutover so users expect a re-login, confirm that revocations made in the final hours are reapplied, and tell the security team which token state was not carried over.

Export contents

Applications pointing at the old hostname

Clients store redirect URIs, web origins and issuer values, and a move that changes the Keycloak hostname or path breaks sign-in even when the database is correct. Inventory every client's redirect URIs and the issuer URL each application trusts, then run a test sign-in against the new instance from each application before DNS changes. Keep the old hostname answering with redirects until all applications are confirmed.

An untested rollback path

The old MySQL database is the only known-good copy until the new system has run real traffic, so rollback depends on keeping it intact and reachable. Teams often decommission the source too early or find that rolling back requires re-exporting data that changed after cutover. Before the window, write the rollback steps, rehearse them in a non-production copy, decide the point after which rollback is no longer practical, and keep the source database read-only with its backups verified until that point passes.

Questions buyers ask before moving Keycloak to a new database

How much effort does moving Keycloak to a new database take?

The effort depends mainly on the size of the realm data, the number of custom providers and themes, and how many applications depend on stable client settings. The database change itself is a full realm export, a clean target database, and an import with the server stopped, so the core steps are mechanical. The work that takes time is verification: comparing user counts, client redirect URIs, role mappings and identity provider settings in the new environment, and testing sign-in for each application. Ask any partner to split its quote into export and import rehearsal, environment work, verification, and cutover support, and to state which items are one-time and which recur after go-live.

How long does the cutover window need to be, and what sets it?

The window is set by how long the server must stay stopped while the export and import run, plus time for verification and the rollback decision. Keycloak's kc.sh export and kc.sh import run as launches that exit when done and must not run while the server is running, so sign-in is unavailable for the full stop. Export and import time grows with user count, and for more than 50,000 users the Keycloak import and export guide advises exporting to a directory rather than one file. Rehearse the full sequence on a copy of production data and time each step before agreeing a window with the business.

Can our own team move Keycloak to a new database without a partner?

Yes, a team with database and Keycloak administration skills can do this in-house, and the steps are documented in the Keycloak database and import and export guides. The risk lies in what the export leaves out: user and admin events, persisted sessions, workflow state and revoked tokens are not carried over, so the team must decide what to accept losing and communicate it. Also check whether the team has rehearsed the change, can roll back to the old database quickly, and has someone who owns the production cutover decision. If any of these are missing, an outside partner can plan and rehearse the work under a written scope.

What does the work need from our database, identity and application teams?

Each group has a distinct role. Database owners provision the target PostgreSQL instance, set authentication and TLS, size storage, plan backups, and confirm the network path from Keycloak nodes. Identity admins own the export, the realm review, the import, the Keycloak configuration file changes and the post-cutover checks of login flows, identity providers and admin access. Application owners confirm their redirect URIs, client secrets and logout behavior still work against the restored realms. Agree named owners and a sign-off list before rehearsal, because most delays come from waiting for a decision rather than from technical work.

Will users have to sign in again after the database change?

It depends on what the export carries and on your session lifetimes. Keycloak exports omit persisted sessions and revoked tokens, so users with active sessions at cutover are likely to be asked to authenticate again once the new database is live. Users' accounts, credentials and realm configuration are part of the realm export, so their passwords and enrolled second factors normally keep working. Confirm the exact behavior in a rehearsal, decide whether to announce a re-login, and check that any revoked-token state you rely on is handled by a documented process.

Which PostgreSQL version should we choose for the new database?

Choose a version that is supported for the whole planned life of the Keycloak deployment. Keycloak's supported production databases include PostgreSQL 14 to 18. According to the PostgreSQL versioning policy, version 18 is supported until November 14, 2030, version 17 until November 8, 2029, version 16 until November 9, 2028, version 15 until November 11, 2027, and version 14 until November 12, 2026. Starting on a version that is close to end of life means a second database upgrade soon after cutover, so favor the newest version your Keycloak release and your platform team support. Confirm the choice against the Keycloak database guide for your target release before you commit.

What should we check before we agree a quote for this move?

Ask for the written scope to name the Keycloak version and current distribution, the source and target database types and versions, the realm count, user count, custom providers and themes, and the applications that depend on each realm. Ask whether the quote covers at least one full rehearsal on production-sized data, the cutover itself, rollback planning, and verification after go-live. Confirm who provisions and secures the PostgreSQL instance, and whether backups and monitoring are included or left to your team. A clear scope lets you compare offers on the same basis, and it shows which costs recur if you also want ongoing support.

How DeployOpen scopes and delivers a Keycloak database move

DeployOpen plans a move of an existing Keycloak to a new database as a fixed-scope engagement inside your infrastructure. We agree the target database, export and import method, cutover window and rollback path in writing before any change is made to your production realms.

How we scope

  • Confirm the current database, the Keycloak version and the target database, including whether the target is on the supported list for your Keycloak release.
  • Inventory realms, clients, identity providers, user federation links, themes and custom SPI providers that must survive the move.
  • Agree in writing what the export excludes, such as user and admin events, persisted sessions and revoked tokens, and how each gap is handled.
  • Define the cutover window, the maintenance communication plan and the go or no-go criteria before the engagement starts.

How we build

  • Build the target database platform and its backup, high availability and connection settings in your infrastructure before any data moves.
  • Run a full realm export with the server stopped, then test the import into a non-production Keycloak on the target database.
  • Check realm counts, client redirect URIs, identity provider settings, secrets and user login paths against the source before sign-off.
  • Repeat the export and import rehearsal until the cutover runbook is accurate, then document the rollback steps.

How we hand over

  • Deliver the migration runbook, configuration changes, verification checklist and a record of what was exported and what was not.
  • Document the target database operations your team owns, including backups, restores, patching and monitoring of the Keycloak connection.
  • Provide a post-cutover review listing open items, such as sessions users must re-establish and events that were not carried over.
  • Walk your administrators and platform engineers through the runbook so the next Keycloak upgrade can be planned by your team.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Support during the cutover window and the first production days is covered in the written scope where agreed.
  • Ongoing Keycloak support, upgrades and continuous testing are available as a retainer after the move.
  • Ask for a quote built from the written scope, which should list each component, the environments covered and any hosting or licensing costs you pay directly.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.