Running Keycloak in High Availability on Kubernetes (with Istio)
A step-by-step guide to running Keycloak 26 in HA on Kubernetes with the keycloakx Helm chart and Istio, including how to prove the pods clustered and a live failover test.
A single Keycloak pod is a single point of failure for every app that logs in through it. When a node gets drained, an autoscaler consolidates nodes, or the pod gets OOM-killed, every login on the platform stops until the pod comes back. On a normal cluster that takes somewhere between 45 seconds and three minutes, and for those minutes nobody can sign in.
Most of the fix is one line in your Helm values, and people usually assume it’s harder than that.
Many teams think Keycloak HA means running an external Infinispan cluster, a Redis layer, or some sidecar that syncs sessions. Modern Keycloak needs none of that. It ships with an embedded Infinispan cache that clusters itself, and it uses the database you already have to find its peers. You raise the replica count, make sure the pods can reach each other, and confirm they formed a cluster.
This tutorial walks through the whole setup from start to finish: Postgres, Keycloak with the keycloakx Helm chart, Istio in front, and a failover test where you kill a pod while traffic is flowing. I ran this exact setup on an EKS cluster running Kubernetes 1.35, Istio 1.22, and Keycloak 26.7.0. The log lines in this article come from that cluster.
Everything below uses plain, upstream Keycloak. No custom themes, no provider JARs, no custom SPIs. I’ll come back to that at the end, because those are where HA tends to break.
What you need before you start
- A Kubernetes cluster with nodes in more than one availability zone. This tutorial needs at least two nodes.
- Istio already installed, with an
istio-ingressgatewayrunning inistio-system. This tutorial does not cover installing Istio. kubectlandhelm(v3) on your machine.- A DNS name you control, such as
auth.example.com, pointed at the Istio ingress gateway’s load balancer. - A TLS certificate for that name, stored as a Kubernetes secret in
istio-system. cert-manager works fine for this.
Throughout this guide I use the namespace keycloak and the hostname auth.example.com. Change both to fit your setup.
Which Keycloak version you need
The version matters more than people expect. These are the releases that changed how clustering works:
| Keycloak version | What changed for HA |
|---|---|
| 17+ | Quarkus-based distribution. Configuration moved to KC_* env vars and kc.sh options. Anything older (WildFly) is a different product, so don’t bother. |
| 26.0 | Persistent user sessions turned on by default. User sessions are written to the database, not just held in memory. |
| 26.1 | jdbc-ping became the default cache stack. Nodes discover each other through a table in the Keycloak database. Before this, the default was UDP multicast, which most cloud VPCs block. |
| 26.x (recent) | JGroups traffic between nodes is encrypted with mTLS by default on TCP stacks. Keycloak manages the certificates itself. |
My recommendation: run Keycloak 26.2 or later, and ideally the latest 26.x. I tested on 26.7.0. On those versions, clustering works with zero JGroups configuration from you.
If you’re stuck on something older than 26.1, you can still cluster, but you have to choose a discovery stack yourself (usually kubernetes, which uses DNS_PING against a headless Service). Upgrading is the better use of your time.
How Keycloak HA actually works
There are three layers, and you need to know what each one does.
1. Traffic layer. Istio’s ingress gateway terminates TLS and sends requests to a Kubernetes Service. The Service spreads them across all ready Keycloak pods. Any pod can handle any request.
2. Cache layer. Each Keycloak pod runs an embedded Infinispan cache. The pods join into one cluster over JGroups on TCP port 7800, and use port 57800 for failure detection. The cluster shares things like authentication sessions (a login that’s halfway through), action tokens, brute-force counters, and invalidation messages for realm and user data. Distributed caches keep two copies of each entry by default, so losing one pod loses no cache data.
3. Discovery and storage layer. That is Postgres. When a pod starts, it writes its address into a JGROUPS_PING table and reads the addresses of the other pods from the same table. That is how they find each other. No Kubernetes API permissions, no multicast, no extra service. The same database also stores realms, users, clients, and, since 26.0, user sessions.
The third layer is what makes HA easy now. Because user sessions sit in the database, a user who is logged in stays logged in even if the pod that handled their login is gone. Because discovery uses the database, any two pods that can reach the same Postgres and reach each other on port 7800 will form a cluster.
Step 1: Create the namespace and secrets
kubectl create namespace keycloak
Should you inject the Istio sidecar into the Keycloak namespace? You don’t have to. The ingress gateway can route to pods without sidecars. If your mesh policy requires sidecars everywhere, label the namespace:
# Optional: only if you want sidecars on Keycloak pods
kubectl label namespace keycloak istio-injection=enabled
I’ll cover what the sidecar changes in Step 3.
Next, create two secrets: one for the database password and one for the first admin user.
kubectl -n keycloak create secret generic keycloak-db \
--from-literal=password="$(openssl rand -base64 24)"
kubectl -n keycloak create secret generic keycloak-admin \
--from-literal=password="$(openssl rand -base64 24)"
Step 2: Get a Postgres database
Use a managed database for anything real, such as RDS, Cloud SQL, or Azure Database for PostgreSQL, with Multi-AZ turned on. If Postgres goes down, Keycloak goes down with it, no matter how many replicas you run. Running two Keycloak pods doesn’t help if they both depend on one database that can fail.
For a lab, a single in-cluster Postgres is enough to follow along:
# postgres.yaml (LAB ONLY: single instance, not HA)
apiVersion: v1
kind: Service
metadata:
name: keycloak-db
namespace: keycloak
spec:
selector:
app: keycloak-db
ports:
- name: tcp-postgres
port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: keycloak-db
namespace: keycloak
spec:
serviceName: keycloak-db
replicas: 1
selector:
matchLabels:
app: keycloak-db
template:
metadata:
labels:
app: keycloak-db
spec:
containers:
- name: postgres
image: postgres:16
env:
- name: POSTGRES_DB
value: keycloak
- name: POSTGRES_USER
value: keycloak
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: keycloak-db
key: password
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 5Gi
kubectl apply -f postgres.yaml
kubectl -n keycloak rollout status statefulset/keycloak-db
If you use a managed database instead, create the keycloak database and user there, and put its hostname in the values file in the next step.
Step 3: Write the Helm values
I use the community keycloakx chart from codecentric (version 7.2.2 at the time of writing). It’s a thin wrapper around the official Keycloak image, and its defaults are already good for HA. Out of the box it:
- Sets
KC_CACHE=ispnandKC_CACHE_STACK=jdbc-ping, so pods cluster through the database. - Adds a required pod anti-affinity per node, so two Keycloak pods never land on the same node.
- Adds a preferred pod anti-affinity per zone.
- Wires readiness, liveness, and startup probes to Keycloak’s
/healthendpoints on the management port (9000).
Here is the whole values file. I’ll explain each part below.
# keycloak-values.yaml
fullnameOverride: keycloak
# This is the HA change.
replicas: 2
image:
tag: "26.7.0"
# Production mode. Do NOT use start-dev for anything clustered.
command:
- "/opt/keycloak/bin/kc.sh"
args:
- "start"
# Keycloak 17+ serves from "/", not "/auth".
http:
relativePath: "/"
# Istio terminates TLS and sends X-Forwarded-* headers.
proxy:
enabled: true
mode: xforwarded
http:
enabled: true
database:
vendor: postgres
hostname: keycloak-db.keycloak.svc.cluster.local
port: 5432
database: keycloak
username: keycloak
existingSecret: keycloak-db
existingSecretKey: password
# "default" = KC_CACHE=ispn + KC_CACHE_STACK=jdbc-ping
cache:
stack: default
extraEnv: |
- name: KC_HOSTNAME
value: "https://auth.example.com"
- name: KC_BOOTSTRAP_ADMIN_USERNAME
value: "admin"
- name: KC_BOOTSTRAP_ADMIN_PASSWORD
valueFrom:
secretKeyRef:
name: keycloak-admin
key: password
# Never voluntarily evict more than one pod at a time.
podDisruptionBudget:
maxUnavailable: 1
# Keep pod-to-pod JGroups traffic out of the Istio sidecar.
# Harmless if there is no sidecar.
podAnnotations:
traffic.sidecar.istio.io/excludeInboundPorts: "7800,57800"
traffic.sidecar.istio.io/excludeOutboundPorts: "7800,57800"
# Spread pods across zones, not just nodes.
topologySpreadConstraints: |
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
{{- include "keycloak.selectorLabels" . | nindent 6 }}
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
memory: 1Gi
Here’s why each part is there.
replicas: 2. This is the change that makes it HA, and the key name matters. The chart reads replicas, not replicaCount. If you wrap keycloakx in your own umbrella chart and copy a replicaCount key from some other chart’s template, Helm will ignore it without any warning and you’ll keep running one pod. I’ve seen this happen. Run helm template and check the StatefulSet before you trust it.
args: ["start"], not start-dev. The Keycloak docs say start-dev turns off distributed caches by setting --cache=local. The keycloakx chart sets KC_CACHE=ispn as an env var, and I’ve seen pods running start-dev with that env var still form a cluster. Don’t rely on it. Dev mode also turns off other production safeguards. Use start.
proxy.mode: xforwarded and KC_HOSTNAME. The Istio gateway handles TLS and passes X-Forwarded-Proto and X-Forwarded-For to Keycloak. Keycloak needs to trust those headers, or it will build http:// redirect URLs and logins will fail. Setting KC_HOSTNAME to the full public URL (hostname v2, Keycloak 25+) pins the issuer so every pod produces identical tokens. Don’t use the old KC_PROXY=edge setting. It’s a hostname v1 option, and Keycloak 26 prints a warning at startup if it’s still there.
podDisruptionBudget. Node drains, cluster upgrades, and autoscaler consolidation are voluntary evictions. A PDB with maxUnavailable: 1 makes Kubernetes evict one Keycloak pod, wait for the replacement to become ready, and only then evict the next. Without a PDB, a drain can take out both pods at once and you’re back to having no HA. If you run Karpenter, you can also add karpenter.sh/do-not-disrupt: "true" to podAnnotations so consolidation skips these pods entirely.
The Istio port exclusions. If a sidecar is injected, it intercepts all pod traffic by default, including JGroups. JGroups already does its own mTLS, so it doesn’t need Istio’s. Having the sidecar in the middle of a raw TCP protocol that connects straight to pod IPs is a known way to get nodes that never join or that keep dropping out of the cluster. Excluding 7800 and 57800 lets the pods talk directly. If there’s no sidecar, the annotations do nothing.
topologySpreadConstraints. The chart’s per-zone anti-affinity is only preferred. On my cluster both pods ended up in the same zone anyway, because the scheduler found room there first. Anti-affinity per node protects you from a node failure. It doesn’t protect you from a zone failure. DoNotSchedule makes the zone spread mandatory. If your cluster can’t always place a pod in a second zone, switch it to ScheduleAnyway and accept the risk.
Render the chart before you install it:
helm repo add codecentric https://codecentric.github.io/helm-charts
helm repo update
helm template keycloak codecentric/keycloakx --version 7.2.2 \
-n keycloak -f keycloak-values.yaml \
| grep -E "kind:|replicas:|KC_CACHE|maxUnavailable|excludeInbound"
You should see replicas: 2, KC_CACHE and KC_CACHE_STACK, a PodDisruptionBudget with maxUnavailable: 1, and the sidecar annotations. If replicas shows 1, fix the values before you go on.
Step 4: Install Keycloak
helm upgrade --install keycloak codecentric/keycloakx \
--version 7.2.2 \
-n keycloak \
-f keycloak-values.yaml
The chart creates a StatefulSet with podManagementPolicy: OrderedReady, so keycloak-0 has to be ready before keycloak-1 starts. On the first start, keycloak-0 also creates the database schema. Starting one pod at a time keeps two pods from running the schema migration at once.
kubectl -n keycloak get pods -o wide -w
Wait until both pods show 1/1 Running. Plain kc.sh start runs a build step on every boot, so expect 40 to 60 seconds per pod. Then check that they landed on different nodes and zones:
kubectl -n keycloak get pods -l app.kubernetes.io/name=keycloakx \
-o custom-columns=POD:.metadata.name,NODE:.spec.nodeName --no-headers \
| while read pod node; do
echo "$pod $node $(kubectl get node "$node" -o jsonpath='{.metadata.labels.topology\.kubernetes\.io/zone}')"
done
Step 5: Prove the pods formed a cluster
Two running pods don’t prove you have HA. If they never joined into one cluster, you have two separate Keycloaks that share a database but not their caches. Logins that start on one pod and finish on the other will fail in confusing ways.
Check the logs for the cluster view:
kubectl -n keycloak logs keycloak-0 | grep -E "JDBC_PING|Encryption|ISPN000094"
On a healthy cluster you’ll see something like this (trimmed from my cluster):
JGroups JDBC_PING discovery enabled.
JGroups Encryption enabled (mTLS).
ISPN000078: Starting JGroups channel `ISPN` with stack `jdbc-ping`
ISPN000094: Received new cluster view for channel ISPN: [keycloak-1-53732|3] (2) [keycloak-1-53732, keycloak-0-51671]
The (2) is the number to look for. It’s the cluster size. It should match your replica count. If each pod reports (1), they’re running alone. Skip ahead to the troubleshooting section.
You can also look at the discovery table directly. In the lab Postgres:
kubectl -n keycloak exec -it keycloak-db-0 -- \
psql -U keycloak -d keycloak -c '\dt *ping*'
kubectl -n keycloak exec -it keycloak-db-0 -- \
psql -U keycloak -d keycloak -c 'SELECT * FROM jgroups_ping;'
There should be one row per live pod, each with that pod’s IP and port 7800.
Step 6: Put Istio in front
Istio is already running, so you only need a Gateway to accept traffic for your hostname and a VirtualService to send it to Keycloak.
# istio.yaml
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
name: keycloak
namespace: keycloak
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 443
name: https
protocol: HTTPS
hosts:
- auth.example.com
tls:
mode: SIMPLE
credentialName: auth-example-com-tls # secret in istio-system
- port:
number: 80
name: http
protocol: HTTP
hosts:
- auth.example.com
tls:
httpsRedirect: true
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: keycloak
namespace: keycloak
spec:
hosts:
- auth.example.com
gateways:
- keycloak
http:
- route:
- destination:
host: keycloak-http.keycloak.svc.cluster.local
port:
number: 80
kubectl apply -f istio.yaml
Point at the keycloak-http Service on port 80. Don’t use the keycloak-headless Service, and don’t route to individual pods. The regular Service only includes pods that pass the readiness probe, and that’s what keeps traffic off a pod that’s still starting or already shutting down.
Note that the keycloak-http Service also exposes port 9000, the management port with /health and /metrics. The VirtualService above only routes to port 80, so the management endpoints stay internal. Keep it that way.
Optional: sticky sessions
You don’t need sticky sessions. The cluster shares authentication sessions, so a login can start on one pod and finish on the other. Keycloak does recommend stickiness for performance, though: if the same pod handles every step of a login, it doesn’t have to fetch session data from the other pod. With Istio that’s a DestinationRule that hashes on Keycloak’s auth session cookie:
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: keycloak
namespace: keycloak
spec:
host: keycloak-http.keycloak.svc.cluster.local
trafficPolicy:
loadBalancer:
consistentHash:
httpCookie:
name: AUTH_SESSION_ID
ttl: 0s
Start without it. Add it only if you measure a reason to.
Open https://auth.example.com/admin and log in as admin with the password from the keycloak-admin secret:
kubectl -n keycloak get secret keycloak-admin -o jsonpath='{.data.password}' | base64 -d; echo
Step 7: Break it on purpose
Until you’ve killed a pod and watched what happens, you don’t know whether the setup is HA. Run these three tests.
Test 1: Kill a pod during live traffic
In one terminal, request a token from the admin-cli client twice a second and print the HTTP status:
ADMIN_PW=$(kubectl -n keycloak get secret keycloak-admin -o jsonpath='{.data.password}' | base64 -d)
while true; do
code=$(curl -s -o /dev/null -w '%{http_code}' \
-X POST https://auth.example.com/realms/master/protocol/openid-connect/token \
-d grant_type=password -d client_id=admin-cli \
-d username=admin --data-urlencode "password=$ADMIN_PW")
echo "$(date +%T) $code"
sleep 0.5
done
In a second terminal, delete one pod:
kubectl -n keycloak delete pod keycloak-0
The first terminal should keep printing 200. You might see one failed request right when the pod dies, if a request was already in flight to it. Istio’s default retry policy usually covers that. After that the Service stops sending traffic to the pod and everything goes to keycloak-1.
In a third terminal, follow the surviving pod’s logs:
kubectl -n keycloak logs -f keycloak-1 | grep -E "ISPN000094|ISPN100001"
Here’s what that looked like on my cluster:
10:32:44 ISPN000094: Received new cluster view ... (2) [keycloak-0-23381, keycloak-1-53732]
10:32:54 ISPN000094: Received new cluster view ... (1) [keycloak-1-53732]
10:32:54 ISPN100001: Node keycloak-0-23381 left the cluster
10:35:54 ISPN000094: Received new cluster view ... (2) [keycloak-1-53732, keycloak-0-51671]
keycloak-0 left, keycloak-1 kept serving as a one-node cluster, and the new keycloak-0 rejoined three minutes later (most of that was pulling images onto a fresh node). In that window nobody lost the ability to log in.
You may also see a failed sending graceful close ... Broken pipe error from JGroups right when the new pod joins. It’s the old pod’s connection being torn down, and it’s harmless.
Test 2: Stay logged in while a pod restarts
- Log in to the admin console in your browser.
- Delete
keycloak-1. - Click around the console and refresh the page.
You should still be logged in. Your session didn’t depend on the pod that created it.
Test 3: Do a rolling restart
This is the test that matches real life, because it’s what happens on every config change, image upgrade, and node rotation:
kubectl -n keycloak rollout restart statefulset/keycloak
kubectl -n keycloak rollout status statefulset/keycloak
Keep the curl loop running. The StatefulSet replaces pods one at a time, in reverse order, and waits for each new pod to pass its readiness probe before it moves on. You should see 200 the whole time.
Here’s the part that surprises people: after the restart, both pods have been replaced, and your browser session from Test 2 still works. That’s persistent user sessions (Keycloak 26.0+). The session was in Postgres the whole time.
When the pods don’t cluster
If each pod reports a cluster view of (1), check these in order:
- Can the pods reach each other on 7800 and 57800? A
NetworkPolicythat only allows traffic on 8080 will block JGroups. Allow pod-to-pod traffic on both ports inside the namespace. - Is the Istio sidecar intercepting JGroups? Check that the exclusion annotations are on the pods themselves:
kubectl -n keycloak get pod keycloak-0 -o jsonpath='{.metadata.annotations}'. - Is the cache set to local? Look for
KC_CACHE=ispnin the pod env, and check that the args saystart, notstart-dev. - Are both pods using the same database and schema? Discovery happens through the database. Two pods pointing at different schemas will never see each other.
- Are the Keycloak versions mixed? Nodes on different versions shouldn’t share a cluster. For patch upgrades, recent 26.x releases include
kc.sh update-compatibilityto tell you whether a rolling update is safe. For anything bigger, plan for a full restart.
How many replicas?
Two is the minimum for HA, and it’s what I ran here. It survives one pod failing, one node draining, or one zone going down (if you enforced the zone spread).
Three is better for production. During a rolling restart one pod is always out, so with two replicas you’re running on a single pod for a minute or so on every deploy. With three you still have redundancy during the rollout.
Don’t start with the HPA. Keycloak pods take close to a minute to start and then have to rebalance caches with the cluster. That’s a poor fit for fast autoscaling. Pick a fixed number based on your login traffic and leave it.
A word on themes, JARs, and custom extensions
Everything in this tutorial uses plain Keycloak. Real deployments often aren’t plain. They have custom login themes, provider JARs in /opt/keycloak/providers, custom authenticators, event listeners, and protocol mappers.
Those can work fine with HA, but you need to have developers check each one before you call the setup HA. These are the things that break:
- State kept in JVM memory. An extension that caches data in a static map or a local field now has two copies that don’t know about each other. Pod A updates its copy, and pod B keeps serving stale data.
- Event listeners run on every node. An event listener that publishes to Kafka or calls a webhook will run on whichever pod handled the event. Check that nothing downstream assumes there’s only one sender.
- Scheduled tasks. A custom task scheduled inside Keycloak will run on every replica unless it’s coordinated through the cluster.
- Theme caching. If you turned off theme caching to make theme development easier, each pod renders themes on its own. That’s fine for correctness but costs performance. Turn caching back on in production.
- Internal SPIs. Keycloak logs a warning when an extension implements an internal SPI, since those can change in any release. HA doesn’t break them directly, but rolling upgrades put two versions next to each other for a short time, and that’s where hidden assumptions show up.
Run the three tests above with your extensions installed, then go through your real login flows (social login, MFA, password reset, anything custom) while you kill pods. If those still work, you’re done.
Checklist
- Keycloak 26.2 or later (I tested 26.7.0)
-
replicas: 2or more, confirmed withhelm template -
kc.sh start, notstart-dev - Managed, Multi-AZ Postgres
-
KC_HOSTNAMEset to the public URL, proxy headers set toxforwarded - PodDisruptionBudget with
maxUnavailable: 1 - Pods on different nodes and different zones
- JGroups ports 7800/57800 excluded from the Istio sidecar (if one is injected) and allowed by NetworkPolicy
- Logs show
ISPN000094 ... (N)where N equals your replica count - Pod-kill, session, and rolling-restart tests pass
- Custom themes and extensions checked by the dev team
Making Keycloak HA mostly comes down to setting replicas: 2 and then proving the pods actually formed a cluster. Most of this article is about the proving part.