[GH-ISSUE #9141] api-key: Add option to disable inline deleteAllExpiredApiKeys cleanup #19918

Open
opened 2026-04-15 19:17:14 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @AdirAmsalem on GitHub (Apr 12, 2026).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/9141

Is this suited for github?

  • Yes, this is suited for github

Is your feature request related to a problem? Please describe.

Problem

The api-key plugin runs deleteAllExpiredApiKeys() on every route handler (create, verify, list, update, delete). For applications that generate high volumes of keys (e.g. short-lived tokens), this causes serious database performance issues:

  • The DELETE query scans the entire table if no index exists on expires_at
  • Multiple concurrent requests bypass the 10-second in-memory throttle (race condition on lastChecked timestamp)
  • Foreign key cascades (ON DELETE ...) on referencing tables compound the cost

Describe the solution you'd like

Add a configuration option to disable the inline cleanup, allowing users to manage expired key cleanup externally (e.g. via cron calling the existing deleteAllExpiredApiKeys endpoint), or avoiding it entirely.

apiKey({
  keyExpiration: {
    autoCleanup: false, // default: true
  },
})
Originally created by @AdirAmsalem on GitHub (Apr 12, 2026). Original GitHub issue: https://github.com/better-auth/better-auth/issues/9141 ### Is this suited for github? - [x] Yes, this is suited for github ### Is your feature request related to a problem? Please describe. ### Problem The `api-key` plugin runs `deleteAllExpiredApiKeys()` on every route handler (create, verify, list, update, delete). For applications that generate high volumes of keys (e.g. short-lived tokens), this causes serious database performance issues: - The DELETE query scans the entire table if no index exists on `expires_at` - Multiple concurrent requests bypass the 10-second in-memory throttle (race condition on `lastChecked` timestamp) - Foreign key cascades (`ON DELETE ...`) on referencing tables compound the cost ### Describe the solution you'd like Add a configuration option to disable the inline cleanup, allowing users to manage expired key cleanup externally (e.g. via cron calling the existing `deleteAllExpiredApiKeys` endpoint), or avoiding it entirely. ```ts apiKey({ keyExpiration: { autoCleanup: false, // default: true }, }) ```
Author
Owner

@GautamBytes commented on GitHub (Apr 13, 2026):

will be working on it!

<!-- gh-comment-id:4235027983 --> @GautamBytes commented on GitHub (Apr 13, 2026): will be working on it!
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#19918