Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/database-prune-batches.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'bentocache': minor
---

feat(database): prune expired entries in batches (`pruneBatchSize`)

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. On a table that grows to millions of rows that statement can outlive the
connection's `statement_timeout`, and the rollback throws away the work already
done — the table never shrinks while every run pays a full scan of it again.

`pruneBatchSize` opts into deleting that many rows per statement, each one inside
a short transaction and ordered by `expires_at` so it stays on the index. Also
prevents overlapping prune runs when a run outlasts `pruneInterval`.
24 changes: 22 additions & 2 deletions packages/bentocache/src/drivers/database/adapters/knex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,28 @@ export class KnexAdapter implements DatabaseAdapter {
})
}

async pruneExpiredEntries(): Promise<void> {
await this.#connection.from(this.#tableName).where('expires_at', '<', new Date()).delete()
async pruneExpiredEntries(options?: { limit?: number }): Promise<number | void> {
/**
* `limit` + `order by expires_at` keeps each statement inside the `expires_at`
* index, so a prune over millions of rows costs a bounded amount of work
* instead of a sequential scan of the whole table. Knex refuses `limit` on a
* `delete`, so the bounded set is picked by a subquery.
*/
if (options?.limit) {
const expired = this.#connection
.from(this.#tableName)
.select('key')
.where('expires_at', '<', new Date())
.orderBy('expires_at')
.limit(options.limit)

return await this.#connection.from(this.#tableName).whereIn('key', expired).delete()
}

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

async clear(prefix: string): Promise<void> {
Expand Down
25 changes: 20 additions & 5 deletions packages/bentocache/src/drivers/database/adapters/kysely.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,26 @@ export class KyselyAdapter implements DatabaseAdapter {
.execute()
}

async pruneExpiredEntries(): Promise<void> {
await this.#connection
.deleteFrom(this.#tableName)
.where('expires_at', '<', Date.now())
.execute()
async pruneExpiredEntries(options?: { limit?: number }): Promise<number | void> {
let query = this.#connection.deleteFrom(this.#tableName).where('expires_at', '<', Date.now())

if (options?.limit) {
const expiredKeys = this.#connection
.selectFrom(this.#tableName)
.select('key')
.where('expires_at', '<', Date.now())
.orderBy('expires_at')
.limit(options.limit)

query = this.#connection
.deleteFrom(this.#tableName)
.where('key', 'in', expiredKeys) as typeof query

const result = await query.executeTakeFirst()
return +result.numDeletedRows.toString()
}

await query.execute()
}

async clear(prefix: string): Promise<void> {
Expand Down
70 changes: 64 additions & 6 deletions packages/bentocache/src/drivers/database/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,21 @@ export class DatabaseDriver extends BaseDriver implements CacheDriver<true> {
*/
#pruneInterval?: NodeJS.Timeout

/**
* Whether a prune run is in progress, so intervals don't overlap
*/
#pruning = false

/**
* Rows deleted per statement while pruning (`0` = single statement)
*/
#pruneBatchSize: number

constructor(adapter: DatabaseAdapter, config: DatabaseConfig, isNamespace = false) {
super(config)
this.#adapter = adapter
// `false`/`0` = one statement, like before; batching is opt-in.
this.#pruneBatchSize = config.pruneBatchSize === false ? 0 : (config.pruneBatchSize ?? 0)

if (isNamespace) {
this.#initializer = asyncNoop
Expand All @@ -53,14 +65,60 @@ export class DatabaseDriver extends BaseDriver implements CacheDriver<true> {
* Maybe rework this using a node Worker ?
*/
#startPruneInterval(interval: number) {
this.#pruneInterval = setInterval(async () => {
await this.#initializer()
await this.#adapter
.pruneExpiredEntries()
.catch(err => console.error('[bentocache] failed to prune expired entries', err))
this.#pruneInterval = setInterval(() => {
/**
* A prune that takes longer than the interval would otherwise overlap with
* the next one, and two prunes deleting the same rows is wasted work. The
* previous run has to finish (or fail) before the next one starts.
*/
if (this.#pruning) return

this.#runPrune().catch(err =>
console.error('[bentocache] failed to prune expired entries', err),
)
}, interval)
}

async #runPrune() {
this.#pruning = true

try {
await this.#initializer()
await this.#pruneExpiredEntries()
} finally {
this.#pruning = false
}
}

/**
* Delete expired entries, in batches when the adapter supports it.
*
* A single `delete where expires_at < now()` over a table with millions of rows
* makes the planner pick a sequential scan and keeps one transaction open for
* the whole delete — long enough to hit a `statement_timeout`, whose rollback
* then undoes everything (the table never shrinks, and every run pays the scan
* again). Deleting `pruneBatchSize` rows per statement bounds each transaction:
* the batches use the `expires_at` index and stop as soon as one comes back
* empty. `false`/`0` keeps the single-statement behaviour.
*/
async #pruneExpiredEntries() {
const batchSize = this.#pruneBatchSize
if (!batchSize) {
await this.#adapter.pruneExpiredEntries()
return
}

/**
* Nothing left to delete ends the loop; `undefined` means the adapter ignored
* `limit` and already pruned everything in one call, so there is no batch to
* repeat.
*/
for (;;) {
const deleted = await this.#adapter.pruneExpiredEntries({ limit: batchSize })
if (!deleted || deleted < batchSize) return
}
}

/**
* Check if the given timestamp is expired
*/
Expand Down Expand Up @@ -172,6 +230,6 @@ export class DatabaseDriver extends BaseDriver implements CacheDriver<true> {
*/
async prune() {
await this.#initializer()
await this.#adapter.pruneExpiredEntries()
await this.#pruneExpiredEntries()
}
}
7 changes: 6 additions & 1 deletion packages/bentocache/src/types/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,13 @@ export interface DatabaseAdapter {

/**
* Remove expired entries from the cache table
*
* When `options.limit` is given, remove at most that many entries and return
* how many were removed, so the driver can prune a large table in batches
* instead of one statement over the whole table. Adapters that ignore the
* option and return nothing are pruned in a single call.
*/
pruneExpiredEntries(): Promise<void>
pruneExpiredEntries(options?: { limit?: number }): Promise<number | void>

/**
* Clear all entries from the cache table
Expand Down
23 changes: 23 additions & 0 deletions packages/bentocache/src/types/options/drivers_options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,29 @@ export interface DatabaseConfig extends DriverCommonOptions {
* @default false
*/
pruneInterval?: Duration | false

/**
* How many expired entries are deleted per statement during a prune run.
*
* One `delete ... where expires_at < now()` over a large table makes the
* planner choose a sequential scan and hold a single transaction open for
* the whole delete. On a cache table that grows to millions of rows, that
* statement can outlive the connection's `statement_timeout`, and the
* rollback then throws away the work that had already been done — the table
* never shrinks while each run keeps paying a full scan of it.
*
* Pruning therefore deletes in batches of this size, one statement each,
* until a batch comes back empty.
*
* Off by default: pruning in a single statement is what every adapter did
* before, and the batched form relies on a `delete … where key in (select …)`
* subquery, which MySQL rejects when the subquery reads the table being
* deleted from. Turn it on for a big Postgres table, where the single
* statement is what becomes a problem.
*
* @default false
*/
pruneBatchSize?: number | false
}

/**
Expand Down
54 changes: 54 additions & 0 deletions packages/bentocache/tests/drivers/database.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,60 @@ test.group('Database driver', () => {
assert.isUndefined(hasFoo2)
})

test('should prune in batches when pruneBatchSize is set', async ({ assert, cleanup }) => {
const db = knex({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
})

const driver = new DatabaseDriver(new KnexAdapter({ connection: db }), {
tableName: 'cache',
autoCreateTable: true,
pruneBatchSize: 2,
})
cleanup(() => driver.disconnect())

// 5 entries, batches of 2: 2 + 2 + 1, and the loop stops on the batch that
// comes back short instead of asking a fourth time for an empty table.
for (const key of ['a', 'b', 'c', 'd', 'e']) await driver.set(key, 'bar', 300)
await sleep(400)

const adapter = new KnexAdapter({ connection: db })
adapter.setTableName('cache')
const deleted = await adapter.pruneExpiredEntries({ limit: 2 })
assert.equal(deleted, 2)

await driver.prune()

const remaining = await db('cache').select('key')
assert.deepEqual(remaining, [])
})

test('should honor an explicit batch size of 1 without looping forever', async ({
assert,
cleanup,
}) => {
const db = knex({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
})

const driver = new DatabaseDriver(new KnexAdapter({ connection: db }), {
tableName: 'cache',
autoCreateTable: true,
pruneBatchSize: 1,
})
cleanup(() => driver.disconnect())

for (const key of ['a', 'b', 'c']) await driver.set(key, 'bar', 300)
await sleep(400)

await driver.prune()
assert.deepEqual(await db('cache').select('key'), [])
})

test('should delete expired item with correct prefixed key', async ({ assert, cleanup }) => {
const db = knex({
client: 'better-sqlite3',
Expand Down