[GH-ISSUE #3954] jwks table is queried from the database on every session read when using the JWT plugin. #9775

Open
opened 2026-04-13 05:29:00 -05:00 by GiteaMirror · 8 comments
Owner

Originally created by @istarkov on GitHub (Aug 12, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/3954

Originally assigned to: @bytaesu on GitHub.

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Add jwt plugin to better auth

See on every get-session database query is executed here
031888178d/packages/better-auth/src/plugins/jwt/index.ts (L340)

through

031888178d/packages/better-auth/src/plugins/jwt/sign.ts (L13)

Current vs. Expected behavior

There is no caching mechanism provided, resulting in repeated DB lookups.

I want to be able to use same caching idea for jwks keys as provided by jose for public keys, i.e.
cooldownDuration

Like per key cache here or at getJwtToken

What version of Better Auth are you using?

1.3.5

System info

System:
    OS: macOS 15.6
    CPU: (8) arm64 Apple M2
    Memory: 151.92 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Browsers:
    Brave Browser: 135.1.77.100
    Chrome: 139.0.7258.67
    Chrome Canary: 141.0.7350.0
    Safari: 18.6
    Safari Technology Preview: 18.4

Which area(s) are affected? (Select all that apply)

Backend

Auth config (if applicable)

import { betterAuth } from "better-auth"
import { jwt } from "better-auth/plugins";
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
  plugins: [
    jwt()
  ]
});

Additional context

Everything else like session-data has cache allowing us to skip some db queries (having cache). But jwks does not.

Originally created by @istarkov on GitHub (Aug 12, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/3954 Originally assigned to: @bytaesu on GitHub. ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Add jwt plugin to better auth See on every get-session database query is executed here https://github.com/better-auth/better-auth/blob/031888178d56f80bb8655ec693e04a4609c0e302/packages/better-auth/src/plugins/jwt/index.ts#L340 through https://github.com/better-auth/better-auth/blob/031888178d56f80bb8655ec693e04a4609c0e302/packages/better-auth/src/plugins/jwt/sign.ts#L13 ### Current vs. Expected behavior There is no caching mechanism provided, resulting in repeated DB lookups. I want to be able to use same caching idea for jwks keys as provided by jose for public keys, i.e. cooldownDuration Like per key cache [here](https://github.com/better-auth/better-auth/blob/031888178d56f80bb8655ec693e04a4609c0e302/packages/better-auth/src/plugins/jwt/index.ts#L340 ) or at getJwtToken ### What version of Better Auth are you using? 1.3.5 ### System info ```bash System: OS: macOS 15.6 CPU: (8) arm64 Apple M2 Memory: 151.92 MB / 16.00 GB Shell: 5.9 - /bin/zsh Browsers: Brave Browser: 135.1.77.100 Chrome: 139.0.7258.67 Chrome Canary: 141.0.7350.0 Safari: 18.6 Safari Technology Preview: 18.4 ``` ### Which area(s) are affected? (Select all that apply) Backend ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" import { jwt } from "better-auth/plugins"; export const auth = betterAuth({ emailAndPassword: { enabled: true }, plugins: [ jwt() ] }); ``` ### Additional context Everything else like session-data has cache allowing us to skip some db queries (having cache). But jwks does not.
GiteaMirror added the perfdatabase labels 2026-04-13 05:29:00 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Aug 12, 2025):

You're correct—currently, the JWT plugin in Better Auth does not cache JWKS keys, so every session read or JWT token generation triggers a database query for the latest key. This is different from session data, which uses a cache to avoid repeated DB hits. There’s no built-in equivalent to jose’s cooldownDuration or per-key cache for JWKS keys in the current implementation, and this has been noted as a desired feature by others as well (discussion).

If you want to implement caching, you could add an in-memory cache (e.g., using a simple Map or LRU cache) in the JWT plugin, keyed by the key ID or a global cache for the latest key, with a configurable TTL. You’d check the cache before querying the adapter, and update it after fetching from the DB. For multi-instance deployments, consider a distributed cache or accept that cache invalidation may be eventual.

This would bring JWKS key handling in line with how session-data caching works (see session caching docs), and should significantly reduce DB load for high-traffic apps.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3180091727 --> @dosubot[bot] commented on GitHub (Aug 12, 2025): <!-- Answer --> You're correct—currently, the JWT plugin in Better Auth does not cache JWKS keys, so every session read or JWT token generation triggers a database query for the latest key. This is different from session data, which uses a cache to avoid repeated DB hits. There’s no built-in equivalent to jose’s cooldownDuration or per-key cache for JWKS keys in the current implementation, and this has been noted as a desired feature by others as well ([discussion](https://github.com/better-auth/better-auth/issues/941#issuecomment-2563062461)). If you want to implement caching, you could add an in-memory cache (e.g., using a simple Map or LRU cache) in the JWT plugin, keyed by the key ID or a global cache for the latest key, with a configurable TTL. You’d check the cache before querying the adapter, and update it after fetching from the DB. For multi-instance deployments, consider a distributed cache or accept that cache invalidation may be eventual. This would bring JWKS key handling in line with how session-data caching works (see [session caching docs](https://better-auth.com/docs/concepts/session-management)), and should significantly reduce DB load for high-traffic apps. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/12f9e244-0ac6-48bf-8f17-1fd277419465?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/3954)
Author
Owner

@anmol-fzr commented on GitHub (Aug 13, 2025):

@Bekacru Hey i would like to work on this issue,

<!-- gh-comment-id:3184631014 --> @anmol-fzr commented on GitHub (Aug 13, 2025): @Bekacru Hey i would like to work on this issue,
Author
Owner

@madhuanildugar-ctrl commented on GitHub (Oct 15, 2025):

@Bekacru @anmol-fzr when is this feature going live ?

<!-- gh-comment-id:3407453488 --> @madhuanildugar-ctrl commented on GitHub (Oct 15, 2025): @Bekacru @anmol-fzr when is this feature going live ?
Author
Owner

@madhuanildugar-ctrl commented on GitHub (Oct 21, 2025):

@Bekacru when is this feature going live ? Pls help, Here are logs on how much this jwks table is adding to the overhead per request. pls help in optimizing this

Image
<!-- gh-comment-id:3424886046 --> @madhuanildugar-ctrl commented on GitHub (Oct 21, 2025): @Bekacru when is this feature going live ? Pls help, Here are logs on how much this jwks table is adding to the overhead per request. pls help in optimizing this <img width="1388" height="227" alt="Image" src="https://github.com/user-attachments/assets/fc42df4f-986b-4ac4-b7ae-53246985a53c" />
Author
Owner

@akarabach commented on GitHub (Oct 31, 2025):

any updates on it ?

<!-- gh-comment-id:3474367228 --> @akarabach commented on GitHub (Oct 31, 2025): any updates on it ?
Author
Owner

@better-auth-agent[bot] commented on GitHub (Oct 31, 2025):

The repeated database queries occur because the current JWT plugin doesn’t implement a caching layer for JWKS keys. To address this, you could add a caching mechanism (for example, based on a cooldownDuration per key) so that once a key is retrieved it’s stored in memory for a set period, similar to how jose handles public keys [1].

Next steps:

  1. Modify the key retrieval logic (e.g., in the getJwtToken flow) to cache the key per its key ID and set a cooldown period.
  2. Test the new caching behavior to ensure it prevents duplicate lookups without compromising key freshness.
  3. Consider filing or tracking an issue/PR if you’d like a coordinated fix in upcoming releases.

Let me know if you need further details or guidance on implementing this cache.

DiagramDiscordGitHub

Diagram Join Star

<!-- gh-comment-id:3474368827 --> @better-auth-agent[bot] commented on GitHub (Oct 31, 2025): The repeated database queries occur because the current JWT plugin doesn’t implement a caching layer for JWKS keys. To address this, you could add a caching mechanism (for example, based on a cooldownDuration per key) so that once a key is retrieved it’s stored in memory for a set period, similar to how jose handles public keys [[1]](https://github.com/better-auth/better-auth/issues/3954). Next steps: 1. Modify the key retrieval logic (e.g., in the getJwtToken flow) to cache the key per its key ID and set a cooldown period. 2. Test the new caching behavior to ensure it prevents duplicate lookups without compromising key freshness. 3. Consider filing or tracking an issue/PR if you’d like a coordinated fix in upcoming releases. Let me know if you need further details or guidance on implementing this cache. <!-- bot:webhook reply v1 --> [Diagram](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) • [Discord](https://discord.gg/better-auth) • [GitHub](https://github.com/better-auth/better-auth) [![Diagram](https://img.shields.io/badge/Diagram-2b3137?style=flat-square)](https://repodiagrams.s3.eu-north-1.amazonaws.com/better-auth_ultra_detailed_interactive.html) [![Join](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&style=flat-square)](https://discord.gg/better-auth) [![Star](https://img.shields.io/badge/star-181717?logo=github&logoColor=white&style=flat-square)](https://github.com/better-auth/better-auth)
Author
Owner

@dosubot[bot] commented on GitHub (Jan 30, 2026):

Hi, @istarkov. I'm Dosu, and I'm helping the better-auth team manage their backlog and am marking this issue as stale.

Issue Summary:

  • You identified that Better Auth's JWT plugin (v1.3.5) queries the jwks database on every session read without caching, leading to inefficiency.
  • It was confirmed that this causes repeated DB lookups, and an in-memory cache with TTL was suggested to reduce load.
  • A user expressed interest in implementing this caching feature, while others asked about the release timeline.
  • I provided guidance on next steps and encouraged contributions to address the issue.

Next Steps:

  • Please let us know if this issue is still relevant with the latest version of better-auth by commenting here to keep the discussion open.
  • If we do not hear back within 7 days, this issue will be automatically closed.

Thank you for your understanding and contribution!

<!-- gh-comment-id:3824516775 --> @dosubot[bot] commented on GitHub (Jan 30, 2026): Hi, @istarkov. I'm [Dosu](https://dosu.dev), and I'm helping the better-auth team manage their backlog and am marking this issue as stale. **Issue Summary:** - You identified that Better Auth's JWT plugin (v1.3.5) queries the jwks database on every session read without caching, leading to inefficiency. - It was confirmed that this causes repeated DB lookups, and an in-memory cache with TTL was suggested to reduce load. - A user expressed interest in implementing this caching feature, while others asked about the release timeline. - I provided guidance on next steps and encouraged contributions to address the issue. **Next Steps:** - Please let us know if this issue is still relevant with the latest version of better-auth by commenting here to keep the discussion open. - If we do not hear back within 7 days, this issue will be automatically closed. Thank you for your understanding and contribution!
Author
Owner

@akarabach commented on GitHub (Jan 30, 2026):

why ?

<!-- gh-comment-id:3824552418 --> @akarabach commented on GitHub (Jan 30, 2026): why ?
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#9775