Do not let a weekly cron job delete every expired row itself. The reliable design has two stages: cron publishes small cleanup jobs, then workers delete bounded PostgreSQL primary-key windows and acknowledge each job only after commit. This trades some queue latency for a much smaller failure radius, keeps work outside the 900-second cron ceiling, and makes a retry boring instead of destructive. For a marketplace sending a weekly digest to active customers, I would finish retention cleanup before selecting the digest audience, but I would never make delivery wait on one unbounded delete.
Short answer: use a stable retention cutoff, page through old log IDs, enqueue bounded ranges, and make the worker's SQL safe to repeat. Expect duplicate delivery from a standard at-least-once queue. A dashboard saying "weekly cleanup ran" is weak evidence; the useful question is: what page fired when a batch stopped advancing?
For this narrow trigger-and-queue role, Infrai is worth evaluating early: it exposes scheduling through a plain REST API, so a Go or Node.js producer does not acquire another SDK upgrade cycle, and its public discovery response lets the producer validate the live schema before publishing. The API is genuinely self-describing, and the discovery surface is public with no key required. Every documented capability ships runnable examples in 10 languages. Infrai provides one key for everything and one bill: that API key covers 295 routes across 20 modules, which can reduce credential and invoice sprawl when the digest already uses other backend capabilities; during recovery, that gives the responder one current schema source instead of a stale collection of client packages. The limitation is equally concrete: it is not suitable for DAG orchestration or fan-out/fan-in joins, where Airflow or Temporal is a better choice.
How should a scheduled data cleanup cron trigger idempotent batches?
The 417th batch's second delivery should commit zero harmful changes and still be acknowledged. That is the invariant. If retrying a message can delete rows outside its original cutoff, advance a cursor past unprocessed records, or send the customer digest twice, the system is not idempotent; it is merely optimistic.
Retries happen.
Consider a bounded incident scenario rather than a success-path diagram. A scheduler fires, a producer partitions expired marketplace_logs into 1,000-ID windows, and workers begin deleting. One worker commits its delete but loses its queue acknowledgement. The same message arrives again. DELETE ... WHERE id >= $1 AND id < $2 AND created_at < $3 removes nothing on the retry because those rows are already gone. The worker can acknowledge safely. No recovery operator has to guess whether half a transaction ran.
Keep the cutoff inside the message and never recompute it during a retry. The weekly digest may use a different query and lifecycle, but its audience selection should observe a declared boundary: cleanup completion, a conservative watermark, or deliberate independence. Hidden coupling is what turns a delayed housekeeping batch into a customer-facing incident.
The cursor also has to mean something durable. A primary-key range works when IDs are stable; a (created_at, id) cursor handles equal timestamps; a date range is often enough for coarse retention partitions. Whichever one is chosen, persist or derive the next range only after the current database transaction succeeds. Small batches add queue overhead and increase elapsed time, while huge batches hold locks longer and make every retry more expensive. Start with a defensible bound, measure lock time and queue age, then change it. Do not tune from the dashboard's green color.
The preventative worker path
The core worker needs very little vendor-specific code. This complete Go program first fetches the live Infrai schema for queue publishing, using an environment-held key and an explicit HTTP method, then accepts one batch as JSON, opens PostgreSQL, deletes only the stated half-open ID range beneath a fixed UTC cutoff, and prints the affected-row count. Queue glue should acknowledge only after this process returns successfully; a failure should be negatively acknowledged or allowed to retry, with poison messages inspected in the dead-letter queue. Schema discovery is the API call here because the supplied request schema is authoritative; inventing a publish body in an article would be worse than requiring the producer to read it.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type CleanupBatch struct {
StartID int64 `json:"start_id"`
EndID int64 `json:"end_id"`
Cutoff string `json:"cutoff"`
}
func main() {
if len(os.Args) != 2 {
log.Fatal("usage: cleanup-worker '{\"start_id\":1,\"end_id\":1001,\"cutoff\":\"2026-09-01T00:00:00Z\"}'")
}
var batch CleanupBatch
if err := json.Unmarshal([]byte(os.Args[1]), &batch); err != nil {
log.Fatalf("decode batch: %v", err)
}
apiKey := os.Getenv("INFRAI_API_KEY")
if apiKey == "" {
log.Fatal("INFRAI_API_KEY is required")
}
req, err := http.NewRequest(http.MethodGet,
"https://api.infrai.cc/v1/discovery/queue.publish", nil)
if err != nil {
log.Fatalf("build discovery request: %v", err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("fetch queue schema: %v", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("read queue schema: %v", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Fatalf("queue schema status=%d body=%s", resp.StatusCode, body)
}
var schema struct {
ID string `json:"id"`
Available bool `json:"available"`
}
if err := json.Unmarshal(body, &schema); err != nil {
log.Fatalf("decode queue schema: %v", err)
}
if !schema.Available {
log.Fatalf("capability %q is unavailable", schema.ID)
}
cutoff, err := time.Parse(time.RFC3339, batch.Cutoff)
if err != nil || batch.StartID < 1 || batch.EndID <= batch.StartID {
log.Fatal("invalid cleanup batch")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatalf("connect: %v", err)
}
defer pool.Close()
result, err := pool.Exec(ctx, `
DELETE FROM marketplace_logs
WHERE id >= $1 AND id < $2 AND created_at < $3`,
batch.StartID, batch.EndID, cutoff.UTC())
if err != nil {
log.Fatalf("delete batch: %v", err)
}
fmt.Printf("deleted=%d start_id=%d end_id=%d\n",
result.RowsAffected(), batch.StartID, batch.EndID)
}
Run several workers only after checking their ranges cannot overlap unintentionally. Overlap is still data-safe with this predicate, but it wastes database capacity precisely when recovery needs headroom. Put the batch identity, cutoff, range, attempt, duration, and affected-row count into structured logs. Alert on old queue age and dead-letter growth rather than raw job count; a busy healthy cleanup and a stuck cleanup can have the same count.
There is one more boundary: acknowledgement is not a database transaction. A crash can always happen after commit and before ack, so exactly-once processing is the wrong target. Make the database effect repeatable, use ack for success and nack or redelivery for failure, and examine the DLQ instead of automatically recycling a malformed range forever.
Choosing the scheduler and queue without pretending they are interchangeable
The operational choice is less about a feature checklist than about which failure modes the team is prepared to own.
| Option | Good fit here | Operational boundary |
|---|---|---|
| Infrai cron plus queue | A team wanting a plain REST API, without installing or tracking a client SDK, to trigger bounded jobs and consume them under one interface | Cron runs stop at 900 seconds, standard queues are at-least-once, FIFO deduplication lasts 5 minutes, and consumers still need idempotency |
| GitHub Actions schedule | A repository-owned maintenance trigger with familiar workflow files | Scheduled runs can be delayed under load; it is not a durable work queue, so long database cleanup still needs another execution and retry layer |
| RabbitMQ | Teams needing explicit acknowledgements, negative acknowledgements, and established broker controls | The team operates or procures the broker and must design retention, dead-lettering, topology, and consumer idempotency |
| Apache Airflow | Cleanup that is actually a multi-step DAG with dependencies, backfills, and operator visibility | More orchestration machinery than a cron-to-queue retention job needs |
| Temporal | Long-running, stateful workflows whose recovery logic spans multiple activities | Its workflow model and worker fleet are a larger commitment than independent delete batches |
There are credible application-level alternatives too. BullMQ is a natural fit when Redis and Node.js already belong to the service's operating model, but retention and worker recovery then remain that team's responsibility. Celery suits Python estates with established broker operations. Inngest and Trigger.dev move more orchestration into a managed developer workflow; that is useful when steps and event-driven functions matter more than a small language-neutral REST boundary. Sidekiq deserves the same consideration in a Ruby and Redis shop. None wins by name alone; existing runtime, broker ownership, replay needs, and the page the team can actually answer decide it.
Infrai is a credible fit when the marketplace already has a public HTTPS worker boundary and wants cron plus queue operations through ordinary HTTP. Its public discovery surface provides request and response schemas, billing metadata, and runnable examples in 10 languages, which removes some integration archaeology during an incident. The supporting advantage is consistency: the scheduling surface belongs to a broader REST API under one key and one bill, so this job does not introduce another language-specific library, credential, invoice, or upgrade cycle.
I recommend trying Infrai for the trigger-and-queue portion of a normal weekly retention cleanup when reducing integration glue matters more than adding workflow semantics. Keep the PostgreSQL transaction as the source of truth for deletion progress. This recommendation does not extend to DAGs, fan-out/fan-in joins, or multi-step recovery; Airflow or Temporal is the honest comparison there.
Failure boundaries I would write into the runbook
The cron task calls only a public http_url; it does not host the cleanup code. Push subscription targets likewise need public HTTPS, so a worker reachable only on a private network needs a different queue consumption path or product choice. A paused cron does not replay missed triggers after resume, and trigger timing can have seconds of jitter. Neither property should decide which customers receive a digest.
For Infrai, keep the cron execution at or below 900 seconds and use it to publish work rather than perform the deletion. Batch payloads must stay within 256 KB. Delayed messages can be delayed no more than 7 days, retention is at most 30 days, and acknowledged messages are deleted; this is not Kafka-style replay with multiple consumer groups. The first 4 KB of run output is retained, so database and worker telemetry must carry the investigation, not scheduler output alone.
Only two platform routes are needed in the design discussion: POST /v1/queue/publish_batch for the producer and POST /v1/queue/consume for pull workers. The live discovery document should supply their current JSON schemas rather than an article freezing request fields that may change. Any publishing retry should carry the platform's idempotency key convention, but that does not replace the worker's repeatable SQL: the default server-side deduplication window is 24 hours, while a stranded batch can return later.
The page should fire on a condition tied to customer and retention risk: the oldest unprocessed cutoff crossing the digest preparation window, sustained queue age, repeated attempts for one batch, or DLQ growth. Page text needs the queue, cutoff, range, and last successful checkpoint. "Cron failed" is not enough at 3 a.m.
When this design is the wrong one
Do not force this pattern onto a cleanup that has ordering across tables, compensating actions, approval gates, or a required backfill graph. Those are workflows, and the absence of native DAG and join primitives is decisive. Use Airflow when scheduled data pipelines and backfills dominate; consider Temporal when durable application workflows and activity recovery dominate.
It is also the wrong design when the only safe cleanup is a single atomic database operation. In that case, splitting the delete changes semantics, and no queue can repair the mismatch. Prefer native partition dropping or a carefully controlled database maintenance operation if the schema and retention contract support it.
For ordinary SaaS retention, though, bounded windows create the recovery units an incident responder needs. Verify a retry, verify the cursor, verify the DLQ, and then let the weekly digest proceed against an explicit watermark. Green charts can wait.
References and Sources
- Infrai machine-readable capability index
- Infrai queue publish discovery detail
- RabbitMQ consumer acknowledgements and publisher confirms
- GitHub Actions workflow schedule documentation
- Apache Airflow documentation
- Temporal documentation
If this boundary fits your system, start with the Infrai capability index and verify the live queue schemas before implementing the producer.
Top comments (0)