Scheduled cleanup job
Delete expired documents every night with a schedule trigger, processing them in batches that fit in a function's timeout.
Many apps store short-lived data: sessions, one-time links, carts, notifications. This recipe removes expired documents from a Sessions bucket every night.
1. The bucket
bucket/Sessions/schema.yaml
title: Sessions
description: Temporary sessions
primary: token
properties:
token:
type: string
title: Token
expires_at:
type: date
title: Expires at
indexes:
- definition: {expires_at: 1}The index on expires_at keeps the cleanup query fast as the bucket grows.
2. The function
Store an API key with access to the bucket as the secret SPICA_API_KEY, and the bucket id as the environment variable SESSIONS_BUCKET_ID.
function/cleanup/schema.yaml
name: cleanup
description: Removes expired sessions
language: javascript
timeout: 60
triggers:
removeExpiredSessions:
type: schedule
active: true
options:
frequency: "0 3 * * *"
timezone: UTC
env_vars: [<SESSIONS_BUCKET_ID id>]
secrets: [<SPICA_API_KEY id>]function/cleanup/index.mjs
import * as Bucket from "@spica-devkit/bucket";
Bucket.initialize({apikey: process.env.SPICA_API_KEY});
const BATCH_SIZE = 100;
export async function removeExpiredSessions() {
const bucketId = process.env.SESSIONS_BUCKET_ID;
const filter = "unixTime(document.expires_at) < now()";
let removed = 0;
while (true) {
const expired = await Bucket.data.getAll(bucketId, {queryParams: {filter, limit: BATCH_SIZE}});
if (!expired.length) {
break;
}
await Bucket.data.removeMany(bucketId, expired.map(session => session._id));
removed += expired.length;
}
console.info(`Removed ${removed} expired sessions`);
return removed;
}Each iteration reads one page of expired sessions and deletes it with a single batch request, until nothing is left.
3. Run it on demand
While you develop, add an HTTP trigger that calls the same code, and remove it before going to production:
JavaScript
export async function runNow() {
return {removed: await removeExpiredSessions()};
}YAML
runNow:
type: http
active: true
options:
method: Post
path: /cleanup/run
authenticate: [IDENTITY]JSON
{"removed": 7}Variations
- Very large backlogs. Stop after a number of batches and let the next run continue, so one run never hits the timeout.
- Keep only the latest N documents. Use document limits with
limitExceedBehaviour: removeinstead of a job. - Archive instead of delete. Insert the documents into an archive bucket or object storage before removing them.