Keycloak Infinispan cache configuration and tuning

Keycloak embeds Infinispan for realm, user, session and other caches that decide how a cluster behaves under load. This page explains which caches are local or distributed, how to size entry limits, and how jdbc-ping discovery and persistent sessions fit in.

On this page

Why Keycloak cache tuning decides how a cluster behaves under load

Infinispan is the embedded distributed cache that Keycloak uses to keep frequently read state close to the node that needs it, and it is the component you tune when a multi-node cluster with growing realms, users and sessions starts to slow down or behave unevenly. Teams usually need to look at it when login latency rises as realm and user counts grow, when session counts climb, or when a node restart or scale-out event causes a visible spike in database reads. Keycloak splits its work across several cache families. Realm and user caches hold configuration and user lookups that change rarely, session caches hold user and client sessions that change on every login and token refresh, and the authentication and action token caches hold short-lived flow state. Some of these caches are local to each node and some are distributed across the cluster, and that split determines how much data each node holds and how much traffic moves between nodes.

The exact default cache names, their entry limits and the sizing rules change between releases, so confirm them against the Keycloak version you run before you change anything. Read the cache section of the server configuration guide for your release, and check the upgrade notes for any cache changes, since cache behavior can differ between minor lines. Keep a record of the defaults you start from, because a tuning change that looks correct in a test realm can behave differently once production realm sizes, client counts and session volumes arrive. Also confirm how your cluster discovers its members, since jdbc-ping and the database it relies on affect how nodes join and leave the cache topology.

Treat cache tuning as a decision with a measurable outcome rather than a set of values copied from a blog post. Before you change a limit, decide which signal proves the change worked, such as database read volume, cache hit behavior exposed through Keycloak's metrics, or login latency under a representative load test. Write down your expected realm count, user count, concurrent session count and client count, because those drive every entry limit that follows. If you cannot yet state those numbers, that gap is the first task, and the sizing and load testing work in this page's sibling sections will help you close it.

Which Keycloak caches are local and which are distributed

Keycloak stores much of its working state in embedded Infinispan caches, and each cache either lives on a single node or is shared across the cluster. That choice decides how much traffic moves between nodes, what a node failure costs users, and where tuning effort pays off. The cards below cover the cache categories to map before you change any setting.

Local caches hold per-node data

A local cache keeps its entries on the node that created them, so reads are fast and no cluster traffic is needed to serve them. The trade-off is that each node warms its own copy, and an entry changed on one node is not automatically visible on another unless Keycloak sends an invalidation message. Check which realm and user caches are local in your version, and confirm how invalidation reaches the other nodes before you raise their entry limits.

Server admin docs

Distributed caches share entries across nodes

A distributed cache spreads entries across the cluster and keeps a configured number of copies, so a node can serve data it does not hold locally. This adds network calls on every remote read and write, and it changes how much memory each node needs. Ask how many owners each distributed cache keeps and what happens to entries held by a node that fails.

High availability overview

Realm and user caches

Realm and user caches store configuration and account data that Keycloak reads on almost every login, so their hit rate drives database load. Entry limits here decide how many realms and users stay in memory before eviction sends reads back to the database. Size these against the number of realms and active users you expect, and watch cache hit metrics after go-live.

Session and client-session caches

Session caches hold user and client sessions, including the tokens and state needed for refresh and logout. Whether these entries are replicated, and how many copies exist, determines whether a user stays signed in when a node restarts. Confirm which session caches are distributed in your version and whether persistent sessions are enabled before you plan a node failure test.

Work and action token caches

Work caches track short-lived actions such as one-time codes, action tokens and similar single-use state across requests. Because these entries are often needed by whichever node receives the next request, their ownership affects whether a login flow survives a load balancer moving it to another node. Review these caches when you enable multi-step flows or a load balancer without sticky sessions.

Confirm the cache list for your version

The set of caches, their names, and their local or distributed mode can change between Keycloak releases, so no list in a guide should be copied into production unchanged. Before tuning, export the cache configuration from your running version and check the cache metrics your deployment exposes. Record the owner count and entry limit for each cache so that changes after an upgrade can be compared against a known baseline.

Cache options and when each one fits

This table compares the cache choices a team weighs when tuning Keycloak's embedded Infinispan caches. Read each row for the condition that favors the option and the memory, network or database cost it adds. Confirm exact configuration keys in the Keycloak documentation for your release before you change them.

OptionWhen it fitsWhat it costsWhat to confirm
Realm and user entry limitsMany realms or a large user base where repeated lookups slow loginsHigher memory use on each node as more entries stay cachedExact entry-limit keys and defaults for your release
Local caches for realm and metadata dataData that changes rarely and can be reloaded safely on each nodeEach node holds its own copy, so memory grows with node countWhich caches Keycloak runs as local in your version
Distributed session cachesClusters where a login must survive the loss of one nodeMemory per active session and network traffic between nodesOwner count and replication settings for session caches
Offline session handlingLong-lived refresh tokens for background jobs or mobile appsOffline sessions live in the database, so cache misses add readsHow many offline sessions the cache keeps before it evicts
Persistent user sessionsSessions that must survive a full cluster restartExtra database writes when session state changesWhether your release enables persistent sessions by default
Cache histograms in metricsTuning phases where you need hit rates and latency per cacheMore metric series for Prometheus to store and queryHistogram flag names alongside --metrics-enabled=true
Discovery with jdbc-pingClusters on networks where multicast discovery is blockedDatabase queries when nodes join, leave or refresh membershipDatabase permissions and table setup for discovery

How jdbc-ping cluster discovery joins Keycloak nodes

jdbc-ping lets Keycloak nodes find each other through the database they already use, so a cluster can form without multicast networking or Kubernetes-specific discovery services. Each node registers its address in a shared table and reads the other entries to build its Infinispan cluster view. For a team running Keycloak on virtual machines, behind a network that blocks multicast, or on a platform where the Kubernetes discovery path is not available, this is the practical choice. The trade-off is that the database becomes part of cluster formation, not only part of data storage.

That dependency has two consequences you should plan for. First, cluster membership is only as consistent as the discovery table, so stale rows from nodes that crashed or were replaced can make a restarting node try to contact addresses that no longer answer. Confirm with your platform team how node addresses are assigned and how the table is cleaned up after a node leaves. Second, a node that starts while the database is unreachable cannot join the cluster, and a node that loses the database mid-run may not rejoin cleanly. Decide in advance whether your startup scripts or orchestrator restart nodes automatically and how long a database failover may take before operators need to intervene.

When you restart a node in a test or maintenance window, verify three things before you call the change complete. Check that the node appears in the cluster view on every other node and that the member count matches what you expect. Check that the Infinispan caches show the same membership and that sessions created on other nodes are still served. Check the node logs for discovery and join errors, and confirm that the database connection pool is healthy after the restart. Repeat the restart with the database primary switched, if your database uses failover, because that is the case most likely to expose discovery gaps. The exact jdbc-ping settings and table names depend on your Keycloak version, so confirm them against the Keycloak high availability overview before you write the runbook.

How to set up and verify a tuned Infinispan cache configuration

This sequence takes a Keycloak cluster from an inventory of realms, users and sessions to a cache configuration that is checked node by node. Each step ends with a membership or metric check so problems surface before the next node joins.

  1. Inventory realms, users and active sessions

    The platform owner counts realms, users per realm, expected concurrent user sessions, and client or service account volume, then records which realms are expected to grow. Use the Keycloak admin console or the Administration REST API for realm and user counts, and your load balancer or existing login logs for peak concurrent sessions. The step is done when the team has a written baseline that the cache limits in later steps can be based on. Confirm the figures with your own environment, since cache sizing depends on your workload.

  2. Choose the cache configuration method

    The team decides how cache settings reach the nodes: the Keycloak Operator custom resource, container arguments or environment variables, or a Keycloak server configuration file. Choose one method and keep it in version control so every node gets the same settings. Check the Keycloak server configuration guide for the cache options your installed version supports, and confirm the chosen method with the Operator documentation if you run on Kubernetes. The step is done when a single reviewed configuration source exists and a test node starts with it.

  3. Configure jdbc-ping for cluster discovery

    Set the JGroups discovery protocol to jdbc-ping so nodes find each other through the Keycloak database, which avoids a separate discovery service. The database user must be able to create and write the discovery table that jdbc-ping uses. Start a single node and confirm in its startup log that it registers with the discovery table and reports itself as the only cluster member. The step is done when the table holds one entry for that node and the log shows no discovery errors.

  4. Enable persistent sessions in the database

    Decide whether user and client sessions should be written to the database so they survive a full cluster restart. Enabling persistent sessions adds database writes, so the team should check the database connection pool and I/O capacity before enabling it. After the change, sign in to a test realm, restart the node, and confirm the session still exists in the admin console or the sessions endpoint. The step is done when a test session survives the restart and the database write load looks acceptable in your database monitoring.

  5. Apply entry limits to realm, user and session caches

    Set maximum entry counts for the local caches holding realm and user data and for the session caches, using the baseline from the first step. Keep caches that hold per-node data local and keep session and login state distributed, as the Keycloak cache documentation describes for each cache. Record the chosen limits and the reason for each. The step is done when the configuration file lists an explicit limit for every cache the team changed, and each value traces back to the inventory.

  6. Start nodes one at a time

    Bring up the first node with the full configuration, then add each further node only after the previous one reports healthy. Watch the startup log for cache initialization errors and for jdbc-ping registration. Do not start nodes in parallel, because simultaneous joins make membership problems harder to trace. The step is done when every node has joined and the log on each node shows the expected number of cluster members.

  7. Verify cluster membership and cache metrics

    After each node joins, confirm the member count in the discovery table or the logs matches the number of running nodes. Enable metrics with the metrics option on the management interface, then query the cache metrics at the /metrics endpoint for hit ratios, entry counts and evictions. Run a test login on one node and confirm the session is visible from another node. The step is done when membership matches the node count, the metrics show entries in the expected caches, and cross-node sign-in works.

  8. Record the verified configuration and repeat checks

    Save the verified configuration, the membership and metric results, and the test session results in the runbook. Repeat the membership and cache metric checks after each Keycloak upgrade, each change to realm count, and each node count change, since those events can change cache behavior. The step is done when the runbook names the owner of each check and the date it was last run.

Sizing caches for many clients, many realms or large user bases

When one realm holds a large number of clients (applications, APIs, service accounts), the caches that hold client definitions, client scopes, roles and their mappings grow with the number of clients and the number of distinct tokens each client requests. Client-level data is read on nearly every token request, so the hit rate on these caches matters more than their absolute size. Most of this data is administrative and changes rarely, which means the main risk is not churn but eviction of entries that many clients need at the same time.

  • Client and scope entries: Count clients, client scopes and protocol mappers in the realm before changing any limit, since each one occupies cache space.
  • Role and group mappings: Large role hierarchies multiply the entries needed to resolve a single token, so review the effective roles per client.
  • Hit rate on realm caches: Watch the cache hit and miss metrics during peak token issuance, not averages over a quiet day.
  • Admin changes during peak: Bulk client creation or configuration pushes invalidate entries across nodes, so schedule them outside login peaks.
  • Load test with the real client count: Use a dataset that matches your client count and token scenarios, then compare hit rates before and after the change.

Confirm the exact cache names, their entry limits and the metric names for your Keycloak version against the Keycloak observability guide and the server configuration reference before writing any change.

Security and operational risks in cache changes

Cache changes alter where Keycloak keeps realm, client, user and session state, so they can expose data, serve stale configuration or open traffic between nodes. Each card names one risk, the control to apply and the check to run after every change.

Stale cached realm and client data

Realm, client and user entries are cached on each node, and a change made on one node can leave other nodes serving the old value for a while. Treat a redirect URI, client secret or role change as a cache event, not just a database write. After each change, log in and request a token through every node or through the load balancer, then confirm the new client settings take effect. Ask the Keycloak team which cache entries are invalidated cluster-wide and which rely on expiry.

Production guide

Session data in shared caches

Sessions are held in distributed caches, so a session replica on another node holds the same login state as the primary. Limit who can read cache contents, keep the cluster on a private network and avoid enabling persistent sessions without a decision about where that data is stored and backed up. After a change to session caches, sign in, confirm single sign-on works across two applications, then sign out and check that the session is removed on every node.

Unencrypted cluster traffic between nodes

Infinispan nodes exchange cache entries over the network, and those entries can include session and token-related state. Confirm that the cluster transport runs on an isolated network segment, that only Keycloak nodes can reach the cluster port, and that transport encryption is configured where your policy requires it. After any change to discovery or transport settings, check from outside the cluster that the cluster port does not answer and that all nodes still form one view.

Exposed metrics and management endpoints

Enabling --metrics-enabled=true exposes Prometheus metrics at /metrics on the management interface, and cache histograms can reveal how many sessions and entries a realm holds. Keep the management port off the public load balancer, allow scrapes only from the monitoring network and disable the optional cache histograms if they are not needed. After enabling metrics, request /metrics from an external address and confirm it is refused.

Metrics guide

Memory pressure from entry limits

Raising entry limits without measuring memory use can push a node into garbage collection pauses or out-of-memory restarts, which look like login failures to users. Set limits per cache, not as one global number, and record heap use before and after each change under representative login load. Confirm that eviction behaves as expected by checking cache statistics and login latency during a test run.

Unreviewed cache changes in configuration

Cache settings often change through configuration files, environment variables or operator resources, and a single missed node can run different values from the rest of the cluster. Keep cache configuration in version control, roll it out through the same process as other Keycloak changes and compare the effective settings on every node after each deployment. Record the change, the test that validated it and the rollback steps in the change ticket.

Questions teams ask before tuning Keycloak caches

How much effort does Keycloak Infinispan cache tuning take?

Effort depends mostly on how many nodes, realms, clients and concurrent sessions the deployment carries, and on how much of that load is already measured. A single-realm cluster with default caches and a clear login profile usually needs a bounded review: confirm which caches are local and which are distributed, check entry limits, and confirm the metrics that show cache pressure. Multi-realm or high-client-count deployments add work because each realm's users, sessions and client data interact with cache sizing and need separate testing. Ask any partner for the written scope to list the caches, realms and load profiles it will cover, since that list drives the quote.

Can our internal team tune Keycloak caches without outside help?

Yes, a team with Keycloak operations experience can do cache tuning, provided it has a test environment that matches production topology and a repeatable way to generate load. The risky parts are changing distributed cache settings without understanding how session replication and failover behave across nodes, and reading cache metrics without a baseline. Internal teams usually succeed when they document the current configuration, change one setting at a time, and retest after each change. Bring in a partner when the team lacks load testing capacity, when the deployment spans several sites, or when a change must be proven before a regulated go-live.

What do we need to provide for a cache tuning engagement?

The work needs access to the running Keycloak configuration, the database and cluster topology, and the metrics that describe cache and login behavior. Keycloak can expose Prometheus-format metrics at /metrics on its management interface when started with --metrics-enabled=true, and cache histograms are optional, so confirm they are enabled before the engagement starts. Also provide representative load data: realm and user counts, client counts, expected login and token refresh volumes, and any peak periods. A test environment that mirrors production node count and database type is needed to validate changes without touching live sessions.

How long does cache tuning take relative to Keycloak release and test cycles?

The timeline is set by the test cycle, not by the tuning itself. Keycloak plans four minor releases a year and a major release every two to three years, and changes that touch caching should be checked against the version you run before they reach production. Each tuning iteration needs a load test, a metrics review and a rollback check, so the schedule depends on how many iterations the baseline requires and how long your change windows are. Plan the work around your own release freeze and change calendar, and confirm the expected duration in the written scope rather than relying on a general estimate.

Does a cache change need to wait for a Keycloak upgrade?

Cache configuration should be re-verified after any Keycloak upgrade, because defaults and cache behavior can change between releases. Since Keycloak 26.0, breaking changes in a minor release are meant to be opt-in, but that does not remove the need to test caching under your own load. Keep cache settings in version control, record the Keycloak version they were validated against, and rerun the same load profile after each upgrade. Check the upgrade notes for the version you are moving to before scheduling the change.

What drives the cost of a cache tuning partner engagement?

Cost is driven by the number of nodes and realms in scope, the size of the test environment, how many load profiles must be proven, and whether persistent sessions or cluster discovery with jdbc-ping are part of the design. Recurring costs appear only if you buy ongoing support or retesting after upgrades, which is typically a retainer. Ask for a quote that lists the deliverables, the environments used, the number of test cycles included, and what happens if results require a second round. DeployOpen does not publish a price list, and each quote follows from the written scope.

When is it worth bringing in a partner for Keycloak cache tuning?

Bring in a partner when a change affects login availability and your team cannot prove the result in a test environment. Typical triggers include multi-site or multi-realm deployments, large client counts, persistent session requirements, a planned go-live with a compliance review, or repeated cache incidents after load peaks. A partner is also useful when internal staff are needed for other platform work and cannot give the testing the change requires. DeployOpen plans, implements, tests and documents self-hosted platforms in your infrastructure, and it prepares evidence for compliance assessments without issuing audit reports.

How Keycloak nodes, caches and the database fit together

The diagram starts at the load balancer, which forwards public traffic to Keycloak nodes on the public side of the trust boundary. Each node holds local caches for data that can be rebuilt, and distributed Infinispan caches whose entries are shared with peer nodes over cluster traffic. Membership discovery through jdbc-ping and all persistent data (realms, users, clients) go through the database. Check that the management interface, which serves /metrics and health endpoints, is reachable only from inside the trust boundary, and that cluster traffic never crosses it.

Request path, cache placement, cluster traffic and database dependencies in one Keycloak cluster.

How DeployOpen scopes and delivers Keycloak cache tuning

DeployOpen works on Keycloak Infinispan cache configuration as part of a self-hosted Keycloak deployment inside your own infrastructure. We start from your realm count, client count, login pattern and cluster topology, then agree a written scope before any configuration changes are made to your environment.

How we scope

  • We record realm, user, client and session volumes, plus the number of Keycloak nodes planned for the cluster.
  • We confirm whether the deployment is a single cluster, a multi-cluster design or a stateless setup before choosing cache settings.
  • Engagements are fixed-scope, with the cache review, deliverables and timeline agreed in writing before work starts.

How we build

  • We review which Infinispan caches stay local and which are distributed, then set entry limits for realms, users and sessions.
  • We configure jdbc-ping discovery and persistent session settings, then test node joins, leaves and restarts in a non-production cluster.
  • We check cache behavior with the Keycloak metrics endpoint enabled, so tuning decisions rest on observed hit rates and memory use.

How we hand over

  • We deliver the cache configuration as files and change records, with each setting explained against your workload and the reason for it.
  • We document the verification steps, including how to confirm cache sizes and cluster membership after an upgrade or node change.
  • Your team receives a runbook covering when to revisit cache limits, what to monitor and which changes need a load test first.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers, so cache settings can be reviewed as your login volume grows.
  • We retest cache settings after Keycloak upgrades, since cache defaults and related configuration can change between releases.
  • Retainer work can include periodic review of cache metrics against the targets agreed in the original scope.

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.