A scheduled cleanup job should begin as a bounded database operation, then acquire queue workers only when each record needs its own retry, pacing, or recovery boundary. Short answer: for predictable Postgres retention work in Node.js, a scheduler plus small committed batches is usually the lower-operational-cost design; use a message queue when independent work items justify its delivery state.
"Cheapest" needs a careful definition. A timer may be inexpensive to run, yet costly when two invocations overlap and delete the same records; a queue may make retries precise, yet costly in design and operation when one SQL statement would have done the work. The useful comparison is therefore not timer against broker. It is the state that must survive a process exit against the state the system is willing to reconstruct.
Keep the retention rule close to the data.
That boundary is useful.
What should scheduled data cleanup cron and message queue jobs do in Node.js with Postgres?
A scheduler answers when a cleanup pass may start. Postgres should decide which rows that pass owns, record the transaction outcome, and make unfinished rows eligible for a later pass. This is a good fit for expired rows whose deletion is local to the database and whose work can be divided into batches without changing the retention rule.
The important property is recoverability. A batch that commits is durable; a batch interrupted before commit rolls back; the next scheduled run can continue from the remaining eligible rows. A transaction-scoped advisory lock can make overlapping triggers decline to run, while FOR UPDATE SKIP LOCKED lets multiple deliberately partitioned workers avoid claiming the same candidate rows. Neither mechanism turns a non-idempotent external side effect into an exactly-once action, so cleanup handlers must keep their side effects narrow and their audit records explicit.
A message queue answers another question: how can many independently recoverable units wait for consumers? It earns that role when one tenant's cleanup can take far longer than another's, when deletion requires a rate-limited external operation, or when a single problematic record must be retried without replaying a whole batch. Queue delivery is normally at-least-once. A consumer must therefore treat the message identifier as an idempotency key and commit a completion record before acknowledging the message.
The catch is that a queue is not suitable when the job is one bounded, database-only sweep and no per-record retry policy is required. Stay with scheduled database batches in that case. Conversely, do not keep a cron-only design when its backlog persists across several schedule windows or recovery must be isolated at record level.
Start from the deletion transaction, not the clock
For retention cleanup, the safest unit is often a short transaction that claims a finite set of records and deletes only that set. The scheduler can be an operating-system cron entry, a platform timer, or a process owned by the application; that choice should not change the deletion contract. The following Go example shows the contract without tying it to a particular scheduler. A Node.js service can implement the same SQL and transaction boundary through its database driver.
package cleanup
import (
"context"
"database/sql"
)
const batchSize = 500
func DeleteExpiredBatch(ctx context.Context, db *sql.DB) (int64, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
var acquired bool
if err := tx.QueryRowContext(ctx,
"SELECT pg_try_advisory_xact_lock($1)", 913701,
).Scan(&acquired); err != nil {
return 0, err
}
if !acquired {
return 0, nil
}
result, err := tx.ExecContext(ctx, `
WITH candidates AS (
SELECT id FROM events
WHERE expires_at < now()
ORDER BY expires_at, id
FOR UPDATE SKIP LOCKED
LIMIT $1
)
DELETE FROM events e
USING candidates c
WHERE e.id = c.id`, batchSize)
if err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, err
}
return result.RowsAffected()
}
This shape makes the audit question tractable: which run acquired the lock, which candidate range it attempted, how many rows it deleted, and whether it committed. Add a run identifier to structured logs, set a statement timeout outside the transaction, and measure rows claimed, transaction duration, lock waits, dead tuples, and backlog age. An index suitable for expires_at and the actual access pattern matters more than a heroic batch size; query plans should be reviewed against representative non-production data before the schedule is enabled.
Small commits have overhead. They also limit lock duration, rollback scope, and the amount of work that becomes ambiguous when a deployment stops a worker. The right batch size is empirical, and it can differ between a quiet primary and a database serving replicas or heavy writes. A long transaction that deletes until no rows remain feels tidy, but it converts ordinary retention work into an availability risk. The same discipline applies to the schedule itself: a run budget should leave enough room for the next invocation to start without inheriting an unbounded predecessor, and a deployment should stop claims before it terminates the process, then let the in-flight transaction either commit as one auditable unit or roll back. If cleanup has to delete related rows, the transaction boundary must reflect the referential rule rather than whichever table happens to be largest; otherwise a partial pass can preserve an orphan that the retention policy was meant to remove. If foreign keys, triggers, or vacuum pressure make a batch unexpectedly expensive, reduce its scope and observe the database again rather than treating retry frequency as proof of progress. The operator needs to distinguish a job that is safely working through a known backlog from one that is repeatedly doing no useful work. Rows claimed, rows deleted, elapsed time, and oldest eligible timestamp make that distinction visible. A single success/failure counter does not.
When does a queue change the recovery boundary?
Queues help when discovery and execution have different shapes. A scheduled pass can identify eligible account IDs and write outbox records in the same Postgres transaction. A publisher then sends those records, and consumers use the outbox ID to reserve or find a durable completion record. The outbox closes the otherwise ambiguous gap between committing application data and publishing a message.
For a queue-backed cleanup worker, an audit row should contain the logical work ID, attempt count, status, and the durable result of the side effect. The consumer first reserves that logical ID, performs only work that is still required, writes completion, and then acknowledges delivery. If delivery repeats, the next consumer observes the completion rather than repeating the side effect. This is an exactly-once effect pattern built on at-least-once delivery; it is not a claim that the broker delivers exactly once.
Visibility timeouts illustrate why the distinction matters. A received message is temporarily hidden from other consumers; if it is not deleted before the timeout expires, it may be delivered again. Timeout length should come from observed processing duration and should be extended only while a worker is making progress. A 429 response can include Retry-After, so a worker calling an external API should record a bounded next-attempt time instead of holding a database transaction open or letting every consumer retry in unison.
This is more machinery.
It is justified by isolation: account A can be delayed or retried without holding account B's cleanup hostage. It is not justified merely because queues sound more production-ready. Don't add a second recovery model until the first model has a measured boundary it cannot meet.
Compare operating cost by failure state
| Design | Durable recovery unit | Operational cost | Use it when |
|---|---|---|---|
| Scheduled Postgres batches | Committed candidate batch | Locking, query plans, run metrics | Expiration is database-local and bounded |
| Queue consumers | One logical work item | Delivery leases, idempotency records, backlog alarms | Items need isolated retries or independent concurrency |
| Scheduled outbox plus queue | Discovery batch and one work item | Both transaction and delivery operations | Discovery and execution have separate failure boundaries |
Direct service charges are only one input to the cheapest option. The more durable cost is the number of states an on-call engineer must reconcile: an uncommitted transaction, a completed message with a missing audit row, an expired lease, a poison item, or a backlog older than the retention objective. A scheduler with a database lock has fewer states. A queue makes more states explicit, which can be the correct trade when the workload is uneven.
Rate limits, deployment behavior, and observability belong in the comparison. Graceful shutdown should stop new claims before the process exits. Alerts should track the oldest eligible record and the retention deadline, not just a failed invocation. For queue consumers, also track oldest-message age, attempts per completed item, consumer saturation, and terminal failures. For scheduled deletion, track work remaining after the run budget and database pressure during the batch. These measures make a decision defensible without pretending that a universal cost ranking exists.
Roll out the smallest verifiable design
Begin with a dry-run query that counts eligible rows, then enable a modest batch under an explicit run deadline. Keep an audit trail of each run and verify that the next invocation resumes cleanly after an intentional cancellation in a non-production environment. Once the schedule is live, compare backlog age with the cleanup interval and inspect lock waits and query plans as data volume changes.
Move discovery into an outbox and introduce queue consumers only after evidence shows that record-level isolation, delayed retries, or independently scaled execution is required. The migration should preserve the same logical work ID from discovery through completion, so old scheduled batches and new consumers can be reconciled during the transition. There is no universal cheapest option; the economical architecture is the one whose failure states the team can audit, test, and operate within its retention window.
Top comments (0)