6/10
Technical Architecture & AI Engineering · 7 min read

System Design: Distributed Job Scheduler and Dead-Letter Retry Queue

Design a 10M-jobs/day distributed scheduler with sub-1-second trigger accuracy, Postgres SKIP LOCKED lease acquisition, cron storm protection, and tenant-fair retries.

Why This Matters at Engineering Leadership Scale

SaaS platforms run millions of scheduled tasks daily: billing invoices, compliance scans, webhook retries, and nightly reports. Single-node cron or RAM-only Redis queues break at 10 million jobs/day: failovers silently drop pending jobs, 00:00 UTC cron storms crush databases, and one large tenant's 40,000 batch jobs starve every other customer's urgent tasks.

Designing a distributed job scheduler tests an engineering leader's grasp of lock-free leasing, at-least-once delivery with idempotency, cron thundering-herd jitter, and tenant fairness.

Core Mental Model & Architecture

Anchor capacity and storage math upfront:

  • Throughput & SLO: 10M scheduled jobs/day (~115 jobs/sec avg), spiking 20x at 00:00 UTC (~2,300 jobs/sec peak); trigger within <1s of due time; at-least-once execution with exponential backoff up to 5 retries + DLQ.
  • Storage Math: At ~1 KB/job row, 10M jobs/day = 10 GB/day (~300 GB for 30 days). Daily partitioning lets us DROP expired partitions instantaneously without expensive VACUUM bloat.
CoordinationThroughputOps OverheadCrash SafetyBest Fit
ZooKeeper LockLow (single leader)High (fencing, quorum)Slow electionSmall scripts
Redis ZSETVery High (50k/s)Moderate (AOF risk)Risky on OOMEphemeral retries
Time-Bucketed Postgres (SKIP LOCKED) + SQS (Chosen)High (5k to 10k/s sharded)Low (standard Postgres)Strong (ACID + lease reaper)SaaS billing & compliance jobs

Step-by-Step Implementation Tutorial

1. Separate Control-Plane Leasing From Execution

Keep DB lease acquisition <10ms; run all business logic outside the DB transaction.

text
PRODUCERS -> Scheduler API (validates cron/delay + shard_id 0..31) -> Time-Bucketed Postgres
STATELESS COORDINATORS (poll 250ms/shard):
  1. `FOR UPDATE SKIP LOCKED` claims 200 due rows (`DISPATCHED`, `lease_until = +60s`)
  2. Push envelopes to Tenant-Partitioned SQS/Kafka; Lease Reaper resets expired leases (>60s)
EXECUTION WORKERS:
  1. Per-tenant Redis semaphore -> Run with `idempotency_key` -> Mark `COMPLETED` (or next cron row)
  2. Transient error -> `NOW() + (2^attempts * 5s + jitter)`; `attempts >= 5` -> Monitored DLQ

2. Write the Time-Bucketed Schema and Lock-Free Lease Query

A partial index on WHERE status = 'PENDING' keeps completed history completely out of active coordinator scans.

sql
CREATE TABLE scheduled_jobs (
  job_id          UUID PRIMARY KEY,
  tenant_id       UUID NOT NULL,
  job_type        TEXT NOT NULL,
  payload         JSONB NOT NULL,
  cron_expr       TEXT,
  bucket_minute   BIGINT NOT NULL,   -- FLOOR(EXTRACT(EPOCH FROM run_at) / 60)
  shard_id        SMALLINT NOT NULL, -- hashtext(job_id::text) % 32
  status          TEXT NOT NULL CHECK (status IN ('PENDING', 'DISPATCHED', 'COMPLETED', 'DEAD_LETTER')),
  run_at          TIMESTAMPTZ NOT NULL,
  lease_until     TIMESTAMPTZ,
  attempts        SMALLINT NOT NULL DEFAULT 0,
  idempotency_key TEXT NOT NULL UNIQUE
);

CREATE INDEX idx_jobs_due_pending
  ON scheduled_jobs (shard_id, bucket_minute, run_at) WHERE status = 'PENDING';

-- Lock-Free Coordinator Lease Claim
WITH due AS (
  SELECT job_id FROM scheduled_jobs
  WHERE status = 'PENDING' AND shard_id = $1
    AND bucket_minute <= FLOOR(EXTRACT(EPOCH FROM NOW()) / 60) AND run_at <= NOW()
  ORDER BY run_at ASC LIMIT 200
  FOR UPDATE SKIP LOCKED
)
UPDATE scheduled_jobs j
SET status = 'DISPATCHED', lease_until = NOW() + INTERVAL '60 seconds', attempts = attempts + 1
FROM due d WHERE j.job_id = d.job_id
RETURNING j.job_id, j.tenant_id, j.job_type, j.payload, j.idempotency_key;

3. Handle the Minute-25 Curveball: Midnight Cron Storm + Mid-Job Worker Crash

"Two million daily reports are scheduled for 00:00 UTC, AND a worker crashes right after charging a customer's credit card before marking the job COMPLETED."

  1. Midnight Cron Storm: Apply deterministic cron jitter (offset_sec = murmurhash3(tenant_id + job_type) % 300) to spread non-exact daily schedules smoothly across 00:00 to 00:05. For strict exact-second triggers, 32 sharded coordinators push bursts into SQS/Kafka while capped worker pools drain smoothly without melting downstream DBs.
  2. Mid-Job Crash Recovery: After 60 seconds, the Lease Reaper reclaims the stuck job and redelivers it. Passing the scheduler's deterministic idempotency_key (invoice:{tenant}:{cycle}) to Stripe ensures the retry returns the original succeeded charge instead of double-billing.

4. Split Multi-Squad Ownership

  • Scheduler Control Plane Squad (5 engineers): Owns submission API, time-bucketed Postgres + partition pruning, SKIP LOCKED coordinators, lease reaper, and cron jitter engine.
  • Worker Runtime & Reliability Squad (5 engineers): Owns tenant-fair SQS/Kafka worker pools, Redis concurrency semaphores, exponential backoff + DLQ redrive UI, and idempotent worker SDK.

Worked Production Scenario: Before vs. After

A financial SaaS company ran scheduled billing and nightly syncs on a single Redis queue. A Redis failover silently dropped 18,000 scheduled jobs, and one large tenant's 40,000 midnight syncs delayed other customers' alerts by 35 minutes. Migrating to time-bucketed Postgres (SKIP LOCKED), cron jitter, per-tenant semaphores, and monitored DLQs solved both issues cleanly.

MetricBefore (Single Redis Queue)After (Postgres SKIP LOCKED + Fair Pools)Net Impact
Jobs Lost on Broker Failover18,000 (RAM loss)0 (ACID Postgres truth)100% durable scheduling
Midnight 00:00 UTC Trigger Lag35 minutes0.8 seconds (jitter + fairness)Meets <1s SLO
Duplicate Side Effects on Crash12/quarter0 (enforced idempotency_key)Safe at-least-once
Poison-Job Triage TimeHours in raw logs5 minutes (DLQ + 1-click replay)Fast recovery

Common Failure Modes & Anti-Patterns

1. Holding DB Locks Across Slow Business Logic

The trap: Keeping a Postgres transaction open while making a 10-second third-party HTTP call starves connection pools and blocks autovacuum. The structural fix: Keep lease acquisition strictly under 10ms (status = 'DISPATCHED') and run all execution outside the DB transaction.

2. Zero-Delay Retries Creating Self-Inflicted DDoS

The trap: Re-queuing failed jobs instantly hammers an already struggling downstream API until it stays permanently down. The structural fix: Always apply capped exponential backoff with full jitter and route exhausted jobs (attempts >= 5) to the DLQ.

3. Letting Completed History Bloat the Polling Table

The trap: Storing 6 months of COMPLETED rows inside the live table slows coordinator scans from 5ms to 800ms. The structural fix: Use partial indexes (WHERE status = 'PENDING') and automatically drop completed partitions older than 7 to 30 days.

How to Handle Pushback in the Room

Principal Engineer: "Polling Postgres every 250ms feels old-school. Shouldn't we build a custom distributed timing wheel?"

Calm Executive Response: "At 10M jobs/day, 32 sharded partial-index queries every 250ms consume under 8% of a mid-sized Postgres CPU while giving us ACID durability, instant job cancellation, SQL visibility, and zero consensus bugs. If we ever pass 100M jobs/day, we can layer a Redis timing-wheel hot cache in front of this exact Postgres store."

Product Manager: "Why can't the scheduler guarantee exact-once execution so engineers skip writing idempotency keys?"

Calm Executive Response: "Any worker can crash after calling an external API and before acknowledging the scheduler, so transport-level exact-once is impossible across networks. Our platform guarantees at-least-once delivery and injects a deterministic idempotency_key into the worker SDK so product teams get effective exact-once safety in two lines of code."

Key Takeaways & This Week's Action Rep

  • Use FOR UPDATE SKIP LOCKED on time-bucketed shards: Scale to thousands of jobs/sec with ACID durability and zero ZooKeeper locks.
  • Decouple <10ms leasing from worker execution: Buffer bursts in tenant-fair SQS/Kafka queues.
  • Defuse midnight cron storms with deterministic jitter: Spread non-exact daily jobs and enforce per-tenant worker caps.
  • Pair lease timeouts with idempotency keys and DLQs: Recover automatically from mid-job crashes without double-charging customers.
  • This Week's Action Rep: Audit every recurring job scheduled at 00:00 UTC in your stack, check if it passes an idempotency key to external APIs, and verify exhausted failures land in a monitored DLQ.