Design a Scalable Distributed Task Processing Engine
System DesignModel answerLast updated
Design an architecture for a multi-tenant distributed task execution platform handling millions of parallel jobs, emphasizing fault tolerance, scheduling, leases, and idempotency.
Architect a distributed task processing engine capable of executing large-scale batch jobs composed of independent, heterogeneous tasks across a multi-tenant compute cluster.
Requirements & Context
- Input & Execution Model: Users submit jobs containing anywhere from a few tasks up to tens of millions of independent tasks (e.g., video processing, ML feature extraction). Tasks take anywhere from hundreds of milliseconds to several minutes to run.
- Core Functionality: The system must support task scheduling, progress querying, job cancellation, priorities, retries with backoff, and task result aggregation.
- Fault Tolerance & Guarantees: Compute instances can crash, experience network partitions, or suffer from long garbage collection pauses. System state must remain consistent, preventing orphan tasks, infinite loops, and duplicate side effects where possible.
Expected Coverages
- API & Data Model: Design the public endpoints and underlying persistence schemes (job/task representations and queue structures).
- Scheduling Architecture: Explain worker discovery, work distribution (pull vs. push), task partitioning, and tenant fairness/prioritization.
- Leasing & Execution Coordination: Describe how task ownership, heartbeats, fencing tokens, and timeout reclaims operate safely.
- Fault Recovery & Idempotency: Detail retry strategies, error classification, poison task/host handling, and achieving at-least-once or effectively-once execution semantics.
- State Aggregation & Scalability: Explain how the system updates job progress counters without creating hot spots, auto-scales worker capacity, and prevents downstream system overload (backpressure).
Hints
Hint 1
Differentiate between job submission (generating metadata) and task ingestion (expanding millions of tasks into execution queues) to avoid blowing up memory or API latency.
Hint 2
Consider how to handle zombie workers—workers that lose network connectivity but continue processing locally—to avoid split-brain side effects when a task is re-assigned.
Hint 3
For high-throughput jobs with millions of tasks, updating a single job record in a database on every task completion will cause extreme write contention. How can you shard counters?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement Clarification & Capacity Estimation
Functional Requirements
- Job Lifecycle: Submit, track progress, fetch aggregated outputs, and cancel running jobs.
- Task Scheduling: Support heterogeneous task runtimes (e.g., containerized specs), custom attempt retries with backoff, priorities (
HIGH,NORMAL,LOW), and tenant quota isolation. - Reliability: Support fault-tolerant execution. No task state lost once acknowledged.
Scale & Load Target
- Job Load: 10,000 jobs/day.
- Task Volume: Average 100M tasks/day (~1,150 tasks/sec sustained), peaking at 5x bursts (~6,000 tasks/sec).
- Execution Profile: Average task runtime is 2 seconds.
- Required Compute: $6,000 \text{ tasks/sec} \times 2 \text{ seconds} = 12,000 \text{ concurrent worker slots}$. Provisioning for 15,000+ slots allows overhead for worker warmup, health checks, and unexpected spikes.
2. API Design & Data Model
Core APIs
POST /v1/jobs
Creates a job with explicit partition specs or an inline task payload.
{
"tenant_id": "org_analytics_01",
"idempotency_key": "upload_2023_10_24_batch_A",
"priority": "HIGH",
"execution_spec": {
"image": "docker.io/company/worker-processor:v2.1",
"cpu_cores": 0.5,
"memory_mb": 512,
"timeout_seconds": 300
},
"input_manifest": {
"type": "S3_PREFIX",
"uri": "s3://my-bucket/inputs/2023-10-24/"
},
"partition_strategy": {
"type": "FIXED_CHUNK",
"chunk_size": 1000
},
"retry_policy": {
"max_attempts": 4,
"initial_backoff_ms": 1000,
"max_backoff_ms": 60000
}
}
Response (202 Accepted): { "job_id": "job_984a2f1b" }
GET /v1/jobs/{job_id}
Returns high-level status and aggregated counters.
{
"job_id": "job_984a2f1b",
"status": "RUNNING",
"counters": {
"total": 50000,
"pending": 5000,
"running": 12000,
"succeeded": 32900,
"failed": 100
},
"estimated_completion_time": "2023-10-24T14:32:00Z"
}
POST /v1/jobs/{job_id}/cancel
Signals the system to stop issuing tasks for this job and terminate running containers.
Data Model & Storage Topology
+------------------------------------------------------------------------+
| Metadata Store (RDBMS) |
| |
| +--------------------------------+ +-------------------------------+ |
| | Jobs Table | | Job Counter Shards | |
| | ------------------------------ | | ----------------------------- | |
| | PK: job_id | | PK: (job_id, shard_id) | |
| | idempotency_key (Unique) | | succeeded_count | |
| | tenant_id, priority, state | | failed_count | |
| | execution_spec (JSON) | +-------------------------------+ |
| +--------------------------------+ |
| |
| +------------------------------------------------------------------+ |
| | Tasks Table (Sharded by job_id) | |
| | ---------------------------------------------------------------- | |
| | PK: (job_id, task_id) | |
| | status (PENDING, READY, LEASED, SUCCEEDED, FAILED, DEAD) | |
| | current_attempt, lease_owner, lease_expiry, execution_token | |
| +------------------------------------------------------------------+ |
+------------------------------------------------------------------------+
-
Job Record Store (Relational DB, e.g., PostgreSQL/CockroachDB):
JobsTable: Stores metadata, runtime limits, overall state (SUBMITTED,EXPANDING,RUNNING,CANCELLED,COMPLETED).- Indexed by
(tenant_id, idempotency_key)to guarantee request deduplication.
-
Task Record Store (Sharded NoSQL/Relational):
TasksTable: Keyed by(job_id, task_id). Contains state (PENDING,READY,LEASED,SUCCEEDED,FAILED,DEAD),current_attempt,lease_owner,lease_expiry, and a fencingexecution_token.- Partitioned by
job_idso all tasks for a job live on the same physical database node cluster.
-
Ready Work Queues (Redis / Apache Kafka / RabbitMQ):
- Decouples task state management from worker consumption. Tasks in
READYstatus are pushed to priority-specific queues grouped by tenant.
- Decouples task state management from worker consumption. Tasks in
-
Result / Output Store:
- Object Store (e.g., S3/GCS) holding blob outputs per task attempt (
/outputs/{job_id}/{task_id}/attempt_{n}.json).
- Object Store (e.g., S3/GCS) holding blob outputs per task attempt (
3. High-Level Architecture & System Components
+-------------------+
| Client API |
+---------+---------+
|
v
+-------------------+
| API Service |
+---------+---------+
|
+-------------------------+-------------------------+
| Writes Job Metadata | Bulk Enqueues Tasks
v v
+-------------------+ +-------------------+
| Job DB / Metadata| | Task Partitioning |
+-------------------+ | Service |
^ +---------+---------+
| Status / Progress updates |
| v
+---------+---------+ +-------------------+
| Progress & Counter| | Multi-Tenant Queue|
| Aggregator Service|<-----+ | (Redis / Kafka) |
+-------------------+ | +---------+---------+
| Commit / Completion |
| Events v Pull Leases
+-------+-------+ +-------------------+
| Worker Fleet |<---------------+ Scheduler / |
| (Containers) | | Lease Manager |
+---------------+ +-------------------+
Key Components
- API Service: Stateless REST frontend that validates payloads, checks tenant quotas, ensures idempotency, and writes the initial
Jobmetadata record. - Task Partitioning Service: Asynchronously reads the
input_manifestfor newly submitted jobs. It chunks large input specs (e.g., millions of object URIs) into task batches, bulk-inserts task records into the database in chunks (e.g., 5,000 records per transaction), and emits task notifications to the Queue layer. - Scheduler & Lease Manager: Monitors the ready queues, applies fair-sharing across tenants, and manages lease allocation.
- Worker Fleet: Distributed worker processes running on compute nodes (e.g., Kubernetes pods). Workers long-poll the Scheduler for work, execute task containers, send periodic heartbeats, and write outputs to object storage.
- Progress & Counter Aggregator: Consumes task completion events asynchronously to compute progress, check job completion conditions, and trigger post-job workflows.
4. Scheduling, Leasing & Coordination Mechanism
Push vs. Pull Execution Model
This design uses a pull-based leasing system with worker-driven polling:
- Why not push? Push architectures require the central scheduler to maintain detailed state about worker capacity, CPU load, and memory pressure. Under high load, misjudging worker health leads to queuing at the worker node.
- Pull Benefits: Workers query the Scheduler only when they have free capacity slots. This provides natural backpressure and handles heterogeneous hardware seamlessly.
Task Leasing Protocol
To prevent double-execution while avoiding heavy distributed locking (like Paxos per task):
Worker Scheduler Task Store
| | |
|--- LeaseTasks(capacity)--->| |
| |--- Fetch READY Tasks -------->|
| |--- UPDATE task SET... ------->|
| | state = LEASED |
| | lease_owner = worker_id |
| | execution_token = token+1 |
| |<-- Return updated tasks ------|
|<-- Grant Lease + Token ----| |
| | |
[Execute Task] | |
|--- Heartbeat(token) ------>| |
| |--- Refresh lease_expiry ----->|
| | |
[Write Output] | |
|--- CompleteTask(token) --->| |
| |--- UPDATE state=SUCCEEDED --->|
- Lease Acquisition:
A worker calls
LeaseTasks(tenant_id, slot_capacity). The scheduler selects tasks from the appropriate queue and executes a conditional write against the Task database:UPDATE tasks SET status = 'LEASED', lease_owner = :worker_id, lease_expiry = NOW() + INTERVAL '30 SECONDS', execution_token = execution_token + 1, current_attempt = current_attempt + 1 WHERE (job_id, task_id) = (:job_id, :task_id) AND status IN ('READY', 'PENDING'); - Heartbeats: While the task executes, the worker sends a heartbeat every 10 seconds. The Scheduler extends
lease_expiryby 30 seconds upon each valid heartbeat. - Fencing Tokens: The incrementing
execution_tokenacts as a fencing token. If a worker experiences a long GC pause or network disruption, its lease expires, and another worker claims the task (incrementing the token). When the slow worker recovers and attempts to report completion, the update is rejected because its local token is stale.
5. Fault Tolerance, Retries & Idempotency
Error Classification & Retries
Errors are categorized into two buckets:
- Transient Failures (Retryable): Network timeouts, HTTP 5xx responses, worker host crash, lease expiration.
- Retried with Exponential Backoff and Full Jitter: $$\text{Backoff} = \text{Random}\left(0, \min\left(\text{MaxBackoff}, \text{Base} \times 2^{\text{attempt}}\right)\right)$$
- The task's
statusbecomesRETRY_WAITuntilnext_run_at <= NOW(), after which it transitions toREADY.
- Permanent Failures (Non-retryable): Input parsing error, HTTP 4xx, out-of-bounds array access.
- Immediately marked as
FAILED. Iffailed_countcrosses a configured job-level threshold (e.g., 5% of all tasks), the entire job transitions toFAILED.
- Immediately marked as
Dealing with Zombie Workers & Poison Tasks
- Reaper Service: A background daemon scans for tasks where
status = 'LEASED' AND lease_expiry < NOW(). The Reaper resets their state toREADY(orRETRY_WAIT) and increments the attempt count. - Poison Tasks: If a specific task causes workers to crash (e.g., triggering a C++ kernel panic / OOM killer), the
current_attemptlimit (e.g.,max_attempts = 4) prevents infinite execution loops. Once exhausted, it transitions toDEADand is placed in a Dead Letter Queue (DLQ). - Poison Workers: If a worker host fails 5 consecutive tasks from different jobs within 1 minute, the cluster manager quarantines that worker node for diagnostic inspection.
Idempotency & "Effectively-Once" Processing
True exactly-once execution is impossible in distributed systems due to the Two Generals' Problem (a worker can complete side effects but crash right before sending the completion RPC). We instead guarantee effectively-once side effects:
- Side-Effect Free Writes: Workers write output artifacts to deterministic object paths tagged with the fencing token:
s3://output-bucket/jobs/{job_id}/tasks/{task_id}/attempt_{execution_token}.dat - Atomic Commit: When the worker commits completion via the API, the database verifies the token and marks the task as
SUCCEEDED, referencingattempt_{execution_token}.datas the authoritative output. Any output written by stale, orphaned worker attempts is ignored and garbage-collected later.
6. Multi-Tenancy, Prioritization & Backpressure
Multi-Tenant Queue Design
To prevent a single tenant submitting 10M tasks from starving a tenant submitting 100 high-priority tasks, we use a Deficit Weighted Round Robin (DWRR) or Fair-Share Queue Structure:
+-----------------------------------------------------+
| Scheduler Router |
+-----------------------------------------------------+
|
+----------------------------+----------------------------+
| High Priority Queue | Normal Priority Queue
v v
+--------------+ +--------------+
| Tenant A | (Weighted Quota: 60%) | Tenant A |
| [T1, T2, T3] | | [T7, T8] |
+--------------+ +--------------+
| Tenant B | (Weighted Quota: 40%) | Tenant C |
| [T4, T5] | | [T9, T10] |
+--------------+ +--------------+
- Each tenant gets sub-queues partitioned by priority (
HIGH,NORMAL,LOW). - The Scheduler pulls work by iterating across active tenant sub-queues using weighted token buckets based on tenant resource tiers.
Cluster Backpressure
- If worker CPU/Memory usage across the cluster exceeds 85%, the Scheduler throttles lease grants.
- If the Redis/Kafka ready queues grow beyond memory limits, the Task Partitioning Service pauses expanding new jobs from
input_manifestfiles, keeping jobs in theSUBMITTEDstate in the primary DB until queue depth drops.
7. Progress Tracking & Counter Aggregation
High-Throughput Aggregation (Avoiding DB Write Contention)
If 6,000 tasks complete every second, updating a single succeeded_count column on a single Jobs row will cause extreme database lock contention.
Solution: Counter Sharding + Event Streaming
[ Worker Completes Task ]
|
v
[ Push Event to Kafka Topic: task-completions ]
|
v
[ Aggregator Worker Pool ]
|
(In-memory Buffer for 1 second)
|
v
[ Batch Update Sharded Counters DB ]
UPDATE job_counter_shards
SET succeeded = succeeded + :batch_success
WHERE job_id = :id AND shard_id = RAND(0, 16);
- Workers emit a
TaskCompletedevent to an Apache Kafka topic. - An Aggregator Service consumes completion events in batches (e.g., every 1 second or every 500 events per job).
- The Aggregator updates one of 16 distributed counter shards per job in the database:
UPDATE job_counter_shards SET succeeded_count = succeeded_count + :batch_count WHERE job_id = :job_id AND shard_id = :random_shard_id; - Reads (
GET /v1/jobs/{job_id}) execute a simple sum across the 16 shards:SELECT SUM(succeeded_count) FROM job_counter_shards WHERE job_id = :job_id. This eliminates lock contention entirely.
8. Summary of Key Trade-Offs
| System Design Choice | Chosen Strategy | Alternative Strategy | Rationale for Choice |
|---|---|---|---|
| Work Allocation | Pull-Based Leasing | Push-Based Direct Dispatch | Pull provides automatic backpressure and prevents overloading slow/unhealthy worker nodes. |
| Execution Guarantees | At-Least-Once Execution + Fencing Tokens | Exactly-Once Processing | True exactly-once execution requires prohibitive distributed lock overhead across heterogeneous tasks. |
| State Tracking | Sharded Counter Tables + Kafka Aggregations | Synchronous Counter Updates | Prevents database row-level locking spikes when thousands of sub-tasks finish simultaneously. |
| Queue Architecture | Per-Tenant Priority Queues | Single Shared FIFO Queue | Prevents large batch workloads from starving fast, high-priority interactive tasks. |