Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Deployment and Operations

Database and Clustering

Plan the Keycloak database and a multi-node cluster: supported databases, connection pools, Infinispan caches, session ownership, discovery, load balancing and sizing.

A single Keycloak node is a single point of failure, and a slow database makes every login slow. Production deployments run several nodes behind a load balancer, against one shared database, with a distributed cache that holds sessions. This lesson explains what lives where, how nodes find each other, and what to tune first.

Keycloak cannot run on this site. The configuration examples are read-only and based on recent Keycloak versions, so verify option names against your release. The TryIt blocks are small JavaScript simulations of ideas (cache ownership, pool sizing) rather than Keycloak code.

What lives where

Keycloak keeps two kinds of state:

  • Persistent data in the relational database: realms, clients, users, credentials, roles, groups, and configuration. Changes are written here, and a node restart loses nothing.
  • Cached data in memory (Infinispan): sessions and caches of realm, user, and authorization data, replicated or distributed among nodes for speed.

Supported databases include PostgreSQL, MariaDB, MySQL, Oracle, and Microsoft SQL Server. PostgreSQL is the usual default choice. Choose the vendor at build time with --db=postgres and supply --db-url, --db-username, --db-password at start. Use a managed database service or a replicated cluster with automatic failover; Keycloak itself does not replicate the database.

Schema and migrations

On startup after an upgrade, Keycloak migrates the schema automatically (Liquibase). Back up before every upgrade and let one node finish the migration before others start (rolling updates are handled carefully in newer versions; see the upgrade lesson).

Connection pool

Each node holds a pool of database connections. Defaults are modest. Tune:

  • --db-pool-initial-size, --db-pool-min-size, --db-pool-max-size
  • Total connections across nodes must stay below the database's own limit (for PostgreSQL, max_connections).
JS Stand-in: connection pool budget

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Clustering with Infinispan

Keycloak nodes form a cluster using an embedded Infinispan library. Key points:

  • Distributed caches such as sessions, authenticationSessions, offlineSessions, and loginFailures split entries across nodes with owners (the default is two copies). If one node dies, the other copy survives and users stay logged in.
  • Local caches such as realms, users, authorization hold read-optimized copies per node. When something changes, a node sends an invalidation message through the work cache so others drop their copy.
  • Discovery: nodes must find each other. With --cache=ispn (the default with multiple nodes), choose the stack with --cache-stack: tcp is common; kubernetes uses DNS ping via a headless service; jdbc-ping stores membership in the database and works on any platform; cloud-specific stacks exist. Open the clustering ports between nodes (typically 7800) and never expose them publicly.

On Kubernetes, the Keycloak Operator manages the StatefulSet, services, and cache settings; it is the supported path for most teams.

flowchart TB
  LB["Load balancer"] --> N1["Node 1"]
  LB --> N2["Node 2"]
  LB --> N3["Node 3"]
  N1 <-->|"Infinispan"| N2
  N2 <-->|"Infinispan"| N3
  N1 <-->|"Infinispan"| N3
  N1 --> DB[("PostgreSQL")]
  N2 --> DB
  N3 --> DB

All nodes share one database and a distributed session cache.

Session ownership

Think of each session as stored on N owner nodes, chosen by hashing the session ID. A simple model helps to see why losing one node is survivable but losing too many is not:

JS Stand-in: session owners and node failure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Set --cache-owners-style options (the exact option name depends on version, and cache configuration may be done with an XML file passed by --cache-config-file) to match your tolerance for failures. More owners means more memory and network traffic.

Newer: persistent user sessions

Recent versions can store user sessions in the database (a feature often called persistent user sessions) so a full-cluster restart does not log everyone out, at the cost of more database load. Check whether it is enabled by default in your version and measure the database impact.

Load balancing

  • Use a layer 7 load balancer with health checks on /health/ready (management port).
  • Sticky sessions are recommended for performance: Keycloak sets a KC_ROUTE-style cookie or uses the node ID in the session cookie, so requests for a session land on the owner node and avoid network hops. The cluster works without stickiness, only slower.
  • Send admin traffic to any node; it is stateless apart from caches.
  • Spread nodes across availability zones; the database must be reachable at low latency.

Multi-site

Active/active across regions needs the database and Infinispan synced across sites. Recent releases document supported multi-cluster setups (typically active/passive or active/active with an external Infinispan and a synchronous database). It is a specialist topic: start with a single region, three nodes, and tested failover.

Sizing first guess

  • Memory: start at 1.5 to 2 GB heap per node for small deployments; leave room for off-heap and the OS. Set JAVA_OPTS_KC_HEAP or use percentage-based settings in containers.
  • CPU: password hashing is the biggest per-login cost (PBKDF2/Argon2), so CPU scales with login rate, not with session count.
  • Database: login writes (sessions are in cache, but events, user updates, and refresh handling touch the DB). Index and vacuum maintenance matter on large user tables.
  • Test with load tools against a staging cluster before launch; measure login latency at your target rate.

Operations checklist

  • At least three nodes for a rolling restart without losing owners.
  • Database backups and tested restores.
  • Health checks wired to the load balancer.
  • Cluster ports closed to the internet.
  • Alerting on cluster size, DB connections, and login latency.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where are realms, users and credentials stored?

    Persistent data lives in the database; Infinispan holds sessions and caches.
  2. 2. What does numOwners of 2 mean for a distributed cache entry?

    Each entry is stored on two nodes, giving fault tolerance for one failure.
  3. 3. Which must you check when sizing connection pools across nodes?

    Total possible connections must fit inside the database's configured limit.
  4. 4. Why are sticky sessions recommended?

    The cluster works without stickiness, but locality improves performance.

Summary

  • Persistent data lives in the database; sessions and caches live in Infinispan.
  • Pool size times node count must fit the database limit.
  • Cache owners provide fault tolerance; discovery stacks let nodes find each other.
  • Use health checks, sticky sessions, and at least three nodes.
  • Measure under load before launch.

Next: Monitoring, Events and Metrics