Why Keycloak database connection pool tuning decides login latency
When an identity service slows or times out under peak login traffic, the first place to look is often the queue in front of the database. Keycloak's database connection pool and HTTP worker threads decide how many requests can run database work at once and how many wait for a connection. A pool that is too small turns database waiting into login latency, even when the database and the Keycloak nodes have spare capacity.
For each request that reads or writes sessions, users, clients or tokens, Keycloak borrows a connection from its pool, runs the queries and returns the connection. If every connection is busy, the request waits until one is released, and the wait is added to the sign-in time the user sees. Teams usually need to revisit these settings when login volume grows, when they add nodes, or when the same database serves other applications. Each Keycloak node holds its own pool, so the total number of connections grows with the node count and can exceed what the database accepts.
Pool tuning is one part of high availability and scaling work, not a standalone fix. Its effect depends on node count, the database's connection limit and the per-request cost measured in your own environment, so confirm those figures before changing values. Plan the change alongside the Keycloak sizing guide work and a load test, and check the pool metrics during that test. Exhaustion usually shows up as rising request time with a database that is not yet saturated, which is the signal to size the pool and threads together rather than raising one value in isolation.
Pool and thread settings and when each fits
This table compares the initial, minimum and maximum database pool sizes and the HTTP worker thread setting, with the purpose of each and the risk of setting it too high or too low. Read each row as a setting to confirm in your running version, then decide whether it should match the others for steady latency.
| Setting | Purpose | When to keep it equal to the others | Risk if set too high or too low |
|---|---|---|---|
| Initial pool size | Connections opened when Keycloak starts, so the first requests after a restart do not wait for new connections to open | Keep equal to the minimum when steady traffic is predictable and you want the pool warm before load arrives | Too high: many connections open at boot and the database accepts them all at once. Too low: first requests after a restart queue while connections open |
| Minimum pool size | Connections kept open while idle, so bursts are served without reconnecting | Set equal to the maximum when load is steady and the database can carry the full pool at all times | Too high: idle connections hold database sessions and memory. Too low: bursts pay connection setup cost and latency rises during spikes |
| Maximum pool size | Upper limit on concurrent database connections from one Keycloak node | Keep the per-node maximum multiplied by node count below the database connection limit, with headroom for admin and maintenance sessions | Too high: nodes exhaust database connections and the database slows or refuses logins. Too low: requests wait for a free connection and pool exhaustion appears in metrics |
| HTTP worker threads | Number of threads that handle incoming HTTP requests on each node | Raise only when CPU is available and database waits are not the bottleneck, so threads are not all blocked on the pool | Too high: more threads contend for a limited pool and CPU, adding queueing. Too low: requests queue at the HTTP layer even when CPU and database have spare capacity |
| Exact key names | Names used in configuration files and command-line options | Always confirm against the running Keycloak version and the database and production guides before changing values | Using a key from another version or a renamed option can silently leave the default in place, so the tuning never takes effect |
How to set pool size against database limits
This sequence turns the database's connection ceiling into a per-node pool and thread budget for Keycloak, then proves that budget holds under load. The output is a documented pool configuration that your team has tested and can explain to the database owner.
Confirm the database engine and version
Start by recording the database engine and exact version Keycloak will use. Keycloak's database guide lists PostgreSQL 14 to 18 among its supported production databases, along with MariaDB, MySQL, Microsoft SQL Server, Oracle Database, EnterpriseDB Advanced, Amazon Aurora PostgreSQL and Azure SQL. Confirm with the database team that the version is still within its vendor support window, because a version that is near end of life will also constrain your upgrade plan. The step is done when the engine, version and support end date are written in the sizing record.
Read the connection limit and existing usage
Ask the database team for the server's maximum connection setting and the number of connections already held by other services, reporting tools, backups and administrators. Include connections that are reserved for superusers or maintenance, because they cannot be given to Keycloak. Check current peak usage over a representative period, not only a quiet moment. The step is done when you have one number for the connections available to Keycloak at peak, and the database team has agreed to it in writing.
Divide the budget across Keycloak nodes
Subtract a safety margin for failover, rolling upgrades and administrative sessions from the available connections, then divide what remains by the number of Keycloak nodes you expect to run, including the extra node you need during a rolling update. The result is the maximum pool size each node may use. Illustratively, if 100 connections were available and you plan three nodes with a reserve, each node gets a share well below 33, and you should verify that figure against your own numbers. The step is done when the per-node maximum and the reserve are recorded and the total across all nodes fits inside the agreed budget.
Set pool sizes and HTTP worker threads
Set the Keycloak database pool so that the initial, minimum and maximum sizes are equal, which avoids pool resizing under load and keeps connection behavior predictable. Then set the HTTP worker thread count so that threads do not queue far more requests than the pool can serve, because waiting threads hold memory without making progress. Record each value in the deployment configuration, such as the environment or Operator resource that carries the Keycloak database settings, and keep the values under version control. The step is done when the configured values match the per-node maximum from the previous step and a rendered configuration can be reviewed.
Confirm the pooler decision with the database team
Decide whether a connection pooler such as PgBouncer sits between Keycloak and PostgreSQL. A pooler can allow more client connections than the server accepts directly, but it changes how transactions, prepared statements and session state behave, so confirm compatibility with the Keycloak version and the database team's operating model before you use it. If you add a pooler, repeat the budget calculation against the pooler's own limits as well as the server's. The step is done when the team has recorded a yes or no decision and, for a yes, the pooler limits that Keycloak's pool must respect.
Run a load test against the configured limits
Run a load test that reproduces expected login, token refresh and client credentials traffic at peak, with the final pool and thread values in place. Keycloak Benchmark, covered in a sibling topic, is one way to generate this load. Watch for request latency that rises sharply as load increases, which often points to threads waiting for connections. Record the peak connection count on the database side and confirm it stays inside the budget from the earlier step. The step is done when the test shows steady latency at the target load and the database connection count never exceeds the reserved share.
Watch pool exhaustion in metrics
Enable Keycloak metrics with --metrics-enabled=true and scrape the Prometheus endpoint at /metrics on the management interface. Review the database connection pool metrics the build exposes in your version, and compare them with database-side connection counts and wait events. Set alerts for sustained pool saturation, rising request latency and growing thread queues, and confirm that alerts fire during a controlled test. The step is done when a dashboard shows pool use under the configured maximum at target load and an alert has been tested to fire before users are affected.
How a login request waits for a pooled connection
The diagram starts at a user's login request reaching a Keycloak node, where it takes an HTTP worker thread before asking the database connection pool for a connection. If a connection is free, the query runs against the database and the response returns to the user. If the pool is full, the request waits in a queue, and a request that waits too long times out. Check pool wait time and active connections in metrics first when logins slow down, because a full pool can make the database look idle while requests stack up.
Requests either get a pooled connection, queue for one, or time out.
Spotting pool exhaustion in metrics and logs
Keycloak exposes Prometheus-format metrics at /metrics on its management interface when it is started with --metrics-enabled=true. The management interface is separate from the public frontend, so the scrape path should be reachable from your monitoring network and not from the internet. Connection pool exhaustion appears as a pattern rather than a single alarm: the number of connections in use climbs to the configured maximum and stays there, while requests wait longer to obtain a connection. Pull the exact metric names for connection pool usage from the observability guide for your Keycloak version, because names can change between releases. Once you have them, graph the in-use count against the configured maximum and watch for a flat line at the ceiling during peak hours.
- Pool at ceiling: A pool that spends long periods at its maximum under normal login traffic is a sizing signal, not a one-off spike.
- Growing wait time: A rising time to acquire a connection shows requests queueing for the pool even when CPU is idle.
- Idle versus busy: A pool with many idle connections and frequent acquisition waits points to a different cause than a pool fully in use.
- Per-node comparison: Compare each node. One node at its ceiling while others are not may indicate uneven load balancing.
- Restart resets: Counters reset when a node restarts, so use rate functions instead of raw totals.
Check that scraping is working on every node before trusting any pool graph, and confirm the metric names in the observability guide for your version.
Keycloak can add HTTP request and cache histograms to its metrics output when the optional histogram settings are enabled. These show how long requests take, which lets you see whether latency is rising as the pool fills. A saturated pool does not usually raise the average latency gradually. It tends to produce a tail: a small share of requests waits for a connection and takes far longer than the rest, so percentile views are more informative than averages. Enable histograms only after confirming the exact option names and their cardinality impact for your version in the observability guide, since extra series add storage cost in your monitoring system.
- Upper percentiles: Watch the high percentile of request duration. Rising tails with flat medians are a common early sign of queueing.
- Endpoint grouping: Token and login endpoints behave differently from admin paths, so compare them separately.
- Correlation with load: Plot request duration against requests per second. Latency that rises only above a certain throughput suggests a capacity limit.
- Thread backlog: Rising duration without matching CPU growth can indicate HTTP worker threads waiting, not computing.
- Cache histograms: Cache timing can show whether slow requests are caused by database reads that bypass the cache.
Before changing pool or thread settings, record a baseline of these histograms during a normal peak so you have something to compare against.
The database knows how many sessions are connected, how many are active, and what they are waiting on. This view is independent of Keycloak, which makes it useful for confirming whether a pool problem is real or a Keycloak-side reporting issue. On PostgreSQL, the pg_stat_activity view lists connections with their state, such as active or idle, and the wait event for active ones. A large number of idle connections held by Keycloak nodes alongside a few long-running active queries suggests that the bottleneck is query time, not pool size. If the connection count approaches the server's configured maximum, the pool sizes across all nodes may be too large for the database, regardless of what each node is doing. Confirm the exact view and column behavior in the PostgreSQL documentation for the version you run.
- Connection count by node: Group sessions by client address to see how many each Keycloak node holds.
- Active versus idle: Many active sessions with long durations suggest slow queries; many idle sessions suggest oversized pools.
- Wait events: Lock or I/O waits show where the database is actually spending time.
- Total against limit: Sum the pool maximums of all nodes and compare with the database connection limit, leaving room for administrators and jobs.
- Long transactions: Idle-in-transaction sessions hold connections and locks, and they are a frequent cause of pool starvation.
Record these counts at the same time as the Keycloak pool metrics so both views can be lined up.
Keycloak's logs record errors and warnings that accompany pool and database trouble, such as failures to obtain a connection or timeouts during a database operation. Logs give the timing and the affected operation, which metrics do not. Because log wording and levels can change across releases, search for the general patterns in your version's output rather than relying on fixed phrases. Log volume also matters: a sudden burst of identical errors from every node at the same moment usually points to a shared dependency, such as the database or a network path, rather than one node's pool. Keep logs from all nodes in one place and align their timestamps so you can compare them with metrics from the same minute.
- Acquisition errors: Messages about failing to get a connection or a timeout during pool wait indicate exhaustion or a stalled database.
- Timeout clusters: Errors that appear together across nodes point to a shared cause.
- Slow query warnings: If your database or driver logs slow statements, match them to the request times in your histograms.
- Restart loops: Repeated startup failures after a configuration change can indicate that new pool settings exceed database limits.
- Timestamp alignment: Synchronized clocks across nodes and the database make event correlation reliable.
When you see an acquisition error, check the pool gauge and the database session count for the same window before changing any setting.
Security and operational considerations for pool changes
Pool size changes touch security, shared infrastructure and release process as well as latency. The cards below cover the controls to set before a tuned value reaches production, and the checks to repeat after every change.
Encrypt and authenticate the database connection
Every pooled connection carries database credentials and query results, so the connection itself needs protection. Use a dedicated database role for Keycloak with only the privileges its schema needs, load the password from a secret store rather than a plain configuration file, and enable TLS on the JDBC connection so traffic between the Keycloak nodes and the database is encrypted. Confirm the TLS settings with your database team, because the exact connection parameters depend on the database you chose.
Keycloak database docsKeep metrics off the public path
Pool metrics are useful for diagnosing exhaustion, but they reveal internal topology and load patterns. Start Keycloak with metrics enabled only where your monitoring can reach it, and keep the management interface on a network that public clients cannot route to. Check that your reverse proxy does not forward the metrics path, and confirm the same restriction applies to every node in a rolling deployment.
Keycloak metrics guideDo not enlarge the pool to hide slow queries
When requests queue for a connection, a larger pool can look like a fix while it actually moves the bottleneck to the database. Each extra connection holds server memory and competes for locks, so a slow query or a missing index gets worse under more concurrency. Before raising the pool, find the slow statements in database logs, check the execution plan and confirm that the wait is for connections rather than for query time.
Roll out pool values through change control
Pool settings are read at startup, so a change takes effect node by node during a rolling restart. Record the current and target values for each node, apply them through your deployment tooling rather than by hand on individual pods, and keep one version of the configuration in version control. During the rollout, watch pool wait times and error rates per node, and keep the previous values ready so the change can be reverted without a new build.
Account for other clients of the database
A Keycloak pool is one of several consumers of the same database server, so its maximum size takes capacity from applications, batch jobs and administrators. Add up the maximum connections across every Keycloak node, plus other services and reserved administrative sessions, and compare the total with the server limit. For a managed database, confirm the limit with the provider because it can depend on instance size. Scale-out adds nodes, so re-run this total each time the node count changes.
Record tested values with sizing figures
A pool value means little without the load it was tested under. Store the chosen pool and thread settings alongside the expected logins and token requests per second, the node count, the database instance class, and the observed wait and latency figures from the load test. When traffic or topology changes, compare new measurements against that record instead of relying on memory. Ask your team to name the owner of this record so it stays current after the original engineers move on.
Questions teams ask about Keycloak pool tuning
How much effort does Keycloak database pool tuning take?
Tuning the pool is usually a small share of a Keycloak project, but the effort grows with the work around it. The main drivers are how many nodes share the database, how many connections the database accepts, how much load testing you need before go-live, and how much of your metrics setup already exists. A single cluster with a clear database budget and existing dashboards is much less work than a deployment where nodes, connection limits and monitoring all have to be agreed first. Ask any partner to show the tuning steps, the load test scenarios and the metrics they will watch, then price those against your environment in the written scope.
Can our own team tune the Keycloak database pool without outside help?
Yes, if your team already runs Keycloak and has someone who can read database metrics and run a load test. The settings themselves are simple configuration keys, so the difficulty lies in choosing values that fit your database limits and proving them under realistic traffic. Teams without database operations experience, or without a load test environment, often get the configuration right and the validation wrong. An outside partner is useful when you need the sizing reasoning documented for an audit, or when several nodes and a shared database must be balanced at once. Decide based on who will own the values after handover.
What does pool tuning need from the database and platform teams?
It needs the database team to state how many client connections the database can accept and how much headroom other applications need. The platform team must confirm how many Keycloak pods can run at peak, because total connections are the per-node pool size multiplied by node count. Both teams should agree on the database engine and version, which must be one of the supported production databases in the Keycloak database guide. The database team should also confirm whether a connection pooler such as PgBouncer sits in front of PostgreSQL, since that changes what the pool limit means. Write these numbers into the change record before any value is set.
How long does it take to validate a new pool configuration?
Validation time depends on how many load scenarios you need and how long each must run to show steady behavior. Plan for a staging run that reproduces peak login and token traffic, a review of pool and thread metrics during the run, and a second run after any change. Keep the test environment close to production in node count and database type, or the results will not carry over. Ask your partner or internal team for the test plan, the pass criteria and the rollback steps, and treat any duration in a proposal as an estimate to confirm against your own traffic profile.
Why do teams set the initial, minimum and maximum pool sizes to the same value?
Setting them equal stops the pool from opening and closing connections as traffic rises and falls, which keeps latency steadier under load. When the pool starts small and grows, requests during a spike wait for new connections to be established, and the database sees bursts of connection setup. With equal values, the connections are ready before traffic arrives, and the total connection count is fixed and easy to calculate against the database limit. The trade-off is that idle connections stay open, so this works best when the total across all nodes fits comfortably inside what the database allows.
How do we know the database pool is too large?
A pool that is too large usually shows up as database strain rather than Keycloak errors. Watch for the database reaching its connection limit, rising memory use on the database host, and lock or CPU contention when many connections run queries at once. In Keycloak, metrics exposed at /metrics on the management interface when metrics are enabled can show whether connections are waiting or idle for long periods. If latency gets worse as you add connections, the database is the bottleneck, and the pool should shrink. Confirm the exact metric names in your Keycloak version before building dashboards.
What changes in the pool settings after a Keycloak upgrade?
The pool settings usually stay the same, but an upgrade is the right moment to recheck them. Each Keycloak release can change its database schema, and the upgrade process may run schema migration at startup by default, which holds connections for longer than normal traffic does. Review the upgrade notes for the target version, check whether migration runs automatically or manually, and repeat a load test if the release changes how requests use the database. Teams in regulated settings should record the pool values before and after the upgrade so that the change is traceable in their change management records.
How DeployOpen scopes Keycloak pool and thread tuning
DeployOpen scopes pool and thread tuning as a fixed-scope engagement with the scope, deliverables and timeline agreed in writing before work starts. For this topic, the written scope usually names the Keycloak version and deployment method in use, the database engine and its connection limits, the node count and the load profile the tuning must hold under. It also names what the client receives at the end: the proposed values for the database pool and HTTP worker threads, the reasoning behind them, the metrics dashboards used to check them, and a short runbook for spotting pool exhaustion. Ask for the scope to state which Keycloak configuration settings will change, which will stay at their defaults, and whether DeployOpen will edit the client's own configuration files, Operator resources or Helm values or only provide them for the client's team to apply.
All work runs inside the client's own infrastructure, including their cloud accounts, data centers or restricted networks. DeployOpen does not need standing access to production data to tune a pool, but it does need a staging or pre-production environment that matches the database version and node count closely enough for results to carry over. Confirm early who provides that environment, who holds the database credentials, and how changes are rolled out and reverted. Scope should also say whether the database team must approve changes to connection limits on the server side, since the pool size chosen for Keycloak has to fit within those limits across every node.
Tuning is usually verified with a load test, and DeployOpen can run that test as part of the engagement or as a separate piece of work. Ongoing support after go-live is available as a retainer, which can cover re-testing after Keycloak upgrades, database changes or traffic growth. Ask any provider to write down how the load test is defined, which metrics mark success, and what happens if results do not meet the targets. DeployOpen does not publish a price list, so the quote follows from the written scope, and the scope is the document to compare across proposals.

