Skip to content

feat(database): prune expired entries in batches - #131

Open
DavideCarvalho wants to merge 1 commit into
Julien-R44:mainfrom
DavideCarvalho:feat/prune-in-batches
Open

DavideCarvalho wants to merge 1 commit into
Julien-R44:mainfrom
DavideCarvalho:feat/prune-in-batches

Conversation

@DavideCarvalho

Copy link
Copy Markdown

The problem

pruneExpiredEntries() in every database adapter is one statement:

await this.#connection.from(this.#tableName).where('expires_at', '<', new Date()).delete()

On a cache table that has grown, that statement is a sequential scan of the whole table inside a single transaction. Measured on a production Postgres (bentocache 1.6.1, @adonisjs/cache):

query time buffers
select count(*) … where expires_at < now() 116 s 928.018
select count(*) (whole table) 133 s 1.866.212

5.4M rows, 15 GB, 79% already expired, shared_buffers 32 MB.

Two failure modes follow, and the second is what this PR also fixes:

  1. The delete gets cancelled and nothing is kept. With a statement_timeout on the connection (30 s on the web pool, a very normal setting), Postgres cancels the statement partway through and the rollback discards every row already deleted. So the table never shrinks, and every run pays the full 116 s scan again — for hours in the logs as [bentocache] failed to prune expired entries ... canceling statement due to statement timeout.
  2. Runs overlap. setInterval fires every pruneInterval regardless of whether the previous run finished. A run longer than the interval means N concurrent bulk deletes on the same table — more locks, more WAL, on a shared database.

The change

pruneBatchSize (default false) opts into deleting that many rows per statement:

drivers.database({
  connection: knexInstance,
  pruneInterval: '1h',
  pruneBatchSize: 10_000,
})

Each batch is its own short transaction, delete … where key in (select key … where expires_at < now() order by expires_at limit N), so it stays on the expires_at index instead of a sequential scan. The driver keeps pulling batches until one comes back short. On the table above: ~200 ms per 10k batch with the index warm.

The interval also skips a tick when the previous run is still in progress, which removes the overlap independently of batching.

Compatibility

  • Default is false = one statement, exactly as today. Nothing changes for existing users.
  • DatabaseAdapter.pruneExpiredEntries(options?: { limit?: number }): Promise<number | void>. An adapter that ignores the argument and returns nothing is pruned in a single call (the driver treats undefined as "already done"), so custom adapters keep working without edits — they just don't get batching. The type is loosened, not narrowed.
  • Knex and Kysely adapters implement the batched form; Orchid keeps the single statement (I don't know its API well enough to write the equivalent, and returning void is a valid implementation of the interface).
  • MySQL rejects delete … where key in (select … from the same table) — it needs a derived-table wrapper. That's why batching is opt-in rather than default; the Kysely adapter could grow a wrapper if someone wants it there.

Tests

tests/drivers/database.spec.ts, 3 new cases on SQLite: batching deletes a table of 5 rows in 2 + 2 + 1 (and stops on the short batch instead of asking a fourth time), pruneBatchSize: 1 terminates, and pruneBatchSize unset keeps the single-statement path.

  • pnpm lint ✅
  • pnpm typecheck ✅
  • pnpm format:check ✅
  • database spec: 5/5, knex sqlite + postgres: 21/21 each, kysely sqlite + postgres: 21/21 each (postgres via a local container)

Happy to make the default true instead, or to add the Orchid equivalent, if you prefer. As-is it's opt-in because of the MySQL subquery restriction and because it changes what a custom adapter is expected to do.

A single `delete ... where expires_at < now()` over a large cache table makes
the planner pick a sequential scan and keeps one transaction open for the whole
delete. Measured on a production Postgres table of 5.4M rows (15 GB, 79%
expired): 116s for the scan of the expired rows, 133s for the whole table, with
1.86M buffers touched.

Two things go wrong with that on a long-lived app:

- the connection's `statement_timeout` cancels the delete partway through, and
  the rollback discards every row already deleted, so the table never shrinks
  while each run keeps paying the full scan — 116s of shared database every hour,
  in the logs as `failed to prune expired entries ... statement timeout`.
- a run that outlives `pruneInterval` overlaps with the next one, so two prunes
  work on the same rows and the table gets concurrent bulk deletes.

`pruneBatchSize` opts into deleting that many rows per statement, ordered by
`expires_at` so each one stays on the index, until a batch comes back short. The
interval now skips a tick while a run is still in progress. Defaults to `false`
(one statement, the previous behaviour) because the batched form needs a
`delete ... where key in (select ...)` subquery, which MySQL rejects when the
subquery reads the table being deleted from.

BREAKING CHANGE: `DatabaseAdapter.pruneExpiredEntries()` now takes an optional
`{ limit }` and may return the number of deleted rows. Adapters that ignore the
argument and return nothing keep working (they are pruned in one call), but a
custom adapter that wants batching needs to accept the argument.
@changeset-bot

changeset-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 509ae39

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
bentocache Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant