What Is Infinispan Caching in Keycloak?

What Is Infinispan Caching in Keycloak?

A complete, beginner-friendly walkthrough of the distributed, in-memory cache that keeps Keycloak fast and consistent, especially when it's running across more than one server.

Imagine a chain of coffee shops in the same city, all owned by one company. If every barista had to call company headquarters and wait for an answer before confirming a customer’s loyalty points balance, service would be painfully slow. Instead, each shop keeps a fast, local copy of recent customer activity, and the shops quietly keep each other’s copies in sync in the background. Keycloak faces a very similar problem once it’s running across multiple servers at once, and its answer is a technology called Infinispan — a distributed, in-memory data grid that keeps frequently needed information fast to read, without every single request having to go all the way back to the database.

1What Is Infinispan, Really?

Before diving into Keycloak specifics, let’s fix the plain-English idea in place.

Infinispan is an open-source, distributed, in-memory data grid — essentially a very capable caching system that can spread data across multiple servers, keep copies synchronized, and survive individual servers failing without losing everything. Keycloak embeds Infinispan directly and uses it as the backbone for almost everything that needs to be read constantly and updated frequently during normal operation: active login sessions, realm configuration, user lookups, and more.

Without a technology like Infinispan, every single request Keycloak handles — checking whether a session is still valid, looking up a realm’s settings, verifying a client’s configuration — would need to hit the relational database directly, every time. At any real scale, that would make Keycloak slow and put enormous pressure on the database. Infinispan exists to keep that hot, frequently accessed data close at hand, in memory, right where Keycloak needs it.

Simple Analogy

Think of Infinispan as a shared whiteboard hanging in the break room of several branch offices at once. Instead of every employee calling head office to check today’s schedule, they glance at the whiteboard — and whenever head office updates it, all the branch whiteboards get updated too, kept in sync without anyone re-checking the master copy for every little question.

i
Where the name comes from

Infinispan is a general-purpose project used well beyond Keycloak, but Keycloak has embedded and configured it specifically to serve as its own internal caching and clustering layer.

2Why Keycloak Needs a Distributed Cache

The need for Infinispan becomes obvious once Keycloak runs on more than one machine.

A single Keycloak instance could, in principle, just keep its hot data in a plain, local in-memory map. But real production deployments almost always run several Keycloak nodes behind a load balancer, both for capacity and for resilience against any one node failing. That introduces a hard problem: a user might log in through node A, then have their very next request land on node B. If node B has no idea that user’s session exists, the whole system breaks.

Infinispan solves exactly this. Rather than each node keeping an isolated, local cache, Infinispan lets Keycloak nodes form a cluster and share cache data — so a session created on node A is visible, quickly, to node B as well. This is what makes a load-balanced, multi-node Keycloak deployment behave, from the outside, like one single, consistent system.

The core problem it solves

“How do multiple Keycloak servers, running independently, all agree on the same up-to-date picture of active sessions and configuration, without constantly hammering the database?”

3Local Cache vs. Distributed Cache vs. Database

Keycloak actually leans on all three of these, each for a different purpose.

Storage LayerSpeedShared Across Nodes?Survives Restart?
Local (per-node) cacheFastestNoNo
Infinispan distributed cacheFastYes, replicated across the clusterTypically no, unless persistence is layered on top
Relational databaseSlowestYes, single source of truthYes

Keycloak’s general pattern is to treat the database as the ultimate source of truth for anything that must survive a restart, while using Infinispan as the fast, shared layer for data that’s read constantly but doesn’t necessarily need permanent storage — with a notable, deliberate exception discussed shortly.

!
Common Misconception

Infinispan is not simply “Keycloak’s database.” It’s a caching and clustering layer that sits alongside the database, not a replacement for it.

4The Caches Keycloak Actually Uses

Keycloak doesn’t use just one big cache — it defines several, each dedicated to a specific kind of data.

Config Data

realms, users, authorization

Caches holding frequently read configuration and metadata — realm settings, user records, and authorization policy data — to avoid re-querying the database on every request.

Session Data

sessions, clientSessions

Caches holding active user sessions and client sessions, shared across the cluster so any node can serve a request tied to an existing login.

Offline Data

offlineSessions, offlineClientSessions

Caches that work alongside the database-persisted offline session records, providing fast access on top of that durable storage.

Security Data

loginFailures, actionTokens

Caches tracking failed login attempts (used for brute-force detection) and short-lived action tokens used in flows like email verification and password reset.

Splitting responsibilities this way lets Keycloak tune each cache’s behavior — how it replicates, how long entries live — independently, based on how that particular kind of data is actually used.

5Local Caches vs. Clustered Caches

Not every Infinispan cache in Keycloak behaves the same way — some are local, some are truly distributed.

Some caches, like the ones holding realm and user configuration, are primarily local to each node for maximum read speed, but Keycloak uses Infinispan’s clustering to invalidate those local caches across every node whenever the underlying data changes — so a configuration update made on one node quickly clears the stale, cached copy everywhere else. Other caches, particularly the session-related ones, are genuinely distributed, meaning the actual data itself, not just an invalidation signal, is shared and replicated across nodes.

flowchart TD
    subgraph Node A
        LA["Local Cache Copy"]
    end
    subgraph Node B
        LB["Local Cache Copy"]
    end
    Admin["Admin updates a realm setting on Node A"] --> LA
    LA -->|Invalidation message via Infinispan| LB
    LB --> Fresh["Node B fetches fresh data
from the database on next read"]
FIG 1 — For configuration data, Infinispan often synchronizes freshness through invalidation signals rather than replicating every value everywhere.

6Embedded vs. Remote Infinispan

Keycloak can run Infinispan in more than one topology, depending on deployment needs.

Embedded Infinispan (Default)

  • Runs directly inside each Keycloak server process
  • Keycloak nodes discover and cluster with each other directly
  • Simplest to set up for typical deployments

Remote / External Data Grid

  • Runs as a separate Infinispan (or Data Grid) cluster outside the Keycloak processes
  • Keycloak nodes connect to it as clients rather than embedding it directly
  • Useful for very large deployments or when caching infrastructure needs to be managed independently
i
Practical Tip

Most Keycloak deployments run comfortably with the default embedded mode; moving to a fully external caching layer is typically reserved for large-scale or highly specialized infrastructure requirements.

7How Nodes Find and Trust Each Other

Clustering only works if nodes can actually discover one another — that’s handled by a companion technology called JGroups.

Underneath Infinispan’s clustering sits JGroups, a toolkit for reliable group communication between servers. JGroups is responsible for the mechanics of forming a cluster: nodes discovering each other (through various discovery mechanisms depending on the environment, such as Kubernetes-aware discovery or a shared database ping table), joining the group, and reliably exchanging messages once connected.

Why this layered design matters

Separating “how do nodes find each other and talk reliably” (JGroups) from “what do we do with that connection once established” (Infinispan’s caching logic) lets each piece be swapped or tuned independently for different environments, like traditional VMs versus container orchestration platforms.

8Data Flow: A Session Read and Write

Tracing a concrete example makes the whole picture click into place.

sequenceDiagram
    participant U as User
    participant LB as Load Balancer
    participant N1 as Keycloak Node 1
    participant N2 as Keycloak Node 2
    participant IC as Infinispan Session Cache

    U->>LB: Login request
    LB->>N1: Routed to Node 1
    N1->>IC: Write new session
    IC->>IC: Replicate across cluster
    N1-->>U: Login successful

    U->>LB: Next request
    LB->>N2: Routed to Node 2 this time
    N2->>IC: Look up session
    IC-->>N2: Session found (replicated from Node 1)
    N2-->>U: Request served normally
        
FIG 2 — Because the session lives in the shared Infinispan cache rather than only on Node 1’s local memory, Node 2 can serve the very next request correctly.

9Cache Data vs. Persisted Data

Not everything Infinispan touches lives only in memory — offline sessions are the clearest example of the exception.

Regular user and client sessions live primarily within Infinispan’s in-memory cache, which is fast but, by itself, doesn’t guarantee the data survives a full cluster restart. Offline sessions, by contrast, are deliberately written straight into the relational database from the moment they’re created, precisely because they’re meant to survive far beyond typical session lifetimes — including through restarts, upgrades, and node failures.

Cache
regular sessions live here
DB
offline sessions live here
Both
used together for durability + speed
i
Connecting the Dots

This is the same distinction that explains why offline tokens survive a full Keycloak cluster restart while a regular login session generally does not — it comes down to which storage layer each one actually lives in.

10Cross-Datacenter Replication

For organizations running Keycloak across multiple physical sites, Infinispan’s reach can extend even further.

Larger deployments sometimes run Keycloak across two or more geographically separate datacenters for resilience or performance reasons. Infinispan supports cross-datacenter replication modes that let session and cache data be synchronized not just across nodes within one site, but across entire sites — so a user’s session created in one datacenter can, depending on configuration, remain usable if traffic is routed to another.

Why this is a specialized setup

Cross-datacenter replication adds real architectural complexity and network considerations, so it’s typically reserved for organizations with strict multi-site availability requirements, rather than a default recommendation for most deployments.

Because Infinispan sits on the critical path of nearly every Keycloak request, its configuration has a real, measurable effect on performance.

Cluster Size

Node Count and Topology

More nodes generally increase capacity but also increase the coordination overhead for cache replication — a balance worth tuning deliberately.

Network

Low-Latency Networking Between Nodes

Since cluster members constantly exchange cache updates, high latency or unreliable networking between nodes directly slows down the whole system.

Cache Sizing

Memory Allocation

Session-heavy deployments need enough memory allocated for Infinispan’s caches to avoid excessive eviction, which would force more frequent, slower database lookups.

“A Keycloak cluster is only as fast and consistent as the caching layer holding it together — Infinispan’s health is Keycloak’s health.”

12Security Considerations

Because Infinispan carries session and identity-related data across the network between nodes, it deserves its own security attention.

Network Isolation

Restrict cluster traffic

Inter-node Infinispan and JGroups traffic should be confined to a trusted internal network, not exposed to the public internet.

Encryption

Encrypt cluster communication where required

In environments with strict data-in-transit requirements, cluster communication channels should be encrypted, not just isolated by network segmentation.

Access Control

Protect any external Data Grid deployment

If running Infinispan or Data Grid externally rather than embedded, that infrastructure needs its own access controls, since it now holds sensitive session data outside the Keycloak process boundary.

13Advantages, Disadvantages & Trade-offs

Infinispan solves a real scaling problem, but it does add its own layer of operational complexity.

Advantages

  • Enables truly clustered Keycloak deployments with consistent session visibility across nodes
  • Dramatically reduces database load for frequently accessed data
  • Supports both local invalidation and full data replication patterns as appropriate
  • Extensible to cross-datacenter setups for organizations that need them

Disadvantages / Trade-offs

  • Adds a genuinely complex distributed-systems component under the hood
  • Cluster networking issues can manifest as confusing, hard-to-diagnose Keycloak symptoms
  • Requires careful capacity planning, since cache memory usage grows with active sessions
  • Cross-datacenter configurations meaningfully raise operational complexity further

14Design Patterns & Anti-Patterns

A few recurring habits distinguish healthy Keycloak clusters from troubled ones.

Pattern: Treat Cluster Networking as First-Class Infrastructure

Give the network path between Keycloak nodes the same reliability attention as the path to the database, since Infinispan depends on it just as heavily.

Pattern: Size Caches for Real Session Volume

Base memory and cache sizing decisions on realistic estimates of concurrent active sessions, rather than defaults meant for small test deployments.

ANTI-PATTERN-01 Avoid
Problem

Running multiple Keycloak nodes behind a load balancer without verifying that they’ve actually formed a proper Infinispan cluster together.

Why It’s Harmful

Nodes that fail to cluster correctly behave like isolated islands — a session created on one node may appear invalid or missing when a later request lands on another, causing confusing, intermittent login problems.

Correct Approach

Explicitly verify cluster formation and health as part of deployment validation, not just assume it’s working because each individual node starts successfully.

15Best Practices & Common Mistakes

A short, practical checklist for teams running Keycloak across more than one node.

1

Confirm cluster discovery works in your environment

Choose and validate the right discovery mechanism for your infrastructure — traditional networking, cloud environments, and container platforms each have their own considerations.

2

Monitor cluster membership, not just individual node health

A healthy-looking individual node that has silently fallen out of the cluster is a common and easy-to-miss failure mode.

3

Plan capacity around session volume, not just request rate

Cache memory needs scale with how many sessions are simultaneously active, which doesn’t always track directly with raw request throughput.

4

Test failover deliberately

Simulate a node going down to confirm sessions remain available on the remaining nodes, rather than discovering gaps during a real incident.

!
Common Mistake

Assuming that because Infinispan is embedded and starts automatically, no further attention to clustering configuration is needed — in real multi-node deployments, network and discovery configuration still require deliberate setup.

16Real-World Use Cases

Infinispan’s role becomes visible wherever Keycloak needs to scale beyond a single server.

High Availability

Multi-Node Production Clusters

Organizations running Keycloak for critical applications rely on Infinispan to keep sessions consistent across several nodes for resilience against individual server failures.

High Traffic

Large-Scale Consumer Login

Applications with heavy login volume depend on Infinispan’s caching to keep response times fast without overwhelming the underlying database.

Global Deployments

Multi-Region Availability

Organizations operating across multiple regions or datacenters can use Infinispan’s cross-datacenter replication capabilities to extend session consistency across sites.

17Monitoring, Logging & Metrics

Because Infinispan underlies so much of Keycloak’s behavior, keeping an eye on it is essential operational practice.

Track cluster membership and node count

Sudden, unexpected changes in cluster size often point to networking issues or node failures worth investigating immediately.

Watch cache hit and miss rates

A rising miss rate for caches like realms or users can indicate memory pressure or configuration issues causing excessive database fallback.

Monitor cache memory usage

Since session data scales with active user load, watching memory consumption trends helps anticipate capacity needs before they become incidents.

18Frequently Asked Questions

Q1Is Infinispan a separate product a team has to install on its own?

In its default, embedded mode, no — it’s bundled directly inside Keycloak. A separate, external Infinispan or Data Grid deployment is only needed for more advanced topologies.

Q2Does losing the entire Infinispan cluster mean all data is lost forever?

Not necessarily. Configuration data can be reloaded from the database, and offline sessions specifically are persisted there as well. Regular, in-memory-only session data, however, would need users to log in again.

Q3Is JGroups the same thing as Infinispan?

No. JGroups handles the underlying cluster communication and node discovery, while Infinispan builds its distributed caching functionality on top of that communication layer.

Q4Do single-node Keycloak deployments still use Infinispan?

Yes. Even a single node uses Infinispan’s local caching capabilities, just without the clustering and replication behavior that only becomes relevant once multiple nodes are involved.

Q5Can Infinispan be replaced with a different caching technology in Keycloak?

Infinispan is deeply integrated into Keycloak’s architecture as its caching and clustering layer, so it isn’t treated as a casually swappable component in typical deployments.

Q6Why do some caches only invalidate rather than replicate full data?

For data that’s read far more often than it changes, like realm configuration, it’s often more efficient to keep a fast local copy per node and simply signal “this is now stale” across the cluster, rather than constantly pushing the full data everywhere.

19Summary and Key Takeaways

Infinispan is the distributed, in-memory data grid Keycloak embeds to keep frequently accessed data — sessions, realm configuration, user records — fast to read and consistent across a cluster of servers. Working alongside JGroups for cluster communication, and complemented by the database for anything that genuinely needs to survive restarts, Infinispan is what allows a load-balanced group of Keycloak nodes to behave, from a user’s point of view, like one single, coherent system. Getting the most out of it means treating cluster networking, memory sizing, and cache health as real, ongoing operational concerns — not a detail that takes care of itself once the servers are running.

Key Takeaways

  • It’s the shared caching and clustering layer — embedded directly inside Keycloak by default.
  • It solves the multi-node consistency problem — letting any node in a cluster serve a request tied to a session created on another.
  • Different caches behave differently — some replicate full data, others simply invalidate stale local copies.
  • JGroups handles cluster communication — Infinispan builds its caching behavior on top of it.
  • The database remains the ultimate source of truth — for anything that must survive a restart, like offline sessions.
  • Cluster health is an operational responsibility — networking, discovery, and capacity all need deliberate attention.
  • It scales further when needed — supporting external Data Grid deployments and cross-datacenter replication for advanced use cases.