Load testing Keycloak with Keycloak Benchmark before go-live
A team that has sized a Keycloak cluster needs evidence that it meets its login and token targets before users arrive. Keycloak Benchmark is the Gatling-based tool the Keycloak project provides for this purpose: it drives simulated load against a deployment you run, so you can measure throughput and latency rather than assume them. Keycloak is an Apache 2.0 licensed identity server, and the current release is 26.8.1, so the benchmark is aimed at the software you plan to run. It is not a substitute for vendor validation or for the sizing guide's published per-request figures, which it is meant to check against your own network, database, load balancer and node sizes.
The test is most useful when a team needs to confirm that expected interactive logins, token refreshes and client credentials grants per second can be served with the planned pod CPU, memory and database capacity. Before running it, decide which scenarios match your traffic mix, and prepare a dataset of realms, users and clients close to production volume, because a test against an empty realm measures very little. Ask your team to confirm the target percentiles and error rates in writing, and to confirm that the test environment mirrors production in database engine, version and placement, TLS termination and the reverse proxy path, since each of these changes the result.
Run the test with metrics enabled. Starting Keycloak with --metrics-enabled=true exposes Prometheus-format metrics at /metrics on the management interface, and the optional HTTP and cache histograms show where time goes during the run. Watch database connection pool usage and HTTP worker threads alongside CPU and memory, because pool exhaustion often appears as latency before it appears as errors. Read the results against the sizing assumptions rather than against a single pass or fail number, and plan a retest after each change so that the evidence you hand to reviewers matches the configuration you actually launch.
What Keycloak Benchmark covers
Login scenarios drive the authorization code flow with a username and password, create user sessions, issue tokens and, where the realm enforces them, complete a second factor. They are the most expensive requests per operation because they combine password hash verification, session creation and database writes for login events.
- Password hashing cost: Each login verifies a password hash, so the hashing algorithm and iteration settings in the realm's password policy change CPU use per login. Run with the production policy, not a lowered one for convenience.
- Session creation: Each new user session writes to the cache layer and may persist to the database, which is where cluster and database capacity usually show up first.
- Second factors: If the test flow includes OTP or another MFA step, the scenario adds work that a password-only run never exercises.
- Login failure recording: Keycloak 26.8 persists login failures to the database by default, so failed-login traffic adds write load that belongs in the test.
Confirm that the scenario follows the browser redirects your users make and that the test population matches the realm you will run in production. This scenario does not prove browser rendering, front-end asset delivery or the time a person spends entering credentials.
Once users are signed in, applications keep sessions alive by refreshing access tokens. APIs may validate tokens locally by checking signatures or call Keycloak for each request. Token and refresh scenarios measure how often the server issues and refreshes tokens, which for many applications happens far more often than fresh logins.
- Refresh frequency: The access token lifetime sets how often each session refreshes. Shorter lifetimes multiply refresh requests for the same user population, so test the lifetimes you plan to ship.
- Token signing: Issuing signed tokens uses CPU on each node, and the signing key type and algorithm affect that cost. Use the production configuration.
- Session state reads: Refresh requests read session and client state, which exercises the same cache and database paths that logins touch.
- Introspection calls: Token introspection sends each request back to Keycloak, a load pattern that differs from local signature checks. Test the validation method your applications actually use.
Compare the lifetimes and validation method in the test with the configuration your applications will run. This scenario does not prove how your APIs cache tokens, how long client libraries keep them or how a gateway in front of the APIs behaves.
Client credentials grants let services obtain tokens under their own identity without a user present. They produce steady, high-rate machine traffic, and in service-heavy estates they can account for most token requests. That makes this scenario the most likely to expose connection pool and worker thread limits.
- Client count: Each confidential client has its own credentials to verify. A large number of clients spreads work across more client records and cache entries than a few busy clients do.
- Burst patterns: Batch jobs and autoscaling services can request tokens at the same moment. Model the peak schedule, not only the average rate.
- Authentication method: Client authentication cost depends on whether services use a client secret, signed JWTs or another method. Test the method your services use.
- Connection pressure: High request rates with little idle time push the database pool and HTTP worker threads harder than interactive logins do.
Ask the platform team which services use client credentials, how often each one requests tokens and whether they cache tokens between calls. This scenario does not prove how the downstream APIs behave under the tokens they receive or how a service mesh handles retries.
A result holds only for the data volume it was produced with. Benchmark datasets set how many users, realms, clients and sessions the server holds during the run. Cache and database behavior change as those counts grow, so a run against a small dataset can look fast while the production realm performs very differently.
- User population: Size the test user count to production, including the share of users who sign in during the same window.
- Realm and client counts: Deployments with several realms or many clients place more entries in caches and more rows in the database.
- Existing sessions: Pre-populate sessions to match steady-state load, because session count drives memory use and cache size.
- Outside the test path: A run inside one network segment does not prove load balancer behavior, TLS termination, WAN latency or the speed of upstream identity providers. Test those paths separately.
Record the dataset numbers next to every result and compare them with the inputs you used in the sizing guide before accepting a pass. Ask the vendor or the project's documentation which dataset parameters the benchmark exposes, since the options available depend on the version you test.
Test options and when each fits
This table compares the main choices you make before a Keycloak Benchmark run: dataset size, scenario mix, injection profile and target environment. Read each row for the situation it suits and the cost it carries, then pick the combination that matches your go-live targets.
| Option | When it fits | Trade-off |
|---|---|---|
| Small dataset (few users, clients, realms) | Early functional tuning, quick checks after a configuration change, or validating a new scenario script | Cache and database behavior can differ from production, so results may overstate headroom |
| Production-scale dataset (users, clients, realms matching your estate) | Sign-off runs before go-live and sizing checks against the sizing guide | Longer data generation and database preparation, plus more storage and time to reset between runs |
| Password login scenario | Workforce or customer sign-in traffic is mostly username and password, and you need to measure hashing and session creation cost | Password hashing is CPU-heavy, so results depend on the hashing policy you configure |
| Authorization code with PKCE scenario | Browser and single-page app logins dominate your traffic, including redirects and consent | Needs realistic browser-style redirects and session handling, which takes more scenario work to script |
| Refresh token scenario | Long-lived sessions generate steady token refresh traffic that can outweigh new logins | Refresh rates depend on token lifetimes you set, so it must match your real lifetime configuration |
| Client credentials scenario | Services call Keycloak for tokens at high rates, such as API gateways or backend jobs | Stresses token issuance and client lookups but not user sessions, so it does not show login-path limits |
| Ramp injection profile | Finding the point where latency or error rate starts to climb, and checking cache warm-up | Takes longer to run, and the result shows a curve rather than a single steady-state figure |
| Constant rate or peak profile | Holding a known login or token rate to verify a target, or rehearsing a planned peak such as a launch or enrollment window | Only tells you about the rate you chose, so you must confirm that rate against your own traffic estimates |
| Staging mirror environment | Repeatable tuning runs, scenario development and comparing configuration changes | Infrastructure, database size and network paths may differ from production, so confirm the gaps before trusting absolute numbers |
| Production-like environment | Final verification of targets, including database, load balancer and network paths you will use at go-live | Higher cost to run and coordinate, and load can affect shared systems, so schedule runs in a controlled window |
How to set up a Keycloak Benchmark run
This sequence turns sizing targets into a repeatable load test against a production-like Keycloak, so the first measured run produces numbers you can compare with the sizing guide. Each step ends with a check that the test environment is observable before any load is applied.
Define targets from the sizing guide
The platform owner and the Keycloak lead translate expected peak logins, token refreshes and client credentials grants per second into explicit pass criteria, including response time percentiles, error rate and resource ceilings for CPU, memory and database connections. They confirm the per-request figures they are relying on against the Keycloak sizing guide and record the source of each number. Done when the targets sit in a written test plan that names the scenarios each target applies to and who signs off on the results.
Deploy a production-like Keycloak
The infrastructure team deploys Keycloak with the settings it will use in production: TLS on every connection, a reverse proxy with path restrictions, and the admin console and Administration REST API on a separate hostname or context path from public frontend URLs. The same database engine, node count, container limits and network path as the intended production design are used, because a test on a smaller shape only tells you about that shape. Done when a smoke login succeeds through the proxy and the admin endpoints are unreachable from the public hostname.
Enable and scrape metrics
The engineer starts Keycloak with --metrics-enabled=true, and configures the Prometheus server to scrape /metrics on the management interface, not on the public listener. Optional HTTP request and cache histograms are switched on before the test so their series exist in the baseline. Done when the scrape target shows as up and the dashboards display JVM, HTTP and database pool series for every node.
Load the synthetic dataset
The team creates the test realms, users, clients and credentials in a database that matches production in engine, version and sizing, and records the row counts and realm layout. Test users should reflect the real ratio of password, OTP and token-based accounts, and the dataset should be restored from a snapshot so every run starts from the same state. Done when the database row counts match the plan and a sample of generated users can log in through the proxy.
Clone and configure Keycloak Benchmark
The engineer clones the Keycloak Benchmark project from the Keycloak project's repository, sets the target hostname, realm names, client IDs and user ranges to match the dataset, and selects the login and token scenarios that map to the targets. Load injectors are placed in a network position that resembles real client traffic, and the Gatling run parameters are checked against the sizing assumptions. Done when a dry run with a single virtual user completes every selected scenario without assertion failures.
Confirm pool and CPU observability
Before any load is applied, the engineer confirms that the database connection pool usage, HTTP worker thread activity, CPU and memory for each Keycloak node, and database query latency all appear on the dashboards during a short warm-up. The team agrees which signals will stop a run, such as pool exhaustion or sustained CPU saturation. Done when every signal named in the test plan has a live series, because a run without visibility cannot explain its failures.
Run a baseline before stepping up
The team runs a baseline at a modest fraction of the target load, captures Gatling reports and the matching metrics for the same window, and saves them with the Keycloak version, configuration and dataset identifiers. The run is repeated once to confirm results are stable before load is increased in steps toward the target. Done when two consecutive baseline runs agree closely enough that the team accepts them as the reference for later comparison.
Why the test dataset decides whether results mean anything
A load test only proves something about the population it was run against. User count, client count, realm count, session volume and database size all change how Keycloak behaves under load: more users and sessions push data out of the Infinispan caches and into the database, and more clients and realms enlarge the configuration Keycloak must read on each request. A small seeded dataset keeps everything in memory, so a run can pass with latency and database load that a production population would never reproduce. Before the first run, write down the planned identity population for go-live and the growth you expect over the next budget cycle, then seed the test database to that scale, not to a convenient round number. Keycloak Benchmark's dataset tooling is the place to set those counts, and the Keycloak sizing guide's per-request figures only mean something when the dataset behind them matches your numbers.
Warm the caches before any measurement starts. A freshly restarted cluster has cold caches, so the first minutes of a run measure database reads that steady-state traffic would rarely make. Run a warm-up phase with the same scenario mix, confirm that cache and database query rates have leveled off in your observability dashboards, and only then start the recorded run. Confirm with your own environment how long the warm-up needs to be, since it depends on your user count and session lifetimes, and do not reuse one warm-up length across datasets of different sizes.
Record enough detail that the run can be repeated after a change. Keep the Keycloak version, the exact Keycloak Benchmark commit, the dataset parameters, the database engine and version, instance types, CPU and memory limits, pool settings, cache configuration and the feature flags in use. Save the raw Gatling reports alongside the Prometheus metrics for the same time window, so a later regression can be compared against a known baseline. Without this record, a result that looks better after a tuning change cannot be separated from a change in the dataset, the warm-up or the environment.
What to watch during a load test
A load test only proves a target when you can see where the system is strained. The signals below come from Keycloak, its cache layer, the database, the JVM and the load generator itself, and they should be read together during every run against the sizing targets.
Keycloak request and latency metrics
Start every run by enabling metrics with --metrics-enabled=true and scraping /metrics on the management interface. Track request rate, error responses and latency percentiles for the token and login endpoints, not just averages, because tail latency rises first when a node nears its limit. Confirm that the request histograms are enabled, since they are optional, so the figures you compare against the sizing guide come from the same counters.
Cache histograms and cache behavior
Cache metrics show whether logins and token refreshes are hitting the embedded Infinispan caches or falling through to the database. A falling hit ratio during a steady-state run means the test dataset is larger than the caches were sized for, or session data is spreading across nodes in a way the test does not reflect. Compare cache behavior between the first and last minutes of a run to catch warm-up effects that can hide a slow start.
Database connection pool usage
Watch active, idle and waiting connections in the Keycloak connection pool during the run. Pool exhaustion appears as rising request latency while database CPU stays low, which is easy to misread as a database problem. Check that the minimum, initial and maximum pool sizes are set to the same value as the team intended, and that the total across all nodes stays within the limits of the database server.
Database CPU and IOPS
Record database CPU, read and write IOPS, lock waits and commit latency on the same timeline as the Keycloak metrics. Session and event writes, including login failures persisted to the database by default in 26.8, can make the database the first limit under heavy login traffic. Ask your database team which of these counters the managed service exposes, because some platforms report IOPS only at coarser intervals.
JVM memory and garbage collection
Track heap usage, old-generation growth and garbage collection pause times for each Keycloak node. A heap that climbs across a run without settling, or long pauses that line up with latency spikes, points to memory sized too small for the caches or to a connection or session leak in the test pattern. Compare the pause pattern across nodes, since one node that collects more often usually carries more traffic than the others.
Load generator saturation
The machine running Gatling can be the bottleneck, and then the results describe the generator instead of Keycloak. Watch its CPU, memory, open sockets, ephemeral port usage and network throughput during the run. If the generator saturates while Keycloak metrics stay flat, the target has not been reached. Check the arrival rate the generator actually produced against the rate you configured, and add generator capacity or spread load across machines before reading the results.
How to read results against the Keycloak sizing guide
Read a Keycloak Benchmark run as a comparison against the per-request figures in the Keycloak sizing guide, not as a single pass or fail number. For each scenario you ran, line up the measured throughput (logins or token requests per second), the latency percentiles and the error rate against the target you set before the test. Then convert the measured rate into pod CPU and memory by scaling from the load the test pod count actually handled. A run that meets the target with the same pod count and database size you plan to use in production is the only kind that tells you something about go-live capacity. Record the pod count, Keycloak version, database instance class and test dataset size alongside every result so the numbers can be reproduced later.
A pass means the scenario held the target throughput with latency and errors inside the thresholds you agreed, and the CPU, memory and database connection use stayed below the headroom you chose, usually with room left for a node or zone failure. Confirm the headroom policy with your own SRE and capacity owners rather than taking a figure from a template. A failure points to a specific place: CPU saturation on pods suggests a need for more pods or a different sizing assumption, rising latency with idle CPU often means the database pool is exhausted or the database is the bottleneck, and errors at the load balancer can come from timeouts or connection limits. Use the Keycloak observability metrics at /metrics to see which of these it is before changing anything.
One run should not be the only go-live evidence. Repeat the scenarios at the planned peak, run a sustained soak long enough to surface memory growth and session accumulation, and rerun after each change to the Keycloak version, database, cache or pod sizing. Include a run that simulates losing a node or zone if your architecture is meant to survive that, because throughput under failure is what your availability target depends on. Ask your test partner or internal team to state in writing which runs are the acceptance evidence and which are exploratory, so the go-live decision rests on repeatable results.
Security and operational considerations for test environments
A load test creates real identities, sessions and traffic against systems that other people depend on. The cards below cover the data, access, third-party and cleanup risks that teams most often miss when they run Keycloak Benchmark, and what to confirm before each run starts.
Synthetic data only in the dataset
Keep production users, password hashes, client secrets and real email addresses out of the benchmark dataset. The benchmark generates its own realms, users and clients, so there is no reason to import a production export into the test cluster. Before each run, check that the test database has no federation link to a live directory and that the generated credentials are kept separate from anything used in production.
Admin endpoints kept off the test network
Load test traffic should reach the public login and token endpoints only, the same way it will in production. The admin console and Administration REST API should stay on their separate hostname or context path, reachable only from the machines running the test harness or an administration network. Confirm this with a request from outside that network before the run, because a test environment with an open admin path is a common source of exposure.
Keycloak production guideMetrics endpoint scoped to the test team
Enabling metrics with --metrics-enabled=true exposes Prometheus-format data at /metrics on the management interface. That data includes operational detail about the deployment, so the scrape path should be limited to the monitoring network and not routed through the public reverse proxy. Treat the metrics port as part of the test environment's attack surface and remove any external route before the run.
Generated accounts removed after the run
A benchmark run can leave thousands of generated users, sessions, offline tokens and clients behind. Those accounts can be used to log in if the environment is later reused, shared or restored from a backup. Record the realm names and user ranges used in each run, delete them through the same tooling that created them, and confirm the counts afterward. Also clear active sessions so no token from a test run survives.
Shared identity providers and email protected
Load tests that trigger password resets, email verification, or brokered logins can hit real identity providers and mail relays that other systems rely on. Point test realms at stub or sandbox providers, and set the SMTP settings to a test relay or a sink that discards mail. Rate limits, lockouts and provider quotas used by production users should not be consumed by a benchmark. Ask the owners of any shared system for written approval of the test volume.
Environment wiped and sanitized
After the results are recorded, tear down the test deployment and its database, object storage and logs, not just the Keycloak pods. Benchmark logs and metrics can contain client identifiers, usernames and request paths, so keep only the summarized results needed for the sizing decision. Document who approved the run, when it started and ended, and when the environment was destroyed, so the evidence trail matches what was actually executed.
Questions teams ask before running Keycloak load tests
How much effort does a Keycloak load test take?
Effort depends mostly on how much of the environment already exists and how many scenarios the targets require. A test of a single login flow against a staging cluster with a seeded dataset is far smaller than a campaign covering password logins, authorization code flows with token refresh, client credentials grants and a cluster that must be sized from the start. The main drivers are the number of scenarios, the size and realism of the dataset, how many runs are needed to separate noise from real regressions, and how much tuning happens between runs. Ask any partner to break its quote into environment preparation, scenario scripting, test execution, analysis and the report, so you can see where the effort sits.
Can an internal team run a Keycloak load test on its own?
Yes, if the team has engineers who can operate Keycloak, a Kubernetes or VM environment that resembles production, and someone comfortable writing and reading Gatling simulations. Keycloak Benchmark is the project's own tooling for this work, so the setup is not proprietary. The usual gaps are not the tool but the surrounding practice: generating a dataset that matches real realm and user shapes, keeping the load generator from becoming the bottleneck, collecting metrics at the same time, and interpreting results against the sizing guide. Teams that have never run one often underestimate how many test cycles are needed before the numbers can be trusted.
What does a load test need from our team?
A load test needs more from your side than from the tool. Plan to provide:
- A staging or pre-production environment with the same Keycloak version, database engine, topology and network path as production, or a clear list of differences.
- Access to create a representative dataset, including realms, users, clients and credentials that are synthetic but shaped like yours.
- Read access to Keycloak and database metrics, plus a place to store results and logs.
- A named owner who signs off the targets (login rate, token refresh rate, latency percentiles and error thresholds) before the first run.
- A maintenance window if the test will saturate shared components such as the database or the identity provider chain.
How long does one Keycloak load test cycle take?
A cycle is the time from a configuration change to a result you can act on. It is set by environment provisioning, dataset loading, warm-up, the length of each run, analysis, and any tuning between runs. Dataset generation is often the longest step when user counts are large, and each run must be long enough to reach steady state, which depends on token lifetimes and session behavior. Ask for the expected number of cycles, what each cycle changes, and what counts as passing. The duration of your own cycle depends on your environment and targets, so confirm it with your team and the partner before scheduling a go-live.
Do we need to retest after an upgrade or configuration change?
Usually yes for any change that touches the request path, and the decision should be written down in advance. Keycloak ships minor releases several times a year, and the upgrading guide lists changes that can affect behavior, so a version upgrade should be re-measured against the same scenarios. Configuration changes that deserve a retest include database pool sizes, HTTP worker threads, cache settings, token lifetimes, enabled authentication flows, password hashing or MFA requirements, and the load balancer or proxy in front of the nodes. Cosmetic theme changes rarely need a full run.
What does a consultant add to a Keycloak load test?
A consultant adds experience with the failure modes that repeat across deployments: pool exhaustion, a database that becomes the limit before the Keycloak nodes do, load generators that hide the real bottleneck, and results that look fine on average but fail at the tail. DeployOpen plans, implements, hardens and supports self-hosted open-source platforms in the client's own infrastructure, and the load test is scoped in writing before work starts. The output should be a report that maps measured results to your sizing targets, a list of changes made, and the evidence your architecture and security reviewers will ask for. Confirm the deliverables, retest policy and environment requirements in the written scope.
How do the results map to the Keycloak sizing guide?
Start from the per-request figures in the Keycloak sizing guide and convert your expected logins, token refreshes and client credentials grants per second into a target for each scenario. A test then shows whether the measured CPU, memory, database load and latency at that rate stay within your headroom. Keep the comparison honest by testing the same topology and dataset shape the guide assumes, and by recording whether a result came from a bottleneck in Keycloak, the database or the load generator. Ask your team to confirm which figures apply to your deployment before accepting a sizing conclusion.
How DeployOpen scopes and delivers Keycloak load testing
DeployOpen plans load tests of Keycloak as part of the same self-hosted deployment it builds in your infrastructure, so the test targets come from your login volume and your sizing decisions. Each engagement starts with a written scope that names the scenarios, datasets, environment and acceptance criteria before any test runs.
How we scope
- Written scope names the login, token refresh and client credentials scenarios to be tested before work starts
- Agreed targets state the concurrency and throughput levels the deployment must meet at go-live
- Scope confirms the test environment, whether it mirrors production topology, database size and network path
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work begins
How we build
- Keycloak Benchmark is configured for your realms, clients and user dataset, using the project's Gatling-based scenarios
- Dataset generation is planned so user counts and client registrations match the sizing assumptions being tested
- Observability is enabled before the first run, including Keycloak metrics, database and pod resource monitoring
- Test runs are repeated with changed parameters so results show where the deployment saturates first
How we hand over
- Documentation records the test setup, datasets, scenarios and exact configuration used for each run
- Results are read against your sizing targets, with observed CPU, memory, database and pool behavior explained
- Findings list the configuration or capacity changes that would be needed before go-live, with owners named
- Your team receives the scripts and runbook so later tests can be repeated after upgrades or configuration changes
How we support
- Ongoing support is available as a retainer for repeat load tests after upgrades, realm growth or new clients
- Retesting after fixes confirms that the changed configuration meets the agreed targets
- Support can cover updates to the test suite when the Keycloak release line or deployment topology changes
- Ask for the retainer scope, retest terms and response expectations in writing alongside the initial quote

