Architecting a Distributed Asynchronous Job Execution System
System DesignModel answerLast updated
Design a scalable, fault-tolerant job scheduler that manages delayed execution, recurring tasks, worker leasing, and failure recovery with at-least-once delivery.
Design an asynchronous background job processing system capable of executing tasks at a designated future time or on a recurring schedule.
Requirements & Functional Scope
- Task Lifecycle & Types: Support one-time delayed tasks (e.g., send an email in 2 hours) and recurring CRON-like tasks (e.g., generate a daily analytics report).
- Execution Guarantees: Provide at-least-once delivery. Tasks must not be dropped due to application crashes or network partitions. Workers acquire tasks via dynamic leases to handle execution timeouts.
- Task Operations: Support task scheduling, cancellation, retry strategies (with exponential backoff), and tracking job status.
- Scalability & Performance: Assume a target scale of 10,000 tasks per second with execution latency within seconds of the scheduled run time.
Deliverables
Provide a high-level architecture diagram (ASCII/Text), data model, core workflow mechanisms (polling vs. pushing, handling concurrency and race conditions), worker lease/heartbeat mechanisms, and failure handling strategies.
Hints
Hint 1
Consider how to efficiently index tasks by run time to avoid full-table scans when searching for pending execution targets.
Hint 2
Think about how multiple worker nodes prevent claiming the same job simultaneously without relying on heavy distributed locking overhead.
Hint 3
Distinguish between one-off scheduled jobs and recurring tasks when updating state post-execution.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Architecture
The system consists of three main tiers: the API Layer, the Scheduling & Data Layer, and the Worker Fleet.
+-------------------+
| Client App / |
| Upstream Service|
+---------+---------+
|
v
+---------------------+
| Scheduler API |
+----------+----------+
|
+-----------+-----------+
| |
v v
+--------------------+ +-------------------+
+ Task Storage (RDBMS| | Delay Queue / |
| / Key-Value Store) | | Time Index (Redis)|
+---------+----------+ +---------+---------+
^ ^
| |
+-----------+------------+
|
v
+----------------------+
| Worker Fleet |
| (Executors/Leasers) |
+----------------------+
Components
- Scheduler API: Handles task submission, status retrieval, and explicit task cancellations.
- Task Store: Durable persistence layer storing task metadata, payload, execution history, and state (RDBMS like PostgreSQL or a distributed KV store like Cassandra/DynamoDB).
- Time-Wheel / Delay Queue Index: A fast, indexed structure (e.g., Redis Sorted Sets or Kafka delayed topics) used to fetch tasks whose target execution timestamp (
scheduled_at <= NOW()) is reached. - Worker Fleet: Staters processors that claim task execution leases, execute the business logic, send heartbeats, and mark tasks as complete or failed.
2. Data Model & Schema
A relational schema (e.g., PostgreSQL) cleanly enforces state transitions and transactional updates:
CREATE TYPE task_state AS ENUM ('PENDING', 'RUNNING', 'COMPLETED', 'FAILED', 'CANCELLED');
CREATE TABLE tasks (
task_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
payload JSONB NOT NULL,
state task_state NOT NULL DEFAULT 'PENDING',
scheduled_at TIMESTAMPTZ NOT NULL,
cron_expression VARCHAR(64), -- NULL for one-time tasks
max_retries INT NOT NULL DEFAULT 3,
current_retry INT NOT NULL DEFAULT 0,
lease_owner VARCHAR(128),
lease_expires_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Index for scheduled execution lookup
CREATE INDEX idx_tasks_fetch ON tasks (scheduled_at, state)
WHERE state = 'PENDING';
-- Index for detecting timed-out worker leases
CREATE INDEX idx_tasks_lease_timeout ON tasks (lease_expires_at)
WHERE state = 'RUNNING';
3. Core Task Execution Workflow
A. Task Creation
- The client calls
POST /taskswith payload, target time (scheduled_at), or CRON expression. - The API persists the record in the
taskstable withstate = 'PENDING'. - If the run time is in the immediate future (e.g., within 30 seconds), the task ID is also added to a Redis Sorted Set (
ZADD scheduled_tasks <scheduled_at_timestamp> <task_id>).
B. Task Acquisition & Atomic Leasing
To ensure workers do not conflict or double-process tasks simultaneously, we use atomic update leasing:
UPDATE tasks
SET state = 'RUNNING',
lease_owner = 'worker-node-42',
lease_expires_at = NOW() + INTERVAL '30 seconds',
updated_at = NOW()
WHERE task_id IN (
SELECT task_id
FROM tasks
WHERE state = 'PENDING'
AND scheduled_at <= NOW()
ORDER BY scheduled_at ASC
FOR UPDATE SKIP LOCKED
LIMIT 100
)
RETURNING task_id, payload, current_retry;
SKIP LOCKEDallows concurrent worker threads to grab distinct batches of ready tasks without blocking each other or causing database deadlocks.
C. Worker Heartbeat & Lease Renewal
- For long-running operations (longer than the initial 30-second lease), active workers send periodic heartbeats (
UPDATE tasks SET lease_expires_at = NOW() + INTERVAL '30 seconds' WHERE task_id = ? AND lease_owner = ?). - If a worker process crashes, its lease expires automatically after 30 seconds.
4. Retries & Recurring Schedules
Retry Strategy (Exponential Backoff with Jitter)
When execution fails:
- Increment
current_retry. - If
current_retry < max_retries:- Calculate next run:
next_run = NOW() + base_delay * (2 ^ current_retry) + random_jitter. - Set
state = 'PENDING',scheduled_at = next_run, and resetlease_owner = NULL.
- Calculate next run:
- If max retries are exceeded:
- Transition
state = 'FAILED'. - Trigger Dead Letter Queue (DLQ) notifications for monitoring.
- Transition
Recurring (CRON) Tasks
Recurring tasks should follow a single active instance or generator pattern:
- When a recurring task completes successfully, compute the next execution time based on
cron_expression. - Insert a new task instance with
scheduled_at = next_cron_timeor update the current task instance back toPENDINGwith the new timestamp. - Updating the existing task record prevents record bloat, while logging history to an audit table provides observability.
5. Fault Tolerance & Edge Cases
| Scenario | Recovery Mechanism |
|---|---|
| Worker Crash mid-task | A background system process sweeps tasks where state = 'RUNNING' AND lease_expires_at < NOW(). These tasks are reset to PENDING to be reclaimed by healthy workers. |
| Database Network Partition | Workers stop renewing heartbeats. The storage layer assumes the lease expired and re-assigns the job once connection is restored. |
| Duplicate Delivery / Idempotency | Because network delays can cause duplicate executions (at-least-once delivery), task payloads should carry an idempotency_key. Upstream task execution logic must verify if idempotency_key was already applied. |
| Hotspotting on Time Triggers | Distribute execution load using Redis Sorted Set sharding by hash(task_id) % num_partitions. |
6. Trade-Offs & Scalability Options
-
RDBMS (SKIP LOCKED) vs. Redis + KV:
- RDBMS: Provides strong consistency, simplified retry state management, and ACID guarantees out of the box. Scales easily up to tens of thousands of tasks/sec with appropriate indexing.
- Redis + Distributed Locks: Offers lower latency and higher throughput (>100k tasks/sec), but requires manual handling of persistence, replication, and split-brain scenarios.
-
Push vs. Pull Architecture:
- Pull (Polling): Workers query storage periodically. Simpler, but can introduce latency or poll overhead if intervals are inefficient.
- Push (Timer-Wheel/Broker): A central coordinator pushes ready tasks to workers via gRPC/WebSockets. Lowers latency, but increases coordinator complexity and failure-mode handling.