Build a Scalable Task Scheduling Service
System DesignModel answerLast updated
Architect a fault-tolerant distributed system that executes millions of recurring jobs with precise timing, at-least-once guarantees, and resilience to failures.
Problem
You're building a cloud-native task scheduling platform that customers use to automate recurring operations—sending invoices, generating reports, purging stale data, and triggering batch pipelines. Your service must reliably fire jobs at their configured intervals, deliver execution requests to external systems, and remain available despite infrastructure failures.
What You Need to Design
Core Capabilities
- Schedule CRUD: Customers define repeating tasks using cron syntax with explicit time zones. They can create, modify, pause, resume, delete, and manually invoke schedules on demand.
- Trigger Dispatch: When a task's time arrives, the system sends its payload to a designated target—an HTTP endpoint, message queue, or worker fleet.
- Execution Tracking: Record every attempt, enforce timeouts, retry failed deliveries with backoff, and allow in-flight cancellations.
- Missed-Run Handling: Define behavior when a job misses its window—fire once immediately, replay all missed occurrences in sequence, or skip entirely. Support explicit backfill requests for historical windows.
Scale & Performance Targets
- Capacity: 50 million active schedules; peak load of 50,000 triggers per second.
- Precision: 99% of jobs must dispatch within one second of their scheduled time.
- Reliability: Guarantee at-least-once execution through node crashes, network splits, and database failovers. Minimize (but tolerate) duplicate dispatches using deterministic identifiers.
- Fairness: Prevent heavy or bursty schedules from monopolizing resources at the expense of others.
What to Provide
- Component Architecture: Identify the key services (API layer, scheduling coordinators, storage, dispatch queues, execution workers) and explain how they interact.
- Storage Schema: Define tables or collections for job definitions, materialized run instances, and execution logs.
- Partition & Dispatch Logic: Describe how you scan upcoming work, distribute it across scheduler instances, and ensure exactly one coordinator fires each job without duplication or omission.
- Failure Handling: Address coordinator crashes, worker timeouts, lease expiration, duplicate dispatch scenarios, daylight saving transitions, and orphaned runs that need reconciliation.
Hints
Hint 1
Think about how to avoid scanning all 50 million jobs every second—what indexing or bucketing strategy keeps lookups fast?
Hint 2
Deterministic run identifiers (derived from job ID and scheduled time) allow multiple components to safely attempt the same insert without creating duplicates.
Hint 3
Consider a two-phase approach: pre-materialize runs shortly before their trigger time to absorb write spikes, then flip their state and enqueue at the exact moment.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Establish Scale Parameters
Begin by translating requirements into concrete numbers that shape your design.
| Metric | Calculation |
|---|---|
| Job metadata | 50M jobs × ~1 KB ≈ 50 GB (fits in a sharded database) |
| Steady-state rate | Most jobs run hourly or daily → ~12k fires/s average |
| Peak burst | 50k fires/s (concentrated at top-of-hour boundaries) |
| Daily run records | ~1B executions/day × 500 B ≈ 500 GB/day (retain 30 days hot, archive older) |
| Dispatch latency | p99 < 1 s → hot path cannot afford synchronous database queries at trigger time |
Key assumptions: minute-level granularity, at-least-once delivery semantics, execution means dispatching a payload (not running arbitrary code in-process).
2. API Surface
POST /schedules {cron, timezone, target, payload, retry_config, timeout, misfire_mode, priority}
PATCH /schedules/{id} (update, pause, resume)
DELETE /schedules/{id}
POST /schedules/{id}/trigger → execution_id (manual invocation with unique request ID)
POST /schedules/{id}/backfill {start_time, end_time, concurrency_limit}
POST /executions/{id}/cancel
GET /schedules/{id}/executions?from=&to=
3. Storage Schema
schedules table
schedule_id (PK), tenant_id, cron_expression, timezone, target_url, payload_location,
retry_config, timeout_seconds, misfire_mode, status, version, next_trigger_utc
time_buckets index (partition-friendly secondary structure)
shard_id, bucket_minute_utc, schedule_id -- composite PK
shard_id = hash(schedule_id) % 4096
executions table
execution_id (PK), schedule_id, tenant_id, scheduled_time_utc, state, attempt_count,
lease_holder, lease_expires_at, fencing_token, record_version
-- execution_id = deterministic_hash(schedule_id || truncate_to_minute(scheduled_time_utc))
-- GSI on (state, lease_expires_at) for reconciliation queries
attempts log
execution_id, attempt_number, worker_id, started_at, completed_at, outcome, error_message
shard_leases table
shard_id (PK), owner_node, lease_epoch, expires_at
The deterministic execution_id is the foundation of idempotency. Multiple components (scheduler, backfill processor, reconciler) can all attempt to insert the same execution record; conditional writes ensure only one succeeds.
4. Architecture Overview
API Service (stateless)
Validates cron expressions and time zones, computes next_trigger_utc, and atomically writes both the schedules row and corresponding time_buckets entry.
Scheduler Cluster (~30 nodes)
Each node claims ownership of a subset of 4096 logical shards via distributed leases (etcd, Consul, or DynamoDB). Every lease carries a monotonically increasing epoch (fencing token).
In-Memory Timing Wheel
Each scheduler pre-loads jobs from its owned shards for the next 1–2 minutes into a hierarchical timing wheel, avoiding repeated database scans.
Pre-Materialization (T-30s)
About 30 seconds before a job's trigger time, the scheduler inserts an execution record with state PENDING. This spreads write load and absorbs the top-of-hour spike.
Trigger Dispatch (at T)
When the wheel fires at the exact scheduled second, the scheduler:
- Updates execution state from
PENDING→QUEUED - Publishes a message to the execution queue
- Advances the schedule's
next_trigger_utcand updatestime_buckets, conditioned on the current lease epoch
Fair Dispatch Layer
Messages flow into tenant-partitioned queues (Kafka topics or SQS queues). A dispatcher service drains them using weighted round-robin or deficit round-robin to enforce fairness.
Worker Pool
Workers acquire a lease on an execution (with heartbeat), invoke the target endpoint, and record the attempt outcome.
Reconciliation Service
Periodically scans (state, lease_expires_at) to recover stuck executions—retrying expired leases, enforcing timeouts, and handling orphaned records.
Why 4096 logical shards?
Peak load of 50k fires/s ÷ 4096 ≈ 12 per shard per second. Each scheduler node handling ~150 shards (5k fires/s) means ~10 nodes at peak; run 30 for headroom. Fixed logical partitions make rebalancing lightweight (only lease ownership moves, no data migration).
5. Correctness Under Failure
Idempotent Replay
The core invariant: every step is safe to retry.
- Conditional-insert execution as
PENDING(idempotent due to deterministic ID) - At trigger time, enqueue and transition to
QUEUED - Advance schedule, conditioned on
lease_epoch == my_epoch
If a scheduler crashes mid-sequence, the next owner re-scans the same time bucket and repeats all steps. Duplicate inserts are rejected by the database; duplicate messages are deduplicated by workers checking execution_id.
Split-Brain Protection
A zombie scheduler with an expired lease will fail the epoch check on step 3. Even if it enqueues a message, the worker's CAS from QUEUED → RUNNING succeeds exactly once due to optimistic locking on record_version.
Database Failover
After a primary failover, the new leader may be missing recent writes. Schedulers re-scan buckets from now - grace_period. Since all operations are idempotent, replaying is safe.
Worker Failure
Workers hold 30-second leases and heartbeat every 10 seconds. On lease expiry, the reconciler transitions the execution to RETRY_PENDING and schedules exponential backoff. Each retry attempt increments fencing_token; completion writes with stale tokens are rejected.
Timeouts
Workers enforce timeouts locally. The reconciler acts as backstop, checking started_at + timeout_seconds.
Cancellation Races
Cancellation sets CANCEL_REQUESTED via CAS on record_version. Workers check this flag on their next heartbeat, abort work, and write CANCELLED. If a worker's SUCCEEDED write wins the race, cancellation reports "completed before cancel". Terminal states are absorbing.
Daylight Saving Transitions
Store all times in UTC. Compute next fire time by converting to the job's configured timezone, advancing by the cron interval, then converting back. Libraries like Joda-Time or dateutil handle ambiguous/nonexistent times correctly.
Misfire Policies
When scheduled_time_utc < now - grace_threshold:
FIRE_ONCE: emit only the most recent missed executionCATCH_UP: emit all missed executions sequentially, rate-limitedSKIP: discard entirely
Backfill Requests
A backfill generator enumerates fire times in [start, end] and inserts executions with the same deterministic IDs. Overlaps with real-time runs deduplicate automatically. Backfill messages go to a separate low-priority queue with controlled concurrency.
6. Key Trade-Offs
Push vs. Pull
Pre-materializing execution records 30 seconds early adds write volume but absorbs top-of-hour spikes and enables the sub-second p99 SLO.
At-Least-Once vs. Exactly-Once
Exactly-once delivery to arbitrary HTTP endpoints is impossible without cooperation. We provide idempotency keys and narrow the duplicate window instead.
Fixed vs. Dynamic Partitions
4096 fixed logical shards simplify rebalancing (only leases move, no data resharding). The cost is a slightly larger lease table and minimum node count.
Storage Technology
DynamoDB or Cassandra offer partition-friendly writes, built-in TTL, and CAS primitives. Relational databases simplify transactions but require manual sharding beyond a few million jobs.
Queue vs. Direct Invocation
Interposing a message queue decouples scheduling from execution, enables tenant isolation and fair queuing, and provides natural retry buffers. Direct HTTP calls would couple scheduler availability to target availability.
7. Common Pitfalls
- Scanning all jobs every second: Use time-bucketed indexes so each scheduler reads only jobs due in its owned shards for the current minute.
- Relying on system clocks for deduplication: Use deterministic execution IDs derived from job identity and scheduled time, not wall-clock timestamps.
- Ignoring lease expiration: Always condition writes on lease epoch; always use fencing tokens on worker completions.
- Treating retries as new jobs: Retries share the same execution_id and increment
attempt_count, preserving idempotency and audit trail. - Forgetting time zone edge cases: Test schedule advancement across DST boundaries, leap seconds, and timezone definition updates.
Summary
This design achieves 50k fires/s at sub-second precision through:
- Bucketed indexing (O(jobs_due) scans, not O(total_jobs))
- Deterministic execution IDs (idempotent inserts across all components)
- Pre-materialization (absorbs write spikes before trigger time)
- Epoch-based leasing (fences zombie schedulers)
- Fair queuing (tenant isolation and priority enforcement)
- Active reconciliation (repairs any anomaly, making the system self-healing)
Every operation is designed to be safely retried, making the system resilient to arbitrary crash-and-restart sequences.