Short answer: use a cron trigger to create a bounded cleanup job, let a queue consumer process it in small PostgreSQL transactions, and make the database receipt the authority for completion. Redis TTL can remove a second lookup path, but it should not be the only record when a customer-support system must explain which expired session or token was removed and why.

The important distinction is between scheduling and delivery. A cron expression says when to ask for work; it does not say that old user sessions were deleted, that expired tokens were visited, or that a public webhook was delivered exactly once. For a backend that handles support events, a retry is normal traffic, not an exceptional event. The design therefore needs an exactly-once effect even though the trigger, webhook, and queue each provide at-least-once delivery.

The architecture decision record: define the receipt first

The cleanup job should carry a deterministic job_id, an expiry cutoff, and a bounded scope such as a tenant or primary-key interval. It should not carry a snapshot of every row selected for deletion. The scheduler or public webhook authenticates the request, records the intent, and enqueues that small description. A worker reads the description, selects rows from PostgreSQL using the stored expires_at, deletes a batch, inserts a receipt in the same transaction, and acknowledges the queue message only after commit.

That sequence gives every stage a failure boundary. A process may die before enqueueing, after enqueueing, after the database commit, or after the queue acknowledgement. The receipt makes the third case harmless: a redelivery finds the completed job_id and records no second deletion. The database remains the authority for expiry and completion, while the queue is responsible for carrying work.

Three words: receipt before acknowledgement.

The first version should be report-only. Record the cutoff, candidate count, tenant, and range, then compare those results with an independent query for several runs before enabling destructive deletes. I would also keep the request ID, queue message ID, worker attempt, committed count, and completion time in an audit trail; a green cron history is too small an explanation for a deletion that a support agent may need to defend later.

The trade-offs are architectural, not cosmetic:

Option Good fit Boundary to accept
PostgreSQL job table plus cron The database team owns expiry, leases, and audit records Cleanup shares resources with the primary database, so batch size and vacuum pressure need monitoring
Redis TTL plus a queue Fast session invalidation and a Node.js worker already use Redis Expiration notifications and key retention are not a substitute for a durable deletion receipt
PostgreSQL outbox plus queue The enqueue decision must commit with application state A relay process and replay handling add operational work
Durable workflow engine Cleanup has timers, fan-out, joins, or compensation A workflow runtime is more machinery than a single bounded sweep needs

There is no universal winner. Choose the smallest mechanism that preserves the evidence your retention and compliance rules require.

How should Node.js cron cleanup handle expired sessions, tokens, queues, and a public webhook?

Keep the Node.js HTTP handler boring. It validates the method and authentication, computes a cutoff from a trusted clock, creates an idempotency key, and returns only after the job is durably queued. It should not scan a user-session table or wait for the queue consumer to delete anything. A public webhook endpoint is a trigger surface, not a worker.

The endpoint's response also needs a precise meaning. 202 Accepted can mean that the bounded job was durably accepted; it must not be presented as proof that cleanup finished. If enqueueing cannot be confirmed, return a failure that causes the caller to retry, and make that retry resolve to the same job_id. Never derive the idempotency key from a random request ID if two cron invocations for the same cutoff should represent one cleanup run.

An old session and an expired token deserve the same expiry discipline, although they need not share a table or delete transaction. The worker can process each relation in bounded batches, record separate counts, and advance a cursor. If a tenant has a large backlog, enqueue the next cursor as a continuation job. That keeps locks short and gives operators a visible unit of progress.

Redis TTL is useful for making a session unavailable quickly. It is a poor audit log: key eviction does not by itself provide the business context of who requested cleanup, which cutoff was applied, or whether a token was also revoked in PostgreSQL. Treat TTL as a serving optimization or a safety net; persist the policy decision where reconciliation can query it.

What does an exactly-once cleanup path look like in code?

The following Go sketch shows the critical path without tying it to a queue product. publish and next are adapters. The correctness contract is the same for a Redis-backed queue, a database-backed queue, or a managed queue: the worker commits the receipt before it acknowledges delivery.

package main import ( "context" "crypto/sha256" "encoding/hex" "net/http" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) type CleanupJob struct { ID string Cutoff time.Time Tenant string } type Delivery struct { Job CleanupJob Ack func() error } func idFor(tenant string, cutoff time.Time) string { sum := sha256.Sum256([]byte(tenant + "\x00" + cutoff.UTC().Format(time.RFC3339))) return tenant + "-" + hex.EncodeToString(sum[:12]) } func trigger(w http.ResponseWriter, r *http.Request, publish func(CleanupJob) error) { if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } cutoff := time.Now().UTC().Truncate(24 * time.Hour) job := CleanupJob{Tenant: "support", Cutoff: cutoff} job.ID = idFor(job.Tenant, job.Cutoff) if err := publish(job); err != nil { http.Error(w, "queue unavailable", http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusAccepted) } func consume(ctx context.Context, db *pgxpool.Pool, next func() (Delivery, error)) error { for { delivery, err := next() if err != nil { return err } tx, err := db.Begin(ctx) if err != nil { return err } var completed bool err = tx.QueryRow(ctx, "select exists (select 1 from cleanup_receipts where job_id = $1)", delivery.Job.ID, ).Scan(&completed) if err == nil && !completed { _, err = tx.Exec(ctx, "delete from user_sessions where tenant = $1 and expires_at < $2 limit 1000", delivery.Job.Tenant, delivery.Job.Cutoff) } if err == nil && !completed { _, err = tx.Exec(ctx, "insert into cleanup_receipts(job_id, cutoff, completed_at) values ($1, $2, now())", delivery.Job.ID, delivery.Job.Cutoff, ) } if err == nil { err = tx.Commit(ctx) } else { _ = tx.Rollback(ctx) } if err != nil { return err } if err := delivery.Ack(); err != nil { return err } } } var _ = pgx.ErrNoRows 

The SQL is a sketch, not a claim that every PostgreSQL deployment accepts a LIMIT directly on DELETE; use the database's supported bounded-delete form, normally a keyset-selected subquery, and test it against the schema and indexes you actually run. That detail matters because a correct idempotency key does not protect a transaction that locks the entire table. I have seen teams spend a day proving duplicate suppression while the real incident was a cleanup query that held locks past the webhook timeout.

The receipt should include the cutoff and useful scope fields, with a unique constraint on job_id. If sessions and tokens are handled separately, use distinct receipt kinds or separate rows so a retry can determine exactly which work committed. A worker crash after commit but before Ack is the test that proves the design; the second delivery must do no destructive work.

Which failure tests should decide the scheduling design?

Run the failure matrix before production:

  • Deliver the same job twice and assert one receipt and one effective deletion.
  • Stop the worker immediately after commit and verify that redelivery is harmless.
  • Accept a webhook, lose the worker, and alert when no receipt appears within the expected interval.
  • Run two cleanup workers for the same tenant and verify that row selection and receipt insertion remain safe under concurrency.
  • Reconcile the count of expired rows remaining past policy with the committed deletion counts.

The monitoring should distinguish accepted triggers, queued jobs, worker attempts, committed receipts, and rows still expired. Those signals answer different questions. A successful webhook with an empty receipt stream means “the trigger worked,” not “the cleanup worked.”

Cron also has a semantic limit: it supplies a time-based invocation, not a durable history of all work that a service forgot to perform. A paused schedule may not recreate every missed invocation, so the job table or queue must provide replay and the operator must know how to issue a bounded backfill. If the business rule requires durable timers, multi-step state, or compensation, a workflow engine is a better boundary than a clever cron expression.

Don't promise exactly-once delivery to a downstream customer-support endpoint. Promise an exactly-once effect inside your own cleanup ledger, and give downstream webhook consumers their own idempotency key. The distinction is small in wording and large in an audit.

The rejected option and the valid use case

I would reject a single cron command that runs DELETE for every expired session and token, then reports success from the scheduler. It has no durable handoff, no stable replay unit, and no reliable way to tell “nothing was due” from “the process stopped halfway.” It is acceptable only for a small, disposable table whose loss can be rebuilt and whose deletion needs no audit trail; that is not the usual posture for customer-support sessions or authentication tokens.

I would also reject Redis TTL as the complete retention policy when PostgreSQL is the system of record. TTL is a good answer to fast invalidation, and it can reduce read pressure, but it cannot replace a receipt with scope, cutoff, and operator-visible reconciliation. Use it alongside the authoritative store when latency matters.

The final decision rule is direct: use cron for the nudge, a queue for bounded delivery, PostgreSQL for expiry and receipts, and Redis TTL only where fast serving behavior justifies a second mechanism. If the workload becomes a workflow graph or needs replayable event history, choose a workflow engine or an event log instead. Your mileage will vary with table size, retention law, and network topology; those constraints should change the design, not be hidden behind a green schedule.

References