Hello! Welcome to your next lesson on system design.
In our last session, we designed a real-time collaborative editor, diving deep into the complexities of fine-grained concurrency with OT and CRDTs. We focused on achieving consistency for every keystroke in a stateful, interactive application.
Today, we shift our focus to a different class of distributed system: one that manages work that happens in the background, often on a massive scale. Our learning outcome is to design a distributed job scheduler for asynchronous background tasks.
This is a foundational problem in large-scale engineering, powering everything from video encoding at Google, to data pipelines at Meta, to asynchronous order processing at Uber. For a Staff-level interview, a simple "queue and workers" model is insufficient. The expectation is a design that demonstrates deep thinking about durability, fault tolerance, resource isolation, and managing time and state across a distributed fleet.
1. Framing the Problem: Beyond Queues and Workers
Before we draw a single box, it's crucial to frame the problem with the rigor expected at a Staff+ level. A distributed scheduler isn't just about assigning work; it's about managing uncertainty and providing guarantees in the face of inevitable failures.
Let's start by reading a short piece that perfectly captures this mindset.
Distributed Job Scheduler System Design - Educative.io
This article from Educative.io explains how to approach the job scheduler problem in a senior-level interview. It emphasizes thinking about failure modes and guarantees from the very beginning.
Please read the introduction and the section titled 'Framing the problem correctly'. Focus on the questions a strong candidate would ask: What kinds of jobs? What scale? What guarantees (job loss, duplicates, latency)?
Drawing from that, let's establish our requirements, aiming for a system that could operate at the scale of a company like Meta or Google.
Functional Requirements:
- Job Submission: Clients can submit jobs to be executed asynchronously.
- Job Types: Support for:
- One-time jobs: Run as soon as possible or at a specific time.
- Recurring jobs: Run on a schedule (e.g., cron
* * * * *). - DAGs (Directed Acyclic Graphs): A job can have dependencies on other jobs (e.g., Job C runs only after A and B complete).
- Job Management: Users can query the status of their jobs (e.g.,
PENDING,RUNNING,COMPLETED,FAILED), and cancel them.
Non-Functional Requirements (Staff+ Level):
- Durability: Once a job is accepted, it is never lost, even if parts of the scheduler system crash. We are aiming for 99.9999% durability.
- Availability: The system should be highly available for job submissions (e.g., 99.99%).
- Execution Guarantees: We will target at-least-once execution. We must design to mitigate the impact of duplicates.
- Scale: The system must handle an ingestion peak of 10 million job submissions per second and manage billions of active jobs at any given time.
- Latency: For high-priority jobs, the "scheduling drift" (delay between scheduled time and actual execution start) must be in the milliseconds.
- Isolation: The system is multi-tenant. A faulty or high-volume job from one tenant must not degrade the performance for others.
2. High-Level Architecture: Decoupling Concerns
To manage this complexity, we must decompose the system into independent domains. A monolithic design would collapse under these requirements. The three core domains are:
- Ingestion & Persistence: The "write path" responsible for accepting and durably storing job definitions.
- Orchestration & Scheduling: The "time brain" that efficiently identifies which jobs are due to run now.
- Execution: The "workforce" that runs the jobs, handles retries, and reports status.
This separation allows each layer to be scaled and optimized independently.

3. Deep Dive 1: Ingestion and Persistence
Handling 10 million writes per second to a single database is impossible. We need a horizontally scalable storage layer.
To understand how to build this, we'll draw inspiration from Meta's internal queuing service, FOQS (Facebook Ordered Queuing Service), which uses a sharded database architecture.
Distributed Job Scheduler Architecture at Meta Hyperscale
This article provides a deep dive into building a scheduler for 'Meta scale'. We'll focus on the Ingestion and Storage section, which details a battle-tested pattern for high-throughput writes.
Read section 3, 'Ingestion and Storage: The “FOQS” Pattern'. Pay close attention to these critical design decisions: The Sharding Key: Why sharding by execution_time is a disastrous anti-pattern, and why sharding by Namespace or Job ID is the correct approach to distribute write load evenly. Table Separation: The rationale for splitting data into a heavy JobDefinitions table and a lean JobSchedules table to optimize scanning. Recurring Jobs: How the system handles recurring jobs by updating the next_run_time field rather than re-creating the job.
Key Takeaways for Persistence:
- Storage Engine: A sharded relational database (like MySQL with MyRocks or PostgreSQL) is a good choice. It provides ACID guarantees within a shard, which is sufficient for managing job state transitions (
PENDING->LEASED). - Sharding Strategy: Shard by a hash of the Job ID or a Tenant/Namespace ID. This distributes writes uniformly across the cluster, avoiding "hot shards" that would occur if you sharded by time.
- Schema Design:
JobDefinitionsTable: Stores the "what." Contains static metadata like the job's logic (e.g., binary path), owner, retry policy, and cron schedule. This table is write-heavy at creation but read-infrequently by the scheduler.JobSchedulesTable: Stores the "when." This is a very slim, highly-indexed table containing onlyjob_id,next_run_time, andstatus. The scheduler will scan this table, making the operation much faster.
4. Deep Dive 2: Scheduling - The "Time Problem"
With billions of jobs in our JobSchedules table, how do we find the ones due right now without continuously scanning the entire database? Polling is inefficient and doesn't scale.
This is where a specialized in-memory data structure comes in: the Hierarchical Timing Wheel. It allows for managing millions of timers with O(1) amortized complexity for adding and triggering timers.
{
"intro": "Let's continue with the 'Meta Hyperscale' article to understand this core scheduling component. It's a significant step up from a simple polling mechanism.",
"resource_title": "Distributed Job Scheduler Architecture at Meta Hyperscale",
"resource_id": "[LINK](https://dilipkumar.medium.com/distributed-job-scheduler-system-design-8ae13a8dee83)",
"relevant_sections": [
3
],
"instructions": "Read section 4, 'The Scheduler: Hierarchical Timing Wheels'. Focus on:\n\n1. **The Core Concept:** Understand the analogy to a clock face and how a hierarchy of wheels (for seconds, minutes, hours) allows for efficient scheduling of jobs far in the future.\n2. **The Cascade Mechanism:** How jobs "cascade" down from coarser wheels (e.g., 'minutes') to finer ones (e.g., 'seconds') as their execution time approaches.\n3. **Persistence (WAL):** How a Write-Ahead Log (WAL) ensures that the in-memory state of the timing wheel can be recovered after a crash, thus preserving durability.",
"estimated_time": "10 minutes"
}
How it all fits together:
- A Scheduler Service acts as a "Loader." It periodically polls the sharded database for jobs scheduled in the near future (e.g., the next 15 minutes).
- It loads these "imminent" jobs into its local in-memory Hierarchical Timing Wheel.
- The timing wheel advances tick by tick. When a tick lands on a slot with jobs, it fires them off to the Execution layer.
- If the Scheduler Service crashes, it recovers its in-memory state by replaying its WAL, ensuring no jobs are lost.
5. Deep Dive 3: Execution - The "Work Problem"
Once the scheduler identifies a job to run, it needs to be delivered to a worker.
Push vs. Pull Model
There are two primary models for this:
- Push: The scheduler sends the job directly to a worker it believes is available. This has low latency but is fragile; if the worker has crashed or is paused (e.g., long GC), the job is stuck until the scheduler detects the failure and reassigns it.
- Pull: Workers ask the scheduler (or a queue) for work when they are ready. This is more resilient to worker churn and provides natural backpressure—if workers are overloaded, they simply stop asking for jobs.
For a large-scale, resilient system, the Pull Model is generally preferred.
The Go Worker Pool
Since your primary language is Go, it's useful to visualize how a worker pool can be implemented using goroutines and channels. This is a classic fan-out/fan-in pattern.

Handling Failures in Execution
This is where the system's reliability is truly tested.
✅ System Design 9: Design Distributed Job Scheduler like Airflow | Temporal | Celery | HLD | LLD
This video provides clear, practical explanations for several core components, including failure handling. We'll focus on its approach to retries and detecting crashed executors.
Watch the segment from 42:50 to 50:22. The key concepts here are: Job Failure Retries: Using separate Kafka topics (e.g., a retry-topic and a dead-letter-topic) to manage failed jobs. The attempt count is incremented in the database. Executor Crash Detection: A clever use of a modified_time heartbeat in the job_run table. A separate 'Watcher' service scans for jobs that are in a 'running' state but haven't updated their heartbeat recently, and re-triggers them.
The "Zombie Worker" Problem and Fencing Tokens
There's a more sinister failure mode:
- Worker A grabs a job and starts processing.
- Worker A experiences a long GC pause, and the scheduler thinks it's dead.
- The scheduler reassigns the job to Worker B, which completes it.
- Worker A wakes up and also completes the job, potentially corrupting data.
This "zombie worker" problem is solved with fencing tokens.
Distributed Job Scheduler Architecture at Meta Hyperscale
This is another advanced concept from the 'Meta Hyperscale' article that is crucial for a Staff-level discussion on correctness.
Read section 8.1, 'Fencing Tokens and the Zombie Worker'. The core idea is that every time a job lease is granted, a monotonically increasing token is issued. A worker must present its token when writing results, and the store will reject writes from workers with stale tokens.
6. Staff+ Topics: Distribution and Isolation
We've designed the core components, but two major questions remain for a truly distributed system.
- Distribution: With thousands of scheduler nodes, how does a specific node know which jobs it is responsible for loading into its timing wheel?
- Isolation: How do we prevent a single tenant (e.g., a team that submits 100 million buggy jobs) from crashing the entire platform?
The answers lie in two advanced patterns used at companies like Meta and AWS.
- The Shard Manager Pattern: A control plane (like Zookeeper) is used to assign ownership of virtual shards of the job space to physical scheduler nodes. If a scheduler node dies, the Shard Manager reassigns its shards to healthy nodes, which then load the relevant jobs from the database. This answers the "who is responsible?" question.
- Shuffle Sharding: This is a powerful isolation technique. Instead of giving each tenant a dedicated set of workers (expensive) or letting all tenants share all workers (risky), each tenant is assigned a small, unique, random subset of workers. A massive failure caused by one tenant is thus contained to their small shard, leaving the vast majority of the system unaffected.
Distributed Job Scheduler Architecture at Meta Hyperscale
To tie this together, please read the final sections of the 'Meta Hyperscale' article on these two patterns. Understanding these will significantly elevate your design.
Read section 5, 'Distribution Strategy: The Shard Manager Pattern', and section 7.2, 'Shuffle Sharding for Fault Isolation'. These are the capstone concepts for a hyperscale design.
Conclusion
We have designed a distributed job scheduler capable of operating at hyperscale. We went far beyond a simple queue, addressing the critical challenges of durability, scheduling efficiency, fault tolerance, and multi-tenant isolation.
Key Takeaways:
- Decouple Everything: Separate Ingestion, Scheduling, and Execution to scale each component independently.
- Smart Persistence: Use a sharded database, but shard by Job ID/Namespace, not by time, to avoid hot spots. Separate lean schedule data from heavy job metadata.
- Efficient Scheduling: Avoid database polling at scale. Use an in-memory Hierarchical Timing Wheel for O(1) timer management, backed by a WAL for durability.
- Resilient Execution: Prefer a pull model for natural backpressure. Use fencing tokens to prevent "zombie workers" from corrupting state.
- Isolate and Distribute: Use a Shard Manager to assign responsibility and Shuffle Sharding to contain the "blast radius" of faulty tenants.
Preview of the Next Lesson:
Our next lesson will be to design a ride-sharing system (Uber focus). This will shift our focus again, this time to a system that involves real-time geospatial indexing, complex matching algorithms between riders and drivers, and managing the state of thousands of moving entities simultaneously.