Distributed tracing for Keycloak with OpenTelemetry

Use OpenTelemetry traces to find where Keycloak logins spend their time across the database, LDAP and identity providers, with a Collector you run in your own infrastructure.

On this page

Keycloak distributed tracing with OpenTelemetry: when slow logins need traces

When logins are slow but dashboards show only averages, the operations lead needs to see individual requests. Distributed tracing records each step of one login, including the database queries, LDAP calls and calls to upstream identity providers that Keycloak makes along the way. Averages hide the rare login that takes ten seconds because one LDAP lookup timed out, and metrics rarely say which dependency caused it. Traces answer that question for a specific request, while metrics show whether the problem is widespread and logs show what Keycloak reported at the time.

OpenTelemetry is a framework and toolkit for generating, exporting and collecting telemetry, including traces, metrics and logs. It is not an observability backend, so it does not store or visualize anything by itself. Keycloak produces spans through its own configuration, which you enable and tune in the server. The OpenTelemetry Collector, which receives, processes and forwards those spans, and the tracing backend that stores and displays them are separate components you choose and operate. Confirm which Keycloak version and tracing settings your environment uses in the Keycloak documentation before you plan the rollout, since span names and attributes can differ between releases.

Before you enable tracing, decide where spans should go and who can read them, because spans can carry query details and user-related attributes. Plan the Collector as its own tier in your infrastructure, check the stability notes for the Collector components you plan to use, and agree on a sampling approach for production so that trace volume does not overwhelm storage. Ask your team to reproduce a known slow login in a test realm first, confirm that the database, LDAP and identity provider spans appear as expected, and only then widen collection to production traffic.

How a Keycloak login trace reaches your backend

A login starts in the user's browser, passes through the reverse proxy, and reaches Keycloak, which creates spans for the request. Keycloak exports those spans to an OpenTelemetry Collector, running either as an agent beside Keycloak or as a shared gateway, and the Collector forwards them to a trace backend you choose. The trust boundary sits around the Collector and the database, LDAP and upstream identity provider calls, which appear as downstream spans in the same trace. When you check the setup, confirm that the proxy and Collector endpoints are protected and that the backend receives the spans you expect.

Login spans flow from Keycloak through a Collector to a backend you choose.

Which tracing setup fits your environment

On a single virtual machine or a container host, the simplest layout places an OpenTelemetry Collector on the same host as Keycloak, acting as an agent. Keycloak sends spans to a local address, and the Collector forwards them to your trace backend. This keeps the exporter configuration short and avoids opening network paths between hosts for telemetry. The trade-off is that every Keycloak node carries its own Collector to patch and monitor.

  • Collector placement: Run the Collector as a sidecar process or container beside each Keycloak node, so spans never leave the host unencrypted.
  • Exporter endpoint: Point the Keycloak tracing exporter at the local Collector address, and keep the backend credentials in the Collector configuration, not in Keycloak.
  • Sampling: Set the sampling ratio on Keycloak so that a busy node does not flood the Collector during an incident.
  • Collector lifecycle: Pin a Collector release, record its checksum from the release artifacts, and include it in your normal patch cycle.
  • Resource limits: Confirm the memory headroom left for Keycloak, since the Collector shares the host.

Before you go live, confirm which Keycloak version you run and that the tracing options you plan to set exist in that release.

Tracing configuration options and when each fits

This table compares the main tracing choices for Keycloak: enabling export, sampling strategy, span detail and Collector placement. Read each row against your login volume and your team's operating model, then confirm the exact setting names in the Keycloak release you run. The main takeaway is that sampling and Collector placement decide most of the production cost and risk, so they deserve the earliest decision.

ChoiceOptionWhen it fitsWhat to confirm
Enabling tracingTracing on with an exporter endpoint pointed at a CollectorAny environment where you need to find slow logins and have a Collector to receive spansThe tracing enable setting and endpoint key for your Keycloak version in the current observability docs
SamplingAlways on (sample every trace)Development, test, or short investigations on low login volumeWhether the volume your backend can store and query stays affordable at peak login rates
SamplingRatio-based (sample a fraction of traces)Production with high login volume where full capture would overwhelm storageThe sampler name and ratio keys, and that a low ratio can miss rare slow logins
SamplingParent-based (follow the caller's sampling decision)Environments where the proxy or gateway in front of Keycloak already samples and you want traces to stay complete across servicesWhether incoming trace context headers reach Keycloak through your reverse proxy unchanged
Span detailDefault spans for HTTP, database and cache workFirst rollout, when you need to separate Keycloak time from database or proxy timeWhich span categories are emitted by default and how much each adds to the trace size
Span detailExtra detail for LDAP and identity provider callsInvestigations into brokering or federation delays, usually enabled for a limited periodWhether the extra spans are available in your version and their effect on trace volume
Collector placementAgent next to Keycloak nodesSmall footprints where each node forwards directly and local buffering mattersResource use per node and how the agent is deployed on your platform
Collector placementGateway accepting data from many sourcesLarger estates where one place handles sampling, batching, and export to the backendCapacity planning for the gateway and the authentication configured on its receivers

Setting up tracing from Keycloak to the Collector

This sequence connects a Keycloak deployment to an OpenTelemetry Collector so that login requests produce traces with spans for database and external calls. Each step ends with a check so the team knows the pipeline works before it relies on it for diagnosis.

  1. Confirm the Keycloak version and deployment method

    Record the exact Keycloak version, how it runs (container, Kubernetes with the Keycloak Operator, or virtual machines), and which database it uses. Tracing options and configuration keys can differ between releases, so read the tracing section of the Keycloak documentation for that version before changing anything. The Keycloak Operator path also means tracing settings go into the Keycloak custom resource rather than a local config file. The step is done when the team has a written baseline of version, deployment method and current configuration that a rollback can return to.

  2. Run a Collector with an OTLP receiver

    Deploy an OpenTelemetry Collector in the same network as Keycloak, either as an agent beside the service or as a gateway that several services share. Configure an OTLP receiver and at least one exporter to your trace backend, which the Collector does not provide itself. Keep the Collector configuration in version control and use the contrib distribution only if a required component needs it. The check is that the Collector starts cleanly, logs show the receiver listening, and a test span sent with a simple OTLP client appears in the backend.

  3. Restrict and secure the Collector endpoint

    Before Keycloak sends data, decide who may reach the OTLP port. Where traffic crosses a trust boundary, enable TLS on the receiver and, if your Collector version and policy require it, add an authenticator extension such as OIDC on the receiver or the oauth2client extension on the exporter. Confirm the exact extension names and options in the Collector configuration documentation for your release. The check is that a request without the expected credentials or certificate is rejected, and a request with them is accepted.

  4. Enable Keycloak's tracing exporter

    Turn on tracing in Keycloak and point its OTLP exporter at the Collector endpoint, using the configuration keys documented for your Keycloak version. Set the service name so Keycloak spans are easy to filter next to other services. Start with sampling that records every request in a non-production environment so you can see the full span set. The check is that Keycloak starts without errors, the startup log shows tracing enabled, and the Collector logs show Keycloak as a sending source.

  5. Set production sampling deliberately

    Before routing production traffic, choose a sampling strategy. Sampling reduces volume and cost, but it can drop the very slow logins you are trying to find, so decide whether sampling is head-based in Keycloak or tail-based in the Collector and document the trade-off. Keep a note of the previous sampling value. Rollback for any sampling change is to restore that saved value and restart or reload Keycloak in the same change window, then confirm span volume returns to the earlier level.

  6. Generate a test login and inspect spans

    Sign in with a test user through a client application, then find the resulting trace in your backend. Confirm the root span covers the login request and that child spans appear for database queries and, if the flow calls them, LDAP or an upstream identity provider. Compare the span names with what your Keycloak version documents. If a database or external span is missing, check whether that component is instrumented in your version and whether sampling dropped the trace. The check is one complete trace showing the expected child spans with durations.

  7. Record the working configuration and rollback steps

    Store the final Keycloak tracing settings, Collector configuration, sampling value and the test trace identifiers in your runbook or version control. Note who approves sampling changes and how to revert them. Confirm the on-call team can find a slow login trace using the service name and the test user's flow. The step is done when a second engineer can repeat the test login and reach the same spans from the documented steps alone.

Reading spans for database, LDAP and identity provider calls

Start from the request span, not from a database query. A slow login is usually one root span for the authentication request with child spans underneath it, and the useful question is which child carries most of the elapsed time. Open the trace for a slow login and sort or read the children in time order. Keycloak's own work appears as the gaps between child spans, so measure the gap before blaming a dependency. If the largest child is a database statement, the problem sits in the data layer. If no child is large but the root span is slow, the time is inside Keycloak itself, such as flow execution, token signing or CPU pressure on the node. Confirm the exact span names for your Keycloak version in a test environment before writing alert queries or dashboards against them, since names and attributes change between releases.

Within the authentication request, the flow steps are the most useful grouping. Each authenticator in the browser flow, such as username and password, OTP or a conditional step, shows how long it ran and which downstream calls it made. A federated user lookup will usually show a directory call under the user storage step. Look for these patterns: a slow user storage span with a long LDAP or Active Directory child means the directory or the network path to it is the bottleneck, and the fix sits with the directory team, a closer domain controller, or a narrower search base and attribute set. A database span that repeats many times in one login usually points to N+1 style access, which is a Keycloak or extension issue to raise with the vendor or your developers. For brokered logins, the round trip to Microsoft Entra ID, Google or a SAML identity provider appears as an outbound client span. Its duration is upstream time, so compare it with the login total before treating the upstream provider as the cause.

Correlation with logs closes the gap that traces leave open. Confirm that Keycloak log lines carry the trace ID and span ID, which depends on your logging format and the logging settings in your version, so verify this in a test environment first. Once they do, take the trace ID from a slow span and search the log store for it to find errors, retries and the username or client involved, without exposing more personal data than your privacy review allows. Also decide who may read traces. Spans can contain query text, user identifiers and upstream hostnames, so restrict the trace backend the same way you restrict admin access and treat its retention as a data handling decision. Ask your implementation partner or Keycloak support to confirm which attributes are recorded and whether sensitive values are masked before you connect production traffic.

Security and operational risks of tracing in production

Traces are useful for finding slow logins, but they carry identity data, open network ports and credentials that a production system must protect. The cards below pair each risk with one control to put in place and check before tracing reaches real users.

Span attributes can become personal data

Spans record attributes from the requests they cover, and identity-related values such as usernames, client IDs or query text can end up in them. Once stored, those values are personal data that your retention and access rules must cover. Before enabling tracing, list which attributes Keycloak and your collector emit, and drop or hash any field your privacy review does not allow in a trace backend.

Unauthenticated collector receivers

A collector receiver that accepts spans on an open port lets anyone on the network send data into your pipeline or flood it. OpenTelemetry supports authenticator extensions, such as OIDC, that check incoming connections on receivers. Confirm that every receiver reachable from outside the Keycloak host network has an authenticator or is bound to a private interface, and test that an unauthenticated request is rejected.

Collector security practices

Exporter credentials stored in config

Collector exporters that send traces to a backend often need a token or client secret. Writing that secret into the collector configuration file puts it in version control, in container images and in anyone's view of the deployment. Use the oauth2client authenticator extension or a secret reference from your platform, restrict read access to the configuration file, and rotate the credential on the same schedule as other service accounts.

Sampling that hides rare failures

Head sampling drops most traces before they finish, so a rare failed login or a single slow LDAP call may never be stored. Lower sampling rates reduce storage cost but also reduce the chance of capturing the incident you are investigating. Decide which sampling rate applies to ordinary logins and which keeps all error or slow traces, and document the trade-off for the on-call team so they know what a missing trace means.

Collector upgrades and component stability

Collector releases ship often, and core components carry different stability levels documented in each component's README. A pipeline that depends on a beta receiver or processor can change behavior between releases. Pin the collector version, read the release notes and component status before each upgrade, verify checksums and signed artifacts from the release page, and run the new version against a staging Keycloak before production.

Collector releases

Keycloak tracing questions buyers ask before hiring help

How much effort does setting up OpenTelemetry tracing for Keycloak take?

Effort depends mostly on how many moving parts sit between a login and the trace backend, not on the Keycloak change itself, which is a small set of settings. The main drivers are the number of Keycloak nodes, whether a Collector already exists, how many external calls (database, LDAP, upstream identity providers) you need to see, and how your trace backend is secured and retained. Each Keycloak node has to export spans, so a cluster adds work to confirm that every node is reporting under a consistent service name. Ask any partner to split the quote into Keycloak configuration, Collector pipeline work, backend setup and verification so you can see where the hours go.

Can our own team set up Keycloak tracing without a partner?

Yes, a team that already runs Keycloak and an OpenTelemetry Collector can usually do the core work, because the Keycloak side is configuration and the Collector side is a documented pipeline. The gaps tend to be in areas that need repeated practice: choosing sampling so production traces stay useful, keeping sensitive attributes out of spans, reading spans for database, LDAP and brokering calls, and confirming that traces line up with logs and metrics during an incident. Teams often hire help for the first design and review, then run the pipeline themselves. The question to answer honestly is whether someone on your team will own the pipeline after go-live.

What access and infrastructure do we need to provide for the work?

Expect to provide access in three places: the Keycloak configuration and deployment (for example, the files or Operator resources that set startup options and tracing settings), a host or workload where the OpenTelemetry Collector runs, and a trace backend that stores and displays spans. Each needs an owner who can approve changes and a test environment where the change can be proven before production. You will also need network paths from Keycloak to the Collector, and from the Collector to the backend, that your security team has reviewed. Ask the partner to list every account, host and network rule they need before work starts, and to say which ones they will hold only for the engagement.

How does the sampling choice affect what tracing costs?

Sampling decides how many traces you keep, and the volume of kept spans is the main driver of storage and query cost in the trace backend. Recording every login is simple and gives full visibility, but login traffic, token refreshes and health checks can produce a large volume. A ratio-based or parent-based sampler reduces volume but can drop the one slow login you need, so sampling rules should keep errors and slow requests in view. The cost also depends on how long you retain traces, whether the backend bills by ingested data or by stored data, and whether the Collector filters spans before export. Ask for the sampling policy in writing, with a note on which signals are always kept.

What does a first useful trace review of a slow login involve?

A first review is a bounded exercise: pick a set of slow or failing logins, follow each trace through Keycloak, and identify where the time goes, such as database queries, LDAP calls, outbound calls to an identity provider or time spent in Keycloak itself. The duration depends on how many services the traces cross, how clean the data is after setup, and how many distinct login flows (password, MFA, brokered login) you want covered. The output should be a written finding for each slow path with the span evidence, plus a list of the next checks, such as pairing the trace with database or LDAP metrics. Ask whether the review ends with a findings document and a retest, and who attends the session.

Do traces expose user data, and how do we keep it out?

Spans can carry attributes such as URLs, query text, usernames or client identifiers, and some of these can be personal data or sensitive operational detail. Before enabling export, review which attributes Keycloak and the instrumentation add, decide which ones to drop or hash, and confirm the trace backend's access controls and retention match your data classification. The Collector can filter and redact attributes before data leaves your network, and its configuration best practices cover securing receivers and exporters. Ask the partner to show a sample of exported spans from a test login so your security and privacy teams can review them.

Will tracing replace our Keycloak logs and metrics?

No. Traces show the path and timing of one request across components, while logs record discrete events and metrics show trends across all requests. Keycloak also exposes Prometheus-format metrics at /metrics when started with metrics enabled, and those metrics are usually the first place to check whether logins are slow across the board. Tracing helps when a few logins are slow or when you need to attribute time to a specific dependency. Plan the three signals together so an alert on a metric can lead to a trace and then to a log line that share an identifier.

How DeployOpen delivers Keycloak tracing

DeployOpen scopes Keycloak tracing as a fixed-scope engagement with a written scope agreed before work starts. The scope names the Keycloak version and deployment topology, the database and any LDAP or identity provider endpoints whose calls should appear in traces, the OpenTelemetry Collector placement (agent next to Keycloak or gateway for many sources), the trace backend the client already runs, and the sampling approach for production. It also records who owns the Collector configuration, who approves changes to sampling, and where trace data may be stored. Ask for a quote that follows from this written scope, and confirm that the work runs in your own cloud accounts, data center or restricted network.

Delivery follows a sequence. DeployOpen enables tracing in a non-production Keycloak first, configures the OpenTelemetry Collector with the receivers, processors and exporters the scope names, and deploys it in your environment with its authentication and transport settings reviewed against the Collector configuration best practices. Engineers then reproduce a set of logins, including slow ones, and confirm that spans for the database, LDAP and brokered identity provider calls appear under the login request with usable timing. Sampling is tuned only after that check passes, so that production volume does not hide the slow paths you are trying to find.

Handover covers the configuration as code, a runbook for changing sampling and exporters, a list of verification traces and their expected spans, and the known limits of the Collector components you deploy, including any whose stability level is not yet stable. Optional retainer support can cover Collector upgrades, sampling reviews after Keycloak upgrades and help with new slow-login investigations. Confirm in writing which recurring tasks are included, who pays for backend storage, and how upgrades to Keycloak and the Collector are tested before they reach production.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.