Design a Distributed Task Scheduler and Time-Window Dashboard
System DesignModel answerLast updated
Architect a scalable background task scheduling engine and high-throughput query service for inspecting upcoming jobs across flexible dynamic time windows.
Design a scalable, fault-tolerant background job scheduling system and an accompanying upcoming tasks dashboard.
The system must allow clients to register one-off delayed jobs and recurring routines (e.g., cron jobs), guaranteeing timely execution even under heavy load. In addition, design a high-throughput query pipeline powering an operational dashboard that displays upcoming tasks within an arbitrary dynamic time window $N$ (e.g., next 15 minutes, 6 hours, 24 hours).
System Capabilities to Address:
-
Functional Requirements
- Create, update, cancel, and retrieve one-time and recurring scheduled jobs.
- Execution semantics, failure handling, retries, and dead-letter queues (DLQ).
- Near-real-time dashboard queries across flexible time windows $[now, now + N]$.
-
Non-Functional Requirements
- Throughput, scale, timing precision, availability, durability, and consistency guarantees.
-
High-Level Architecture & Execution Mechanics
- Core components (API service, scheduler nodes, execution queues, storage, workers).
- Shard ownership, lease management, and worker dispatching.
- Reliability measures: preventing job loss, handling duplicate runs, and mitigating node crashes.
-
Data Modeling & Storage Strategy
- Primary storage schemas for job definitions and execution entries.
- Partitioning and indexing strategies that prevent write hot-spotting during top-of-hour load spikes.
-
Dashboard Query Engine
- Query execution paths that avoid full database scans.
- Efficient scatter-gather aggregation across variable time ranges and multi-tenant filters.
Hints
Hint 1
Avoid global indexes on execution timestamps; top-of-hour job creations will overwhelm a single database node.
Hint 2
Separate the job definition metadata from concrete, scheduled execution instances.
Hint 3
Combine time-bucketed partition keys with salt shards to spread write load while maintaining bounded parallel reads for dynamic window queries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Scope
Functional Requirements
- Job Management: Register, update, inspect, and cancel jobs. Support one-time execution at timestamp $T$ and recurring schedules defined by CRON expressions with explicit timezone boundaries.
- Execution Semantics: Guarantee at-least-once execution. Downstream worker handlers rely on unique execution keys to maintain end-to-end idempotency.
- Retries & Failure Policy: Automatically retry failed executions using exponential backoff with random jitter. Route permanently failed jobs to a Dead-Letter Queue (DLQ).
- Dashboard Querying: Provide low-latency lookups for tasks scheduled in $[now, now + N]$, support filtering by tenant, status, and job type, and supply paginated results alongside aggregate counts.
Non-Functional Requirements
- Scale & Throughput: 100M executions per day ($\approx 1,200\text{ avg executions/sec}$; peak bursts up to $50,000\text{/sec}$ at major hourly boundaries).
- Storage Scale: ~1B active task definitions and upcoming entries ($\approx 1\text{ TB}$ primary storage footprint plus historical execution records).
- Precision: $p99$ execution delay $\le 3\text{ seconds}$ from scheduled trigger time.
- Availability & Durability: $99.99%$ API availability. Zero job loss after client ACK.
- Dashboard Latency: $p99 \le 200\text{ ms}$ for window queries up to $N = 24\text{ hours}$ under thousands of concurrent QPS.
2. API Design
Lifecycle Management APIs
POST /v1/jobs
Content-Type: application/json
{
"tenant_id": "tenant_402",
"type": "PAYMENT_RECONCILIATION",
"payload": { "batch_id": "b_99120" },
"schedule": {
"type": "CRON",
"expression": "0 0 * * *",
"timezone": "UTC"
},
"retry_policy": { "max_attempts": 3, "initial_backoff_sec": 5 },
"idempotency_key": "rec_tenant_402_2023_11_01"
}
Response: 201 Created
{ "job_id": "job_992a01f8", "status": "SCHEDULED" }
DELETE /v1/jobs/job_992a01f8
Response: 200 OK
{ "status": "CANCELLED" }
Dashboard Query APIs
GET /v1/dashboard/upcoming?window=6h&tenant_id=tenant_402&status=SCHEDULED&limit=50&cursor=eyJidWNrZXQiOjE3MDAwLCJpZCI6MX0=
Response: 200 OK
{
"jobs": [
{
"execution_id": "exec_job_992a01f8_1700000000",
"job_id": "job_992a01f8",
"scheduled_time": "2023-11-01T00:00:00Z",
"type": "PAYMENT_RECONCILIATION",
"status": "SCHEDULED"
}
],
"next_cursor": "eyJidWNrZXQiOjE3MDA1LCJpZCI6MTB9",
"total_count": 1420
}
3. Data Architecture & Partitioning
Storing all job schedules in a single table with an index on scheduled_time introduces severe write hotspots on top-of-hour boundaries. To solve this, we decouple Job Definitions from Scheduled Executions and use time-bucketed sharding.
+------------------------------------+
| job_definitions (RDBMS/NoSQL) |
| (PK: tenant_id, SortKey: job_id) |
+------------------------------------+
|
v
+------------------------------------+
| schedule_index (Wide-Column) |
| Partition Key: (bucket, shard) |
| Clustering Key: (time, job_id) |
+------------------------------------+
Database Schema
job_definitions Table (Document/Relational Store, e.g., PostgreSQL or DynamoDB)
Acts as the single source of truth for job specifications.
tenant_id(Partition Key)job_id(Sort Key / UUID)type,payload_refschedule_type(ONEOFF|CRON)cron_expression,timezonestatus(ACTIVE,PAUSED,COMPLETED,CANCELLED)version(Integer for optimistic locking)
schedule_index Table (Wide-Column Store, e.g., Cassandra or ScyllaDB)
Stores light pointer rows for impending execution instances.
- Partition Key:
(time_bucket, shard_id)time_bucket: Epoch floor timestamp corresponding to 1-minute or 5-minute intervals (e.g.,1700000000).shard_id: Salt generated ashash(job_id) % S(where $S$ is the total shard count, e.g., $S = 64$).
- Clustering Key:
(scheduled_time ASC, job_id ASC) - Attributes:
execution_id,tenant_id,type,status(SCHEDULED,QUEUED,RUNNING,COMPLETED)
Partitioning Strategy Trade-offs
Using (time_bucket, shard_id) avoids global lock bottlenecks:
- Hotspot Prevention: Millions of jobs scheduled for
12:00:00are evenly distributed across $S$ distinct database shards rather than striking a single physical B-tree page. - Deterministic Lookups: Querying jobs scheduled during any specific minute requires scanning $S$ predictable partition keys
(minute_bucket, 0)...(minute_bucket, S-1)in parallel, replacing full table scans with targeted range queries.
4. System Architecture & Scheduler Mechanics
+-------------------+
| Client App |
+---------+---------+
|
v
+-------------------+
| API Gateway |
+---------+---------+
|
+------------------------+------------------------+
| |
v v
+---------------+ +-------------------+
| API Service | | Dashboard Service |
+-------+-------+ +---------+---------+
| |
+------------------------+------------------------+
|
v
+-----------------------------------+
| Database Infrastructure |
| (job_definitions & schedule_index)|
+-----------------+-----------------+
^
| (Poll assigned shards)
+-----------------+-----------------+
| Scheduler Leader Nodes |
| (Shard Ownership via etcd/ZK) |
+-----------------+-----------------+
|
v (Enqueue due jobs)
+-----------------------------------+
| Message Broker (Kafka / Pulsar) |
+-----------------+-----------------+
|
v (Consume & Execute)
+-----------------------------------+
| Worker Pools |
+-----------------------------------+
Component Roles
- API Service: Stateless handlers that validate requests, save master definitions, and write the first execution entry to
schedule_index. - Scheduler Leader Group: A cluster of scheduler processes that acquire exclusive leases on shard ranges (
shard_id ∈ [0, S-1]) managed via consensus nodes (etcd/ ZooKeeper). - Queue Infrastructure (Kafka): Partitioned streams sorted by task priority (
high-priority,default,bulk). - Worker Pools: Autoscaling stateless compute nodes that pull executions from queues, enforce local leases, and trigger client callbacks.
Execution Flow & Reliability
- Polling Cycle: Every 1 second, a scheduler node reads pending tasks from
schedule_indexfor its assigned shards for the current time bucket. - In-Memory Timer Wheel: Tasks due within the next few seconds are loaded into a localized min-heap timer wheel.
- Queue Dispatch: Once a job's timestamp arrives, the scheduler attempts a conditional update on
schedule_index(status: SCHEDULED -> QUEUED) and emits theexecution_idto Kafka. - Recurring Materialization: Upon enqueueing a recurring task's execution, the scheduler computes its next runtime based on its cron expression and inserts the subsequent occurrence into
schedule_index. Only one future instance is materialized at a time. - Worker Execution & Lease Heartbeating:
- Workers pick up messages and set
status = RUNNINGwith a short lease expiration (lease_expires_at = now + 30s). - Long-running jobs send periodic heartbeats to refresh the lease.
- If a worker crashes, a sweeper process identifies expired leases, resets the job state, and re-enqueues it.
- Workers pick up messages and set
5. Dashboard Service Architecture
To power near-real-time queries over dynamic windows $[now, now + N]$ without creating execution contention:
Dashboard Request [Window = 6h]
|
v
+------------------+ Map window to buckets
| Dashboard Engine | ----------------------------+
+--------+---------+ |
| v
| Scatter-Gather +-------------------+
+---------------------------->| Buckets [B1...Bn] |
| +-------------------+
v
Parallel Fetch ($S$ shards per bucket)
|
v
+------------------+
| K-Way Merge | --> Apply Tenant Filter --> Paginated Response
+------------------+
Query Pipeline Design
- Bucket Mapping: Convert $[now, now + N]$ into a target list of time buckets. For instance, a 1-hour window with 5-minute buckets maps to 12 distinct time buckets.
- Scatter-Gather Parallel Fetch: Execute concurrent queries across all $(Bucket_i, Shard_j)$ combinations. For a 1-hour window with $S=64$ shards and 5-minute buckets, the service queries $12 \times 64 = 768$ micro-partitions.
- Bounded Read Pool: To prevent excessive parallel requests during large window queries (e.g., $N=24\text{ hours}$), query nodes fetch coarse-grained aggregate indices (5-minute or 1-hour rollup buckets) or cap total active connection pools per node.
- K-Way Merge Sorting: Streams from all shard workers are merged in memory using a min-heap ordered by
scheduled_timeandjob_id. - Cursor Pagination: Cursors encode
(last_seen_bucket, last_seen_scheduled_time, last_seen_job_id). Subsequent page requests resume directly from the target time bucket, skipping previously read keys without requiring offset scans.
Summary of System Trade-offs
| Design Axis | Chosen Approach | Alternative Evaluated | Key Trade-off |
|---|---|---|---|
| Index Partitioning | Bucket + Salt Shard (time_bucket, shard_id) | Global B-Tree Index on scheduled_time | Salted sharded keys require scatter-gather reads for dashboards, but eliminate single-node write hotspots. |
| Recurring Schedules | Single Next-Occurrence Materialization | Pre-generating all future runs | Materializing single upcoming instances reduces database bloat and simplifies cancellations, but requires atomic re-scheduling during dispatch. |
| Execution Safety | At-least-once + Idempotency Keys | End-to-end Exactly-once | Exactly-once delivery across arbitrary external side-effects is impossible; relying on idempotency keys keeps the architecture simple and fault-tolerant. |