Distributed Job Scheduler - HLD

Difficulty: Intermediate–Advanced · Prerequisites: Message Queues, Leader Election, and Database Indexing


TL;DR

A distributed job scheduler lets teams register recurring or one-off tasks (like cron, but across a fleet of machines). It ensures each job runs exactly once, on time, with retries and dependency management.

flowchart LR
    USER["Users<br/>define jobs"]
    API["Scheduler API"]
    DB[("Job Store<br/>Cassandra")]
    TICKER["Ticker<br/>checks whats due"]
    QUEUE["Job Queue<br/>Kafka"]
    WORKERS["Worker Pool<br/>executes jobs"]

    USER -->|"1. POST job definition"| API
    API -->|"2. Store job schedule"| DB
    TICKER -->|"3. Scan due jobs"| DB
    TICKER -->|"4. Enqueue due job"| QUEUE
    QUEUE -->|"5. Execute job handler"| WORKERS

In 3 sentences: Users register jobs with a schedule (cron expression) or a one-time fire time. A “ticker” process scans the database for due jobs and enqueues them to Kafka. Worker pods consume from Kafka, execute the job, and report success/failure back. Leader election ensures only one ticker runs per shard.


1. Understanding the Problem

A distributed job scheduler accepts jobs (run once at time T, or recurring on a cron schedule, or a DAG of dependent steps) and executes them reliably across a fleet of workers. Callers shouldn’t worry about which machine runs the job, what happens when a worker crashes mid-execution, or whether the job ran twice. The scheduler owns timing, dispatch, retries, isolation, and observability.
💡 A DAG (directed acyclic graph) here just means “a set of steps with dependencies and no loops” — run B after A, run D after both B and C. The no-loops part is what makes a valid execution order always exist. Learn more →


2. Naive First Cut

The 30-second whiteboard version:

flowchart LR
    CLIENT["Client App"]
    API["Scheduler API"]
    DB[("Jobs Table")]
    CRON["Cron Loop<br/>single process"]
    WORKER["Worker"]

    CLIENT --> API
    API --> DB
    CRON --> DB
    CRON --> WORKER

Why it collapses under real use:

  • Single point of failure - the one cron loop dies, nothing schedules until someone restarts it.
  • Scheduler and worker coupled - long-running jobs block the schedule tick.
  • No leader election - if you run two cron loops for high availability (HA), both pick up the same due job and run it twice.
  • No retries or backoff - worker crashes mid-run, job is lost.

In simple terms: A worker was running a 4-hour job and crashed at hour 3. Is the job done? Should we retry? If we retry, it runs from scratch - wasting 3 hours of work.

  • Tick granularity - one-per-minute poll can’t handle sub-second precision or 100k due-jobs-per-second bursts.
  • No isolation - a runaway tenant saturates the worker pool, everyone else’s jobs miss their SLA (service-level agreement — the timing promise made to the job’s owner).
  • No observability - “did my job run?” requires grep across worker logs.
  • No dependencies - jobs are independent; can’t express “run B after A finishes.”

The rest of the doc evolves this into a horizontally scalable, HA, exactly-once-in-effect job platform.
💡 “Exactly-once in effect” is the honest version of exactly-once: the network can always deliver a message twice, so instead you make the second delivery produce no additional change. Learn more →


Glossary - what these names mean

Quick reference so nothing in this doc is a black box:

Components we build

  • Scheduler API - the HTTP service users call to create, query, cancel jobs.
  • Dispatcher - a process that watches for due jobs and hands them to workers.
  • Hydrator - a background job that copies “soon-due” jobs from the durable DB (Postgres) into the fast in-memory index (Redis), one hour before their fire time. Keeps the hot index small.
  • Sweeper - a background job that finds executions stuck in RUNNING longer than their heartbeat TTL (time-to-live — the age at which we assume the worker is dead) and marks them failed so they can be retried.
  • Worker - a process that picks up a job from the queue, runs the handler code, and reports success/failure.
  • Worker pool - a named group of workers that handle a specific class of jobs (e.g., email-sender, batch-etl).

Infrastructure pieces we use

  • Postgres - relational DB for durable truth. Job definitions, execution history. ACID (a group of writes either all land or none do), SQL queries, easy admin. Learn more →
  • Redis - in-memory data store. We use two structures:
    • Sorted Set (ZSET) - collection where each entry has a score (we use the fire-time timestamp); supports O(log N) range queries by score. Lets us ask “give me all jobs due before now.”
    • Key with TTL - short-lived entries (heartbeats, cancel flags) that auto-expire.
  • Kafka - durable message broker. Topics hold ordered messages; consumers (workers) pull them with per-partition ordering. Used here to decouple dispatch from execution.
  • etcd / ZooKeeper / Consul - distributed coordination services. They store a tiny amount of data very reliably and let N nodes race for a “lease” (temporary exclusive lock). We use them for leader election - picking one dispatcher among N to own a shard.
  • Kubernetes Lease - Kubernetes’ (K8s’) built-in version of the same leader-election idea.
  • Raft / Paxos - consensus protocols that make coordination services (etcd, ZooKeeper) tolerate node failures without split-brain — two nodes both believing they are the leader and each dispatching the same jobs. You don’t implement them; you use a service that does.
  • DLQ (Dead Letter Queue) - a parking spot for messages that failed N retries. Ops reviews them manually.
    💡 DLQ (Dead Letter Queue) = a holding queue for messages that failed processing after max retries. Operators can inspect and reprocess them later.

External / reference names in Prior Art

  • Airbnb Dynein - Airbnb’s internal delayed-job system.
  • Temporal / Cadence - open-source durable workflow engines (Temporal is the Cadence fork, now the industry standard).
  • Quartz - the classic Java scheduler library with a clustered mode using DB locks.
  • Dkron - a distributed cron daemon built in Go using Raft.
  • AWS EventBridge Scheduler - AWS’s managed version of this entire design.

Observability tools

  • Prometheus - metrics DB. Scrapes services for counters/gauges (e.g., dispatch latency, queue depth), stores time series, powers dashboards and alerts.
  • OpenTelemetry - vendor-neutral SDK that services use to emit metrics, traces, and logs in a standard format.
  • Jaeger - distributed tracing UI. Given a trace ID, shows the full path of a request across services.
  • ClickHouse - columnar analytics DB — it stores each column together on disk instead of each row, so counting failures across a billion executions reads only the status column. Fast at aggregating billions of rows (“how many jobs failed per tenant this week?”); slow at single-row updates. Complements Postgres.

3. Prior Art We’re Drawing From

  • Airbnb Dynein - distributed delayed job queue at Airbnb; uses DynamoDB for job storage, a dispatcher pool that polls by time range, pushes onto SQS for workers. Powers in-app messaging, dynamic pricing. (blog)
  • Uber Cadence / Temporal - durable workflow engine: workflow code runs as a “replayable” function; every step is persisted so the workflow survives host death. Originated at Uber, now the industry standard for multi-step orchestration with human-in-the-loop steps, timeouts, and saga compensation. (Temporal blog)
  • Quartz Scheduler (clustered) - open-source Java scheduler with DB-locked leader election. Classic pattern - a table row with FOR UPDATE or a sentinel column determines the active scheduler. Widely deployed; limits on horizontal scale due to the single write-lock hot row.
  • Dkron - Go-based distributed cron using Raft for leader election. No single point of failure (SPOF), no DB dependency. Good for platform-layer scheduling (host patching, telemetry collection).
  • Google Borg / Kubernetes CronJob - cluster-level job scheduling. Kubernetes CronJob uses a single controller with leader election to create jobs; job pods execute the work.
  • AWS EventBridge Scheduler - the managed version of this pattern at AWS scale. One-shot and cron schedules, EventBridge dispatches to Lambda / SQS / Step Functions. Designed for multi-tenant throughput.

4. Functional Requirements

Core (top 3)

  1. Schedule a job - one-time (run at timestamp T), recurring (cron expression), or delayed (run in N seconds).
  2. Execute reliably - at-least-once delivery to a worker, with retries on failure, respecting timeouts.
    💡 At-least-once = we keep trying until a worker confirms, and we accept that a job may therefore run twice. Choosing this over at-most-once is the single decision that shapes Deep Dives 2, 3 and 7.
  3. Inspect and cancel - query the status of a scheduled or running job, cancel a future run.