Build a Reliable Cron-as-a-Service Platform
System DesignModel answerLast updated
Design a cloud service that lets clients register recurring or one-off tasks, runs them on a worker fleet without skipping any run, enforces timeouts, and exposes run status and logs.
Problem
Design a managed task-scheduling platform that runs as a set of cloud microservices. Clients use an API to register work that should run at specific times, and the platform executes it on a pool of worker machines.
What a client submits
Each job definition contains:
- Job ID: optional; the platform generates one if it is missing.
- Schedule: a cron expression, a single run at a given instant, or a fixed interval ("every X minutes").
- Task: what to execute, such as a script name, a container image, or another executable description.
- Resource needs: coarse, such as a CPU/memory tier or machine class.
- Timeout: the maximum allowed run duration.
- Timeout action: what happens when a run overruns (kill it, mark it failed, retry, trigger another job, and so on).
What the platform must do
- Run every job at, or close to, its scheduled time across many workers, even when machines fail or restart.
- Detect runs that exceed their timeout and apply the configured action.
- Let clients query run state (
PENDING,RUNNING,SUCCESS,FAILED,TIMED_OUT, ...) for a single run, and the history of a job (for example, the last N runs with timestamps and outcomes). - Let clients retrieve logs (stdout/stderr or structured) for a past run.
Constraints and assumptions
- Hundreds of thousands of active jobs.
- Minute-level scheduling at minimum; finer granularity is fine if your design supports it.
- Reliability beats precision: a few seconds of lateness is acceptable, but skipping a run is a defect. Let this drive your delivery-semantics decision.
- If any scheduler instance or worker crashes or restarts, every due job must still eventually run.
- Components must be containerized/VM-hosted and scale independently.
- State any unspecified choices as explicit assumptions: time zones and DST, log retention, exactly-once vs at-least-once, catch-up policy after an outage, and depth of security or multi-tenancy.
What to cover
Walk through the architecture, data model, scheduling logic, execution path, failure handling, and query APIs. Justify the major choices and call out trade-offs. Good clarifying questions include the execution semantics required, the policy for missed windows, timing accuracy, task duration and peak concurrency, retention needs, and how detailed resource requirements are.
Hints
Hint 1
Pick the delivery guarantee first. If skipping is worse than running twice, choose at-least-once and make each run have a unique, deterministic identity (job ID plus scheduled time) so duplicates can be detected.
Hint 2
Keep the scheduler stateless and let the database be the source of truth: index jobs by next due time, and in one transaction create the run record and advance the job's next due time. Partition jobs across scheduler instances with row locks (such as SKIP LOCKED) or hash ranges.
Hint 3
Treat every worker as something that can vanish. Use leases with heartbeats, local timeout enforcement, and a background reaper that requeues expired leases and force-completes runs that exceeded their deadline. Store logs in object storage rather than the database.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- At-least-once execution with a unique run identity. Tasks should be idempotent, and the run ID is passed to them so they can deduplicate. True exactly-once is not achievable across arbitrary external side effects.
- Missed windows: by default, fire once and skip ahead to the next future slot ("coalesce"). A per-job flag can enable backfill.
- Timing target: start within about 5 to 10 seconds of the scheduled instant.
- Times are stored in UTC; the job stores its time zone for cron evaluation. Non-existent DST times shift forward, and ambiguous times run once.
- Out of scope: DAG workflows, secrets management, fine-grained bin-packing.
Sizing
- 500k jobs, with most running every few minutes to hourly, gives an average of a few hundred to a couple thousand runs/sec. Minute boundaries are bursty, so plan for 5 to 10x the average at the top of each minute (up to roughly 10k dispatches/sec).
- Run rows are about 200 bytes. At 50M runs per day that is about 10 GB/day, so partition the table by time and expire old partitions.
- Logs are the largest volume. Stream them to object storage, never the OLTP database.
Architecture
Control plane:
- API service (stateless, behind a load balancer): job CRUD and run/log queries.
- Scheduler service: finds due jobs and creates runs.
- Reaper/watchdog: repairs stuck state.
Data plane:
- Durable queue (Kafka, SQS, or similar), with topics or queues per machine class.
- Worker fleet: pulls runs, executes them in containers, enforces timeouts, ships logs.
Storage:
- Relational DB (Postgres or MySQL, sharded by job ID when needed) for jobs and runs.
- Object storage for logs, with an index keyed by run ID.
The API talks to the DB synchronously. Scheduler to workers is asynchronous through the queue, which absorbs minute-boundary bursts and lets the worker fleet scale on queue depth.
Data model
jobs(job_id PK, owner, schedule, timezone, task_spec, resource_class, timeout_sec, timeout_action, catchup_policy, enabled, next_run_at)with an index on(enabled, next_run_at).runs(run_id PK, job_id, scheduled_for, status, attempt, worker_id, lease_expires_at, started_at, finished_at, deadline_at, log_uri)withUNIQUE(job_id, scheduled_for)and an index on(job_id, scheduled_for DESC).
The unique key is the dedup primitive: two schedulers can never create two runs for the same slot.
Scheduling logic
Each scheduler instance loops every second:
- In a transaction:
SELECT ... FROM jobs WHERE enabled AND next_run_at <= now() ORDER BY next_run_at LIMIT 500 FOR UPDATE SKIP LOCKED. - For each job, insert a
PENDINGrun (scheduled_for = next_run_at) and compute the newnext_run_atfrom the schedule. Under the coalesce policy this is the first slot after now. Under backfill it is the next slot, one at a time. - Commit, then publish run IDs to the queue.
Because the insert and the advance of next_run_at happen in one transaction, a crash either does both or neither. Nothing is skipped (the job remains due) and nothing is double-scheduled (the unique key and row lock prevent it). If the commit succeeds but publishing fails, the reaper republishes PENDING runs older than a threshold. Alternatively, use a transactional outbox. SKIP LOCKED lets many schedulers work in parallel without a leader. At larger scale, shard jobs by hash so each scheduler owns a shard.
Execution path
- A worker receives a run ID and attempts an atomic claim:
UPDATE runs SET status='RUNNING', worker_id=?, lease_expires_at=now()+30s, started_at=now(), deadline_at=now()+timeout WHERE run_id=? AND status='PENDING'. If zero rows change, another worker has it, so drop the message (this handles duplicate delivery). - The worker starts the task in a container with resource limits and streams output to object storage in chunks.
- A heartbeat extends
lease_expires_atevery 10 seconds. - On completion, the worker writes
SUCCESSorFAILEDwith the exit code and finalizes the log URI.
Timeouts
The worker enforces the deadline locally with a timer. On expiry it sends SIGTERM, then SIGKILL after a grace period, and applies the configured action:
- Kill and mark: status
TIMED_OUT. - Retry: create a new attempt with backoff, up to a cap.
- Trigger job: insert a run of another job.
- Mark failed only: leave the process if it is non-killable, and record it.
If the worker itself is dead or partitioned, the reaper catches deadline_at < now() for RUNNING runs and applies the same action. A worker that discovers it lost its lease must stop the task.
Failure handling
- Scheduler crash: the transaction rolls back or has committed. Other instances pick up the remaining due rows.
- Worker crash mid-run: the lease expires, and the reaper sets the run back to
PENDING(incrementing the attempt) and republishes it, or marks itFAILEDif the task is non-retryable. - Lost queue message: the reaper requeues
PENDINGruns older than a threshold. - Duplicate delivery: the atomic claim and the unique run key make it harmless.
- DB failover: use a synchronous replica. Writers retry, and due jobs remain due because
next_run_atis persisted. - Full restart: all state is in the DB, so on startup the schedulers see overdue jobs and apply the catch-up policy.
Query APIs
POST /jobs,GET /jobs/{id},PUT /jobs/{id},DELETE /jobs/{id}GET /jobs/{id}/runs?limit=N&cursor=...returns runs newest first with keyset pagination onscheduled_for.GET /runs/{run_id}returns status, attempt, timestamps, and exit code.GET /runs/{run_id}/logsreturns a pre-signed object-store URL, or a streamed range for live runs.
Scaling and trade-offs
- API and workers scale horizontally; workers scale on queue depth per machine class.
- The central bottleneck is the DB write rate on
jobsandruns. Mitigate with batching, time-partitioned run tables, sharding by job ID, and keeping logs out of the DB. - At-least-once with idempotent tasks gives the strongest "never skip" guarantee at the cost of occasional duplicates. Exactly-once would need fencing tokens and task-side cooperation.
- A polling scheduler is simple and robust. A timing wheel or in-memory heap could reduce DB reads, but it adds recovery complexity, so use it only if polling load becomes an issue.
Common mistakes
- Advancing
next_run_atin a separate transaction from run creation, which causes skips or duplicates. - Relying on in-memory timers or a single leader without persisted state.
- Storing logs in the relational DB.
- Not addressing the minute-boundary burst.
- Having no reaper, so worker deaths leave runs stuck in
RUNNINGforever. - Ignoring DST and time zones in cron evaluation.