Repository navigation
feat(database): prune expired entries in batches - #131
Open
DavideCarvalho wants to merge 1 commit into
Open
DavideCarvalho wants to merge 1 commit into
DavideCarvalho wants to merge 1 commit into
Conversation
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 detectedLatest commit: 509ae39 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The problem
pruneExpiredEntries()in every database adapter is one statement: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):select count(*) … where expires_at < now()select count(*)(whole table)5.4M rows, 15 GB, 79% already expired,
shared_buffers32 MB.Two failure modes follow, and the second is what this PR also fixes:
statement_timeouton 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.setIntervalfires everypruneIntervalregardless 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(defaultfalse) opts into deleting that many rows per statement: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 theexpires_atindex 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
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 treatsundefinedas "already done"), so custom adapters keep working without edits — they just don't get batching. The type is loosened, not narrowed.voidis a valid implementation of the interface).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 in2 + 2 + 1(and stops on the short batch instead of asking a fourth time),pruneBatchSize: 1terminates, andpruneBatchSizeunset keeps the single-statement path.pnpm lint✅pnpm typecheck✅pnpm format:check✅Happy to make the default
trueinstead, 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.