Skip to content

providers/oauth2: speed up the discovery endpoint - #27696

Merged
dominic-r merged 5 commits into
mainfrom
dominic/oidc-discovery-performance
Nov 12, 2026
Merged

dominic-r merged 5 commits into
mainfrom
dominic/oidc-discovery-performance

Conversation

@dominic-r

@dominic-r dominic-r commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Details

What does this PR change?

discovery and jwks were loading the signing key's private key just to publish public info. loading an RSA private key makes openssl run RSA_check_key (checks p and q are prime etc), which is ~70ms for a 3072-bit key and ~155ms for 4096. neither endpoint needs the private key so:

  • CertificateKeyPair.public_key loads the key with the check skipped and only returns the public key. private_key (what signing uses) still runs the check
  • new JWTAlgorithms.from_public_key, from_private_key just calls it now
  • discovery + jwks use the public key. JWKSView.get_jwk_for_key is shared so the SSF, agent connector and apple psso jwks endpoints get the fix too
  • dropped the lru_cache on the jwk builder, it was keyed on the private key object and saved like microseconds
  • discovery select_relateds the app, provider, signing + encryption key in one query (7 -> 4 queries with claims cached). didn't join DCR too becuase postgres took 4ms just planning the 8 table join
  • claims evaluation fetches the anonymous user once instead of once per scope mapping

responses are byte for byte the same.

Why is this change needed?

on my homelab discovery was 200-330ms p50, and ~63% of a cold request was load_pem_private_key. there's already a per-process key cache but workers restart every 1000 requests and clients only hit discovery a few times a day, so it basicaly never hits.

one edge case: an RSA key that parses but fails the check (only possible by writing to the db directly) used to 500 on discovery and get skipped in jwks. now both publish its public key, signing with it still fails.

key load times
Key Load with the check Load without, and take the public key
RSA 3072-bit 69.2 ms 0.011 ms
RSA 4096-bit, as authentik generates 155.8 ms 0.012 ms
EC P-256 0.04 ms 0.012 ms

How was this tested?

seeded a sandbox shaped like my homelab (44 apps, 14 oauth2 providers, 3072-bit keys) plus a 10x set. cold caches, against current main:

main p50 this pr p50
discovery 109.8 ms 14.6 ms
jwks 100.1 ms 3.1 ms

warm caches it's the same (~6ms). at 10x main is slow even warm since the key cache can't hold 150 keys, this is 3.6-5.3x faster there.

all numbers

against current main, homelab-sized data, 200 requests:

Before each request Endpoint p50 main p50 this PR p95 main p95 this PR Queries main Queries this PR
Key and claims caches cleared Discovery 109.8 ms 14.6 ms 118.8 ms 23.2 ms 13 to 20 8 to 13
Key and claims caches cleared JWKS 100.1 ms 3.1 ms 107.9 ms 6.2 ms 1 1
Nothing cleared Discovery 5.9 ms 5.8 ms 9.1 ms 12.8 ms 7 4
Nothing cleared JWKS 3.6 ms 5.2 ms 7.6 ms 7.1 ms 1 1

earlier run against main at a24ae91 (before the rebase, middleware was slower then), median of 3 rounds.

homelab-sized, discovery:

Before each request p50 main p50 this PR Speedup p95 main p95 this PR Queries main Queries this PR
Key and claims caches cleared (homelab-like) 92.0 ms 22.5 ms 4.1x 101.6 ms 26.7 ms 15 to 23 10 to 16
Key cache cleared 92.6 ms 19.1 ms 4.9x 111.7 ms 25.6 ms 9 6
Claims cache cleared 24.6 ms 22.6 ms 1.1x 30.2 ms 28.1 ms 15 to 23 10 to 16
Nothing cleared 32.5 ms 21.4 ms 1.5x 43.3 ms 29.4 ms 9 6

homelab-sized, jwks:

Before each request p50 main p50 this PR Speedup p95 main p95 this PR Queries main Queries this PR
Key and claims caches cleared (homelab-like) 82.0 ms 14.7 ms 5.6x 88.5 ms 17.2 ms 3 3
Key cache cleared 92.9 ms 17.5 ms 5.3x 105.2 ms 21.7 ms 3 3
Claims cache cleared 16.7 ms 16.8 ms 1.0x 19.0 ms 20.6 ms 3 3
Nothing cleared 23.3 ms 18.8 ms 1.2x 34.3 ms 23.8 ms 3 3

10x (500 apps, 150 providers), discovery:

Before each request p50 main p50 this PR Speedup p95 main p95 this PR Queries main Queries this PR
Key and claims caches cleared (homelab-like) 133.9 ms 37.1 ms 3.6x 154.5 ms 46.2 ms 15 to 23 10 to 16
Key cache cleared 124.1 ms 28.0 ms 4.4x 129.8 ms 31.3 ms 9 6
Claims cache cleared 136.8 ms 37.0 ms 3.7x 149.8 ms 41.9 ms 15 to 23 10 to 16
Nothing cleared 85.0 ms 18.6 ms 4.6x 107.0 ms 24.4 ms 9 6

10x, jwks:

Before each request p50 main p50 this PR Speedup p95 main p95 this PR Queries main Queries this PR
Key and claims caches cleared (homelab-like) 122.1 ms 30.1 ms 4.1x 136.4 ms 39.2 ms 3 3
Key cache cleared 121.2 ms 25.4 ms 4.8x 126.3 ms 28.2 ms 3 3
Claims cache cleared 121.3 ms 27.0 ms 4.5x 127.0 ms 29.5 ms 3 3
Nothing cleared 87.4 ms 16.4 ms 5.3x 100.8 ms 22.2 ms 3 3

diffed the full responses of both endpoints for every provider vs main (EC, Ed25519/448, ML-DSA, HS256, encryption key, global issuer, DCR), all identical.

new tests: discovery + jwks work when loading the private key raises, discovery query count with cached claims, claims query count doesn't grow with scope mappings. all fail on main.

Linked issues


Checklist

  • The project has been linted, built, and tested (make all)
  • The documentation has been updated and formatted (make docs)
  • I have read the AI usage policy.

The discovery and JWKS endpoints need only a signing key's public key
and algorithm, but read both from the loaded private key. Loading an
RSA private key checks its private components, which takes tens of
milliseconds for a 3072-bit key and more for a 4096-bit one. The
per-process cache of loaded keys rarely helps these endpoints: clients
fetch them a few times a day, each worker restarts after 1000
requests, and the cache holds 128 keys.

Read the public key from the key data without that check. Every path
that stores a key already ran it, and anything that signs still loads
the validated private key.

Discovery also loads the application, provider and keys in one query,
and fetches the anonymous user once for all scope mappings instead of
once per mapping, as userinfo already shares one user between them.
Dynamic client registration stays a separate query: joining it as
well makes the query slower to plan than the extra round trip.
@netlify

netlify Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit 9b4d65b
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/6af5d16951db11cd28e9721b
😎 Deploy Preview https://deploy-preview-27696--authentik-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.33333% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.05%. Comparing base (1b3867a) to head (bd64312).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
authentik/crypto/models.py 93.75% 1 Missing ⚠️
authentik/providers/oauth2/models.py 94.73% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #27696   +/-   ##
=======================================
  Coverage   93.04%   93.05%           
=======================================
  Files        1237     1237           
  Lines       86390    86465   +75     
  Branches     4894     4894           
=======================================
+ Hits        80383    80458   +75     
  Misses       5920     5920           
  Partials       87       87           
Flag Coverage Δ
conformance 30.35% <30.83%> (-0.02%) ⬇️
e2e 35.02% <31.66%> (+0.04%) ⬆️
integration 27.85% <15.00%> (-0.02%) ⬇️
rust 51.12% <ø> (ø)
unit 94.58% <98.33%> (+<0.01%) ⬆️
unit-migrate 94.58% <98.33%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@jsachs
jsachs self-requested a review November 7, 2026 21:46
@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Playwright e2e

Download this run's HTML report and traces, then open the report:

gh run download 43244507686 -D playwright-artifacts
npx playwright show-report playwright-artifacts/playwright-report

Installation instructions

Instructions for docker-compose

Add the following block to your .env file:

AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
AUTHENTIK_TAG=gh-bd6431211321036019c176db3ed9e40614141e6b
# Distroless image: AUTHENTIK_TAG=gh-bd6431211321036019c176db3ed9e40614141e6b-distroless
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s

Afterwards, run the upgrade commands from the latest release notes.

Instructions for Kubernetes

Add the following block to your values.yml file:

authentik:
    outposts:
        container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
global:
    image:
        repository: ghcr.io/goauthentik/dev-server
        tag: gh-bd6431211321036019c176db3ed9e40614141e6b
        # Distroless image: tag: gh-bd6431211321036019c176db3ed9e40614141e6b-distroless

Afterwards, run the upgrade commands from the latest release notes.

- add OAuth2Provider.jwt_alg so discovery reads the signing algorithm
  from the provider instead of repeating jwt_key's HS256 fallback
- share one parse function and one guarded loader between public_key
  and private_key, reusing KEY_LOAD_ERRORS
- cache public key loads like private keys and certificates
- check encryption_key_id in discovery instead of joining the key row
- point the JWT_SIGNING_KEY_TYPES comment at from_public_key
- test that an RSA key failing validation is published but can't sign
- test that public keys are cached and loaded without the RSA key check

@jsachs jsachs left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed a few small adjustments but would feel better about this if I could reproduce your testing in akbench rather than some opaque claude scripts.

@dominic-r

Copy link
Copy Markdown
Member Author

@jsachs See the following:

https://bench.corp.goauthentik.io/testcases/pr-27696-oidc-discovery
https://bench.corp.goauthentik.io/testcases/pr-27696-oidc-jwks

Due to failing e2e frontend tests however, benchmarks aren't running on your latest commit as the pipeline doesn't reach that far with a failing job

@dominic-r

dominic-r commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

I never got to play with this thing before, so data might be a bit weird before ~9:30 EST while i was trying stuff out

(Oh PS, Latency will probably be lower in reality. Per Claude:

Latency will read high on both: with 64 clients queued against one replica, request duration is mostly waiting. Requests per second is the number to compare.

and throughput should also be higher in reality:

Still shared servers: discovery and JWKS hit the same head and main deployments, because the cluster has no room for a second pair. Each test's throughput is therefore lower than it would be alone.

)

@dominic-r
dominic-r requested a review from jsachs November 10, 2026 17:41

@jsachs jsachs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm, I'm going to open a few related issues but none of them need doing here

Comment thread authentik/crypto/models.py Outdated
key_data.encode("utf-8"),
password=None,
backend=default_backend(),
unsafe_skip_rsa_key_validation=not validate,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd still rather not have this at all

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the location of this parameter but am still quite confident that this is fine, since this only ever gets used for pubkeys:

load_pem_private_key(..., unsafe_skip_rsa_key_validation=True)    crypto/models.py:68
└─ _load_public_key(): returns only .public_key()                 crypto/models.py:56
   └─ CertificateKeyPair.public_key                               crypto/models.py:206
      ├─ JWKSView.get_jwk_for_key: publishes n/e                  oauth2/views/jwks.py:118
      │    (OAuth2 JWKS, SSF JWKS, agent JWKS, Apple PSSO JWKS)
      ├─ OAuth2Provider.jwt_alg: alg name for discovery           oauth2/models.py:377
      └─ EndSessionView.validate: verifies id_token_hint          oauth2/views/end_session.py:82

_parse_private_key took a validate flag and returned a private key, so
an unvalidated key was one argument away from the signing path. Load
the private key as main does, and skip RSA validation only inside
_load_public_key, which returns just the public key.
@dominic-r
dominic-r merged commit 616bd38 into main Nov 12, 2026
172 checks passed
@dominic-r
dominic-r deleted the dominic/oidc-discovery-performance branch November 12, 2026 17:08
kensternberg-authentik added a commit that referenced this pull request Nov 25, 2026
…t-info' into web/element/ak-event-info

* refs/remotes/origin/web/element/ak-event-info: (44 commits)
  A spelling error? In this economy?
  Convert one-line functions into arrow functions.
  Just explaining a seemingly random export in one of the renderers.
  web/component: ak-event-info
  Broke out renderers and switched to pattern matching.
  Holding pattern.
  First: Turn the renderer switch into a _function_
  web/elements: AttributeView and TreeView: Provide a multi-modal view of raw JSON or YAML information (#27687)
  providers/oauth2: speed up the discovery endpoint (#27696)
  providers/saml: share xml signature generation (#27786)
  tests/openid_conformance: upload JPEG screenshots (#27749)
  crypto: export certificate expiry as a Prometheus metric (#27771)
  core: bump openapitools/openapi-generator-cli from v7.26.0 to v7.27.0 in /packages/client-ts (#27663)
  core: bump openapitools/openapi-generator-cli from v7.26.0 to v7.27.0 in /packages/client-rust (#27662)
  core: bump goauthentik/fips-debian from `d363011` to `16c391c` in /lifecycle/container (#27368)
  web: bump body-parser from 1.20.6 to 1.20.9 (#27521)
  core: bump library/node from `6d2c7d5` to `438603b` in /website (#27709)
  core: bump library/nginx from `5ab5b0b` to `165ddde` in /website (#27710)
  web: bump postcss-selector-parser from 7.1.7 to 7.2.0 in /web (#27742)
  web: bump glob from 13.0.6 to 13.0.7 (#27744)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants