Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Distributed Job Scheduler
& Task Execution Platform.

Holding HTTP connections open for a 40-second report, video transcode, or payment reconciliation exhausts API server threads, triggers HTTP/LB timeouts, and turns client retries into duplicate work. A production job platform decouples a millisecond 202 Accepted submission API and durable control plane from isolated queues, capability-matched worker pools, fenced leases, bounded full-jitter retries, and Little's Law capacity sizing.
Start the journey5 stages· Last modified Dec 6, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When executing slow, flaky, scheduled, or retryable work at scale, decouple fast 202 submission and atomic control-plane scheduling from fenced, idempotent worker pools backed by isolated queues, jittered retries, and Little's Law sizing so slow or failing jobs never block clients or corrupt state.

TL;DR30-second simplified summary
▾

Synchronous request/response fails for slow, flaky, or periodic work: a 40-second report holds server threads, hits HTTP/LB timeouts, and causes client retries to run the same work twice.

A production platform splits the Control Plane (API gateway, submission/dedup, metadata DB, leader-elected scheduler, delay/recurring managers, priority router, worker registry, execution coordinator, retry/DLQ managers) from the Execution Plane (priority/delay/DLQ brokers, isolated CPU/I-O/GPU/memory/high-priority worker pools, heartbeats, cgroups, and artifact-first result/webhook delivery).

Every stage below preserves the exact state machines, queue eligibility rules, PostgreSQL SKIP LOCKED claims, Cron/DST uniqueness guards, worker node internals, fenced Java lease guards, 4-timeout and cancellation matrices, single-transaction idempotency SQL, DLQ replay workflow, and Little's Law sizing math.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Idempotency & At-Least-Once Execution
Because lease expirations, visibility timeouts, and crashes cause redeliveries, every job handler and state mutation must be safe under replay. (See idempotency-deduplication.)
Distributed Leases & Fencing Tokens
Time-bounded leases expire after GC pauses or crashes, while monotonic fencing tokens prevent a stalled worker from committing stale results. (See distributed-locking.)
Full walkthrough · 5 stages
01
RESHADED · R & H — WHY BACKGROUND JOBS, 5-LAYER ARCHITECTURE, CONTROL VS. EXECUTION PLANE & STATE MACHINESfoundation

Why Background Jobs, Layered Architecture & Job/Worker State Machines.

Why this matters: Establish why slow, flaky, retryable, or periodic work must run asynchronously, map the 5-layer 13-service architecture and 10-step happy path, separate control vs. execution planes, and define both the 10-state job machine and 6-state worker machine.

Why Background Jobs?

  • Synchronous flow: Client -> GET /report -> API server (~40s of work) -> 200 OK ... 40s later. User waits, HTTP/LB timeouts fire, server threads stay held, and client retries run the same work twice.
  • Asynchronous (job) flow: Client -> POST /jobs -> 202 Accepted + job_id in milliseconds while clients poll GET /jobs/{id} or receive a completion webhook.
  • Rule of thumb: Slow, flaky, retryable, or periodic -> make it a job (emails, reports, image/video transcoding, payment reconciliation, AI inference, periodic DB cleanup, rate-limited APIs). Every job must be idempotent.

5 Architectural Layers & 13 Core Services

  1. Client Layer: Web Apps, Mobile Apps, Backend Services, Admin Dashboard, External API Integrations.
  2. API & Submission Layer:
  • API Gateway: AuthN (API key / OAuth2 / mTLS), AuthZ (RBAC, tenant scope), per-tenant rate limiting, and schema/size validation.
  • Job Submission API: POST /jobs, GET /jobs/{id}, DELETE /jobs/{id} (cancel).
  1. Core Scheduling Services (scheduling = when; execution = who / how):
  • 1. Job Submission Svc: validate, assign job_id, dedupe by idempotency key
  • 2. Job Metadata Svc: PostgreSQL source of truth (job record + status)
  • 3. Scheduler Svc: decides when a job becomes eligible
  • 4. Delay Queue Mgr: holds jobs until run_at / backoff ends
  • 5. Recurring Job Mgr: cron definition -> job instances
  • 6. Priority Queue Mgr: priorities, weights, fairness
  • 7. Queue Dispatcher: routes eligible jobs to the right queue
  • 8. Worker Registry: live workers, capacity, capabilities
  • 9. Job Execution Coordinator: leases, heartbeats, timeouts, reaping
  • 10. Retry Manager: classify failure, backoff + jitter
  • 11. DLQ Manager: park exhausted jobs; replay / discard
  • 12. Result Storage Svc: persist outputs + artifacts
  • 13. Notification Svc: webhook / email / event on completion
  1. Queues & Worker Pools: Brokers (immediate, delayed / scheduled, high / normal / low, retry, DLQ) delivering to isolated worker pools (CPU, I/O, GPU, high-priority, general).
  2. Data Stores & Operations: PostgreSQL (metadata, history), Redis (heartbeats, locks, delay ZSET), Broker (Kafka / RabbitMQ / Redis), Object Storage (large payloads, artifacts), and Monitoring & Ops.

Control Plane vs. Execution Plane & State Machines

  • Why split them? Different scaling and failure domains: worker count follows queue backlog, while the Control Plane scales with job count and metadata writes.
  • Outage behavior: During a short control-plane outage, in-flight jobs keep running, nothing new becomes eligible, and results may need buffering. A highly available scheduler means exactly one instance claims each due job—never all instances.
  • Job States (10) vs. Worker States (6): Keep them strictly distinct. When a worker hits LOST from missed heartbeats, its job still reads RUNNING until the lease expires because the platform cannot tell slow from dead.

Sync vs. Async & Illustrative Job Record Payload

  • Sync (GET /report -> 40s -> 200 OK): User waits, LB/HTTP timeouts fire, server threads stay pinned, client retry runs the same work twice.
  • Async (POST /jobs -> 202 + job_id): Returns in milliseconds; slow work runs later on capacity the platform controls (and can safely retry).
{
  "job_id": "job_1024",
  "job_type": "generate_report",
  "payload": { "user_id": "user_42" },
  "priority": "high",
  "scheduled_at": null,
  "max_retries": 3,
  "timeout_seconds": 300
}
  • job_id: assigned by Submission Service; a client idempotency key can map to it.
  • scheduled_at: null means run as soon as capacity allows; a future timestamp places the job in SCHEDULED.
  • timeout_seconds: enforced per attempt, while max_retries bounds retries across failures.

10-Step Happy Path

  1. Client submits job (POST /jobs).
  2. Submission API validates payload and assigns job_id (deduping via idempotency key).
  3. Metadata DB persists the job record and attaches execution policy.
  4. Scheduler holds the job until due (if delayed/scheduled).
  5. Queue Dispatcher routes the eligible job to the target Job Queue.
  6. Worker Pool leases the job and executes it with a timeout watchdog and periodic heartbeats.
  7. Result Storage persists outputs/artifacts and sets status = SUCCEEDED.
  8. Notification Service sends a webhook/email, or the client polls GET /jobs/{id}.

Control Plane vs. Execution Plane Split

Plane Responsibilities Scaling Driver Outage Behavior
Control Plane (what / when / where) Job registration, scheduling & recurring config, queue/priority/retry/timeout policies, worker registration & health, job metadata, leader coordination & claims Job count & metadata write rate In-flight jobs continue running; nothing new becomes eligible; completion results may need buffering
Execution Plane (does the work) Job dispatch, queue consumption, worker pools, job execution, heartbeats, result persistence, retry re-enqueue, failure reporting Queue backlog & job duration Workers finish or drain active slots; expired leases are reclaimed once connectivity returns

Job & Worker State Machines

  • Job States (10): CREATED -> SCHEDULED (future run_at) or QUEUED (immediate) -> RUNNING (leased) -> SUCCEEDED / FAILED / TIMED_OUT -> RETRY_PENDING (retryable + attempts left; backoff elapsed -> QUEUED) or DEAD_LETTERED (exhausted / non-retryable). RUNNING -> QUEUED if lease expires (worker lost). CANCELLED is reachable from CREATED, SCHEDULED, QUEUED, RETRY_PENDING, or cooperatively from RUNNING. Not every job visits every state: immediate success is CREATED -> QUEUED -> RUNNING -> SUCCEEDED.
  • Worker Registry States (6): STARTING -> IDLE <-> BUSY -> DRAINING -> STOPPED | LOST (missed heartbeats).
COMPLETE JOB LIFECYCLE STATE MACHINE

All 10 Job States From Submission Through Retries, Cancellation & Dead-Lettering

future run_atnowdueleasedlease expired (worker lost)CREATEDValidated & persistedSCHEDULEDFuture run_atQUEUEDEligible in ready queueRUNNINGLeased by worker
02
RESHADED · S & A — QUEUE ROUTING, FAIRNESS, ATOMIC DUE-JOB CLAIMING, TIMING WHEELS & CRON / DSTintermediate

Queue Routing, Due-Job Discovery & Cron / Delay Scheduling.

Why this matters: Detail the 6 queue classes, priority vs. fairness (6:3:1 weighted round-robin, quotas, aging, isolation), leader/standby scheduling with PostgreSQL SKIP LOCKED vs. hierarchical time wheels vs. min-heap/Redis ZSET, and Cron/DST edge cases.

Queue Routing & Eligibility

Incoming work—new jobs (Submission Svc), due jobs (Scheduler), and retries (Retry Mgr)—enters the Job Router / Queue Dispatcher, which maps routing key -> queue name by job_type, priority, execution time (now vs. later), resource needs (CPU / GPU / mem), and tenant.

  • Key invariant: eligible != executed—a job eligible at 09:00 actually starts at 09:00 + queue wait + worker pickup.
  • Priority vs. Fairness: Strict priority drains high first and starves low-priority jobs under sustained load. Use weighted fair round-robin (e.g., 6 : 3 : 1 across High : Normal : Low with FIFO inside each queue), aging (bump jobs waiting too long), and queue isolation (so cleanup floods cannot delay payments).

Leader-Elected Scheduler & Atomic Due-Job Claims

  • Coordination: A Scheduler LEADER (elected via etcd / ZooKeeper / DB lease with ~10s TTL and monotonically increasing leader_epoch) runs a Due Job Scanner (~1s loop) + Job Dispatcher, while standbys watch the lease.
  • PostgreSQL vs. Redis ZSET: Use FOR UPDATE SKIP LOCKED on INDEX (status, run_at) in PostgreSQL, or a Redis ZSET (score = run_at) with an atomic Lua ZRANGEBYSCORE + ZREM move so two pollers never move the same job.
  • Leader crash or overlap: If the leader crashes, a standby wins (epoch 8) and scans durable DB rows (late, never lost). If two leaders overlap during a GC pause or partition, the atomic DB claim is the real guard and claimed_epoch acts as a fencing token on writes.

Outbox Gaps, Single Clock & Cron DST Rules

  • Crash after COMMIT before publish: A transactional outbox or reconciler re-publishes QUEUED but unenqueued rows. Because that can publish twice, workers must be idempotent.
  • Single clock rule: Compare run_at against one clock (the DB now()). NTP keeps hosts close, never identical, and skew grows under faults.
  • Cron definition != execution: Store 1 recurrence_definition row (tz = America/New_York, misfire_policy) and generate 1 job_instance row per fire time with UNIQUE (definition_id, fire_time). Configure DST spring-forward (02:30 missing -> skip or run at 03:00), DST fall-back (01:30 twice -> key on local wall time to run once), and misfire policy (fire once now (coalesce) | catch up, bounded | skip to next).

When Does a Job Become Eligible?

Queue Eligible When... Example
immediate As soon as a worker is free Send welcome email
delayed now + delay (relative time) "Remind in 30 min"
scheduled A fixed timestamp (absolute, explicit TZ) Publish 2026-12-05 09:00 UTC
recurring Each occurrence of a schedule -> a NEW job instance Nightly DB cleanup
priority Ordering among already-eligible jobs Payments before analytics
dead letter Never automatically — parked for people / tooling Failed 4 attempts
  • Weighted Fair Dequeue (6:3:1): e.g., [H H H H H H | N N N | L] where H = payment jobs, N = report generation, L = analytics & cleanup.

Atomic Due-Job Claim (Illustrative, PostgreSQL)

UPDATE jobs
SET status = 'QUEUED',
    claimed_epoch = :leader_epoch
WHERE job_id IN (
  SELECT job_id
  FROM jobs
  WHERE status = 'SCHEDULED'
    AND run_at <= now()
  ORDER BY run_at
  LIMIT 500
  FOR UPDATE SKIP LOCKED
)
RETURNING job_id;
  • INDEX (status, run_at) supports the scan; row locks + status guard ensure each due row is claimed by one scheduler.
  • Precision: poll_interval + queue_wait means run_at guarantees "not before", not "exactly at".

Finding Due Jobs: Three Implementations

Implementation Strengths Weaknesses
Database Scheduler (INDEX(status, run_at)) Durable, queryable, transactional claim; easy to inspect and cancel Polling load + index hot spot at "now"; precision bounded by poll interval
Hierarchical Time Wheel (tick = 1 s, slot = bucket of timers) O(1) insert and expire; handles millions of timers; expired bucket -> execution queue In-memory; needs durable store to rebuild after crash; long delays need overflow wheels
Priority Queue / Min-Heap (or Redis ZSET skiplist) O(1) peek next due; O(log n) insert/pop; sleeps until root is due Single-node in-memory cancel = lazy delete; ZSET is the shared, persistable variant

Cron, Recurrence & DST Edge Cases

  • Pipeline: Recurrence Definition (rec_id, cron, tz, misfire_policy, job_template) -> Cron Parser + Next Execution Calculator -> Scheduler (fire time reached) -> Job Instance Generator.
  • Definition != Execution: Definition is 1 row living for months (e.g., 0 9 * * MON-FRI, tz = America/New_York); Instance is 1 row per fire time with UNIQUE (definition_id, fire_time) (rec_77 @ 2026-12-07 09:00 America/New_York).
  • DST & Misfires:
    • Spring-forward (02:30 never happens): Skip or run at 03:00 per policy.
    • Fall-back (01:30 happens twice): Key instances on local wall time so it runs once.
    • Scheduler down 07:00-11:00 misses 09:00: Misfire policy (fire once now / coalesce | catch up, bounded | skip to next), computed from last_fired_at with the unique key making recovery safe to repeat.
SCHEDULER LEADER, ATOMIC CLAIM & PRIORITY QUEUES

Due-Job Promotion With Epoch Fencing, DB SKIP LOCKED / Redis ZSET & Weighted Queues

Job Routerpriority & tenantScheduler Leaderepoch fencingPriority Queues(6:3:1)High / Normal / LowScheduling DBFOR UPDATE SKIP LOCKEDDelay ZSET (Redis)atomic Lua moveimmediate workscheduled / cronatomic claim (epoch)promote score <= nowenqueue due jobs
03
RESHADED · H & D — WORKER INTERNALS, FENCED LEASES, CANCELLATION, FOUR TIMEOUTS & RESULT PERSISTENCEintermediate

Worker Pools, Leasing, Cooperative Cancellation & Four Timeouts.

Why this matters: Detail capability-matched worker pools, inside-the-node execution architecture, fenced job leases vs. distributed locks/heartbeats, cooperative cancellation, the 4-timeout matrix, and artifact-first result persistence.

Isolated Worker Pools & Inside One Worker Node

  • Dedicated pools: High-priority (reserved capacity, never shared), I/O-intensive (async, many slots/node), CPU-intensive (slots = cores), GPU (1 job/GPU), Memory-intensive (big RAM, few slots), and General-purpose.
  • Inside a worker (pool = cpu, concurrency = 8): Separate the fetch loop (prefetch = 1 for long jobs), heartbeat thread (+ lease renewal), timeout watchdog, and execution runtime (process pool for CPU/GIL bypass, thread pool for blocking I/O, async event loop for thousands of concurrent I/O waits).
  • Why a 2-hour transcode cannot block a 50 ms email: Separate queues + separate pools, per-pool concurrency limits, prefetch = 1, and per-attempt timeouts + cgroup CPU/memory limits.

Job Leasing, Fencing Tokens & Four Primitives

  • Job lease: Time-bounded right to run ONE job (~30s TTL), renewed every ~10s via heartbeats.
  • Distributed lock: Mutual exclusion on a shared resource (e.g., one cron run); also needs TTL + fencing.
  • Worker heartbeat: Liveness signal to Worker Registry (~5s interval, ~15s TTL); a missed heartbeat is not proof of death.
  • Job ownership: lease_owner + monotonic fencing token (41 -> 42). If Worker A pauses in GC past lease TTL, Worker B claims token 42, and the store rejects Worker A late writes (WHERE lease_token = 41).

Cancellation, Four Timeouts & Result Persistence

  • Cooperative cancellation (DELETE /jobs/{id}): Sets a cancel flag in DB/Redis; workers stop at the next checkpoint (or heartbeat reply) and run cleanup hooks before SIGTERM -> grace period -> SIGKILL.
  • Keep the 4 timeouts consistent: lease TTL and broker visibility timeout must strictly exceed several heartbeat intervals, or long jobs get redelivered while still running.
  • Result persistence (3 steps): 1. Upload large artifact to Object Storage (reports/job_1024.pdf) -> 2. One DB transaction (INSERT result row + UPDATE jobs SET status = 'SUCCEEDED' WHERE lease_token = 41 + outbox event) -> 3. Outbox relay triggers Notification Svc (webhook / email).

Four Distinct Timeouts

Timeout Measures Enforced By When It Fires
Job timeout Max runtime of one attempt Worker watchdog Attempt →\rightarrow TIMED_OUT
Heartbeat timeout Worker liveness Worker Registry Worker →\rightarrow LOST
Lease expiration Ownership valid without renewal Coordinator / DB Job becomes eligible again
Queue visibility timeout Broker hides a received message (e.g., SQS) Message Broker Message redelivered →\rightarrow possible duplicate

Cancellation Behavior by Current State

DELETE /jobs/{id} →\rightarrow cancel flag (DB / Redis) →\rightarrow worker checks at checkpoints (cooperative cleanup before SIGTERM →\rightarrow grace period →\rightarrow SIGKILL).

Situation What Happens
Queued job cancelled status -> CANCELLED; a worker that dequeues it re-checks status and skips it
Scheduled job cancelled Row →\rightarrow CANCELLED before run_at; scheduler claim (WHERE status = 'SCHEDULED') never matches
Running job cancelled Flag set; stops at next checkpoint (or heartbeat reply) →\rightarrow cleanup →\rightarrow CANCELLED (not instantaneous)
Worker unresponsive Heartbeats stop →\rightarrow lease expires →\rightarrow job requeued or failed per policy
Execution timeout Watchdog interrupts attempt →\rightarrow TIMED_OUT →\rightarrow retry policy decides

Fenced Job Lease Guard (Java)

import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public final class FencedJobLeaseManager {
    public enum JobState {
        CREATED, SCHEDULED, QUEUED, RUNNING, RETRY_PENDING, SUCCEEDED, FAILED, TIMED_OUT, DEAD_LETTERED, CANCELLED
    }

    public record LeaseRecord(String jobId, String ownerWorkerId, long fencingToken, long expiresAtEpochMs, JobState state) {}

    private final AtomicLong tokenGenerator = new AtomicLong(0);
    private final Map<String, LeaseRecord> records = new ConcurrentHashMap<>();

    public synchronized LeaseRecord acquireLease(String jobId, String workerId, long leaseTtlMs, long nowMs) {
        LeaseRecord current = records.get(jobId);
        if (current != null && current.state() == JobState.RUNNING && nowMs < current.expiresAtEpochMs()) {
            throw new IllegalStateException("Active lease still held for job " + jobId);
        }
        long nextToken = tokenGenerator.incrementAndGet();
        LeaseRecord next = new LeaseRecord(jobId, workerId, nextToken, nowMs + leaseTtlMs, JobState.RUNNING);
        records.put(jobId, next);
        return next;
    }

    public synchronized boolean commitCompletion(String jobId, long fencingToken, long nowMs) {
        LeaseRecord current = records.get(jobId);
        if (current == null || current.fencingToken() != fencingToken || nowMs > current.expiresAtEpochMs()) {
            return false; // Reject stale or expired lease attempt (e.g., token 41 < 42)
        }
        records.put(jobId, new LeaseRecord(jobId, current.ownerWorkerId(), fencingToken, nowMs, JobState.SUCCEEDED));
        return true;
    }

    public static void main(String[] args) {
        FencedJobLeaseManager mgr = new FencedJobLeaseManager();
        long t0 = Instant.now().toEpochMilli();
        LeaseRecord lease1 = mgr.acquireLease("job_1024", "worker-a", 30_000L, t0);
        // Worker A stalls in GC past 30s lease expiration; Worker B takes over with higher fencingToken
        LeaseRecord lease2 = mgr.acquireLease("job_1024", "worker-b", 30_000L, t0 + 35_000L);
        boolean staleCommit = mgr.commitCompletion("job_1024", lease1.fencingToken(), t0 + 36_000L);
        boolean validCommit = mgr.commitCompletion("job_1024", lease2.fencingToken(), t0 + 36_100L);
        System.out.println("staleCommit=" + staleCommit + ", validCommit=" + validCommit);
    }
}
LEASE EXPIRATION & FENCING TOKEN GUARD

Worker A Stall, Lease Expiry, Worker B Takeover & Stale Write Rejection

Worker ACoordinator & DBWorker B1. Claim job_1024 (lease 30s,token 41)2. Renew lease every ~10s; then GCpause / crash3. lease_until passes -> reaper sets…4. Claim job_1024 (token 42)5. Late commit WHERE lease_token =41 -> REJECTED (41 < 42)

Lease expiry alone does not prove Worker A stopped; monotonic fencing tokens checked by the store block stale writes.

04
RESHADED · D & E — FAILURE CLASSIFICATION, FULL JITTER, DLQ REPLAY, CRASH MATRIX & IDEMPOTENT SQLadvanced

Retries, Exponential Backoff + Jitter, DLQ & Idempotency.

Why this matters: Classify transient vs. permanent failures, bound cascading retries with full jitter and retry budgets, separate DLQ from delayed retry queues with manual replay, and enforce idempotency inside one DB transaction.

Failure Classification & Bounded Retries

  • Transient vs. Retryable: Transient describes the fault; retryable is a policy decision. A timed-out payment call is transient yet unsafe to retry without an idempotency key.
  • Durable attempt counter: Store attempt_count in the durable job record (never in worker memory) so it survives crashes and redeliveries.
  • Exponential backoff with full jitter: delay(n) = random(0, min(cap, base * 2^(n-1))) (e.g., base 2s -> 2s, 4s, 8s, 16s) spreads 10k failing jobs out instead of triggering a thundering herd.
  • Stop retry amplification: jobs (x4) -> Service A (x4) -> payments API = 16 calls per job. Retry at one layer only, bound max_attempts + overall deadline, and enforce a circuit breaker / retry budget (retries <= 10% of calls).

Dead Letter Queue (DLQ) & Triage Actions

  • DLQ != Delayed Retry Queue: Delayed retry is automatic and part of normal execution; DLQ is terminal parking with long retention, restricted PII access, and zero automatic consumers (auto-replaying DLQ forever is an infinite retry loop).
  • DLQ record fields: job_id, original_queue, job_type, original_payload (or pointer), failure_reason + error_stack, attempt_count, first/last_failure_time, and worker_id + code_version.
  • Triage actions: Replay (same payload + same idempotency key, fresh attempt budget, rate-limited), Reprocess (corrected payload -> new job referencing the original), or Discard (invalid forever; recorded in audit log).

Idempotency & Duplicate Execution

  • 4 ways a job runs twice: (1) worker performs side effect, crashes before ack; (2) lease/visibility timeout expires during a long task; (3) scheduler outbox/reconciler re-dispatches after crash; (4) client retries submission after timeout.
  • Idempotency key: Derive from business intent (e.g., payment_reconciliation:user_1024:2026-12-04), never from attempt ID, and enforce UNIQUE (tenant, key) at submission.
  • Honest boundary: "Exactly-once" holds only inside one transaction boundary you control (BEGIN ... ON CONFLICT DO NOTHING ... UPDATE ... INSERT outbox ... COMMIT)—never for external emails or third-party card charges (use Idempotency-Key headers where supported).

Failure Classification & Retry Policy Matrix

Failure Nature Retry?
Timeout, connection reset Transient Yes — if the operation is idempotent or carries an idempotency key
HTTP 503 / 429 Transient Yes — back off; honor Retry-After
DB deadlock / serialization error Transient Yes — re-run the whole transaction
Validation error, malformed payload Permanent No →\rightarrow DLQ immediately
Referenced record deleted (404) Permanent No →\rightarrow discard or DLQ (policy)
401 / 403 (bad credentials) Permanent until fixed No →\rightarrow DLQ + alert a human

DLQ vs. Delayed Retry Queue & 5-Step Manual Replay

  • Delayed Retry Queue != DLQ: Delayed retry is automatic, time-delayed, and part of the normal flow; DLQ is terminal parking with long retention, restricted access (payloads may hold personal data), and no automatic consumer (auto-replaying DLQ forever is an infinite retry loop with extra steps).
  • DLQ Record Fields: job_id, original queue, job type, original payload (or pointer), failure reason + error stack, attempt count, first/last failure time, worker id + code version.
  • Handling Options: Manual dashboard inspection, automated grouping by error fingerprint, Replay (same payload + same idempotency key, fresh attempt budget, rate-limited), Reprocess (corrected payload →\rightarrow NEW job referencing original), or Discard (recorded in audit log).
  • Manual Replay Workflow: 1. alert: DLQ growing →\rightarrow 2. group + find root cause →\rightarrow 3. fix + deploy →\rightarrow 4. replay in small batches →\rightarrow 5. monitor: new failures go back to the DLQ.

Crash Recovery at a Glance

  • Scheduler crashes: Standby wins the leader lease; due jobs are durable rows, so they fire late, not lost.
  • Worker crashes: Heartbeats stop →\rightarrow lease expires →\rightarrow reaper requeues →\rightarrow another worker claims with a new token.
  • Broker restarts: Durable queues keep unacked messages and redeliver them →\rightarrow possible duplicates.
  • Metadata DB fails over: Claims and status writes are transactional; uncommitted ones are simply redone.

Idempotent Consumer (Illustrative SQL, One DB Transaction)

BEGIN;
INSERT INTO executions (idem_key, job_id, status)
VALUES (:key, :job_id, 'done')
ON CONFLICT (idem_key) DO NOTHING; -- 0 rows => already done, stop

UPDATE accounts SET balance = balance - :amount WHERE id = :account_id;
INSERT INTO outbox (event_type, payload) VALUES ('job_completed', :payload);
COMMIT;
CASCADING RETRIES VS. JITTERED BACKOFF + DLQ + IDEMPOTENCY

Eliminating 16x Retry Amplification & Duplicate Side Effects

Before · Multi-Layer Unpaced Retries
  • 4 x 4 = 16x retry amplification
  • Synchronized retry waves at 2s/4s/8s/16s
  • Duplicate charges on crash before ack
After · Single-Layer Full Jitter + DLQ + Idempotency
  • Retry budget capped (<= 10% of calls)
  • Full jitter random(0, delay) spreads load
  • ON CONFLICT (idem_key) stops duplicates
Engineering Decision Framework
Problem
How to keep retries and crash recovery safe when downstream services slow down or workers crash mid-flight.
Naive Solution
Retry failed jobs immediately at both API and worker layers without idempotency keys or a DLQ.
Why It Fails
Multi-layer retries amplify outages (4 x 4 = 16x load), synchronized retries cause thundering herds, and crashes before ack execute non-idempotent side effects twice.
Alternatives
Compare immediate multi-layer retries vs. single-layer capped exponential backoff with full jitter + DLQ + transactional idempotency keys.
Engineering Decision
Retry at one layer only with full-jitter backoff and a retry budget, park exhausted/permanent failures in a DLQ, and gate DB side effects with ON CONFLICT idempotency keys.
Trade-Offs
Requires storing execution dedup records and operating a manual DLQ replay workflow in exchange for outage stability and safe replays.
Decision Exercise · Make the Call

A downstream payments API starts timing out for 500 jobs/min. Worker retries 3 times AND Service A retries 3 times without jitter or an idempotency key. What happens?

05
RESHADED · E & D — CAPACITY MATH (LITTLE'S LAW), DRAINING, GOLDEN SIGNALS & SANDBOXINGadvanced

Capacity Math (Little's Law), Autoscaling, Observability & Security.

Why this matters: Provide worked Little's Law worker sizing, graceful SIGTERM draining, golden-signal observability metrics, multi-tenant sandboxing, and when not to build a custom scheduler.

Capacity Sizing With Little's Law

Queue depth alone never tells you how many workers you need: 1,000 jobs taking 10 ms drain in seconds, while 1,000 jobs taking 10 minutes require hundreds of concurrent slots. Always size each worker pool using Little's Law:

  • required_slots = (arrival_rate * average_duration) / target_utilization

Autoscaling, Graceful Draining & Golden Signals

  • Autoscale on queue lag, not CPU alone: Scale on oldest queued job age and queue-depth-per-slot, because I/O-bound workers sit at low CPU while blocked on downstream APIs.
  • Graceful draining (SIGTERM): Transition worker to DRAINING, stop claiming new jobs, finish or checkpoint in-flight work before the grace timeout, and explicitly release uncompleted leases.
  • Observability: Track job counts by state, schedule_lag = actual_start_at - run_at, oldest queued age, duration percentiles (p50/p95/p99), lease/heartbeat expirations, and DLQ growth—propagating trace_id end-to-end.

Multi-Tenant Security & When Not to Build This

  • Isolation & security: Enforce mTLS/OAuth2 + RBAC at the gateway, per-tenant submission rate limits and queue quotas, microVM/gVisor sandboxing with read-only root filesystems, egress allowlists, and short-lived scoped credentials.
  • Operational economics: If volume is modest or workflows live on a single primary DB, a managed queue (SQS / Cloud Tasks) or Postgres SKIP LOCKED / Temporal setup beats operating a custom distributed scheduler.

Worked Little's Law Capacity Sizing (Illustrative)

Formula: required_slots = (arrival_rate * avg_duration) / target_utilization

Pool Arrival Rate (lambda) Avg Duration (W) Target Utilization Required Concurrent Slots
Notifications (I/O) 500 jobs/s 0.2 s 0.70 (500 * 0.2) / 0.70 ≈ 143 async slots
PDF Reports (CPU) 20 jobs/s 15 s 0.75 (20 * 15) / 0.75 = 400 CPU slots
Video Transcode (GPU) 0.5 jobs/s 120 s 0.80 (0.5 * 120) / 0.80 = 75 GPU slots

Observability Golden Signals & Alerts

  • Schedule Lag (actual_start_at - run_at): Alerts when the Scheduler Leader or DB poll cannot keep up with due jobs.
  • Oldest Queued Age: Detects queue starvation in low-priority or tenant-isolated queues before SLAs breach.
  • Lease Expiration / Reap Rate: Spikes indicate GC pauses, OOM kills, or network partitions in worker pools.
  • DLQ Growth Rate: Alerts on rising permanent/exhausted failures grouped by error fingerprint.
ChoiceWhat it buysWhat it costs
Managed Queue (SQS / Cloud Tasks) or DB SKIP LOCKED + Worker PoolMinimal operational toil; strong transactional consistency with existing DB Sufficient for < 1,000 jobs/s without complex cron/fairness needsDB polling hits index contention at very high due-job trigger rates Limited multi-tenant fairness and custom timing-wheel precision
Control/Execution Split + Partitioned Timing Wheels + Multi-Pool WorkersHandles high due-job volume, weighted fairness (6:3:1), and workload isolation Scales horizontally via hash(job_id) scheduler shards and per-pool autoscalingHigher infra & operational cost (leaders, brokers, stores, registries, DLQ tooling) Requires strict fencing-token and idempotent-consumer discipline
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

Why should a distributed job platform separate the control plane from the execution plane?

Recommended Learning Flow