Library / Blogs

Google SRE Book: Distributed Periodic Scheduling with Cron

Running scheduled jobs reliably across machines: leader election, state in a replicated store and avoiding duplicate runs.

By Google SRE team · Google · Added 2026-10-12

Open original source

All content belongs to Google SRE team / Google. We only link to it and give credit. Report a problem

Learn this article

About 37 min left. Your work is saved as you go.

What you are about to study

Google wrote this to explain how they thought about a problem. It assumes you are comfortable with distributed systems.

Ideas you will meet

Consensus
Raft, Paxos and how replicas agree on one order.
Distributed Systems
Consensus, time, failure and the fundamentals of scale-out.

What we already know about this

Our own lessons on these ideas. Read them here before you start, so it makes sense.

  • Advanced Distributed Systems · 12 minConsensus: Raft and PaxosHow a group of machines agrees on one order of operations even when some crash or messages are delayed, and why a majority is the magic number.Read here

    The problem consensus solves

    Several machines must agree on one sequence of operations (who is the leader, what is the next log entry, who owns a lock) even though machines crash and messages are delayed or lost. Without a protocol, replicas drift apart and two nodes may both believe they are the leader.

    Systems that rely on consensus include coordination services (etcd, ZooKeeper), many databases for their metadata or their data, and Kubernetes (through etcd).

    Why a majority

    A decision is valid when a majority (quorum) of nodes accepts it. Any two majorities share at least one node, so a later decision always meets someone who remembers the earlier one. A cluster of n nodes tolerates floor((n-1)/2) failures: 3 nodes tolerate 1, 5 nodes tolerate 2. That is why clusters have an odd number of nodes; a 4th node adds cost but no extra fault tolerance over 3.

    Raft in three parts

    Raft splits the problem so it can be understood:

    Figure SDA-ADS-01-1 · Raft roles and elections · © forcsguy.com

    1. Leader election. Time is divided into numbered terms. A node that hears nothing becomes a candidate and requests votes. A node votes at most once per term, and only for a candidate whose log is at least as up to date as its own. Randomised timeouts make split votes rare.
    2. Log replication. The leader appends a client command to its log and sends it to followers. When a majority has stored the entry, it is committed; the leader applies it and replies to the client. Followers apply committed entries in order, so every replica runs the same sequence.
    3. Safety. The vote rule guarantees that any new leader already has every committed entry, so committed entries are never lost or reordered.

    Figure SDA-ADS-01-2 · Replicating one write · © forcsguy.com

    Paxos, briefly

    Paxos reaches the same guarantee with two phases (prepare/promise, then accept/accepted) over a majority. It is famous for being hard to implement and explain, and for being the basis of many systems. Multi-Paxos repeats it for a log of decisions. Raft is essentially a clearer arrangement of the same ideas with a strong leader, which is why most new systems choose it.

    What consensus costs and what it does not give

    • Latency: every committed write waits for a majority round trip, so cross-region clusters are slow. Keep consensus groups within a region or use few, small groups for metadata.
    • Throughput: one leader handles all writes in a group. Large databases run many small groups (one per data range) to spread load.
    • Availability under partition: the minority side cannot make progress. This is the CAP trade-off made concrete: consensus systems are consistent first.
    • It does not remove all problems: slow nodes, clock assumptions, and reconfiguration (adding or removing nodes safely) need care.

    Where you will meet it

    Leader election for databases and queues, distributed locks and configuration stores, metadata for storage systems, and cluster state in Kubernetes. When a design needs "exactly one leader" or "all replicas agree on this order", you are describing consensus. See also the distributed-locks lesson in the core-concepts course.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Core Concepts: How Things Actually Work · 9 minDistributed locks and leader electionMaking sure only one worker does a job at a time, and why a lock needs a lease and a fencing token to be safe.Read here

    The need

    Sometimes only one worker may do something at a time: run a nightly job, update a shared resource, be the primary of a group. On one machine you use a mutex. Across machines you need a distributed lock or leader election, and failure makes it tricky.

    A naive lock and why it breaks

    SET lock:job 1 NX   (set only if not exists)
    ... do the work ...
    DEL lock:job
    

    Problems:

    • The holder crashes before deleting: the lock is stuck forever.
    • Add an expiry (a lease) to fix that, and a new problem appears: the holder is merely slow (a long pause, a network stall), the lease expires, a second worker takes the lock, then the first wakes up and keeps working. Now two hold it.

    Leases and fencing tokens

    A lease is a lock that expires unless renewed. It lets the system recover from failures, but it cannot, by itself, stop a stalled holder from acting after it has lost the lock.

    The fix is a fencing token: every time the lock is granted, the lock service hands out a number that always increases. The holder sends the token with every write to the protected resource, and the resource rejects any request with a token older than one it has already seen.

    Figure SDA-CORE-18-1 · Leases and fencing tokens · © forcsguy.com

    This makes safety depend on the resource, not on timing.

    Where to keep locks

    Use a service built for coordination, with consensus underneath: etcd, ZooKeeper, Consul. A single Redis instance gives a convenient but weaker lock (it can lose the lock on failover). If correctness matters, prefer a consensus-based service or a database transaction.

    Often you can avoid a lock: make the operation idempotent, use a conditional write (compare-and-set on a version), or let a queue hand each job to just one consumer.

    Air traffic control: one authority coordinates many independent actors, as a leader does in a clusterImage: Senior Airman John Wright · Public domain · Source · Wikimedia Commons: Lajes Field Air Traffic Control

    Leader election

    The same tools elect a leader: nodes compete to create an ephemeral key or hold a lease; the winner leads and renews it. If it fails, the lease expires and another is chosen. Followers watch for changes.

    • Expect brief periods with no leader during failover.
    • Guard against a former leader acting too late (fencing tokens again, or stepping down when it cannot renew).
    • Avoid split brain (two leaders) by requiring a majority (a quorum) to agree.

    Rules of thumb

    • Keep critical sections short, and renew the lease while working.
    • Prefer designs that need no lock: idempotency, conditional writes, partitioned ownership.
    • Always handle "I lost the lock" by stopping work.
    • Test with pauses and network partitions, not only crashes.

    More on this site

    Open this lesson with its quiz and exercise

  • Low-Level Design Practice · 11 minElevator systemRequests, directions and scheduling: a state machine per car and a dispatcher that decides which car answers which call.Read here

    The problem

    A building has several elevators. People press a button on a floor (a hall call with direction) and a floor button inside the car (a car request). The system moves cars, opens doors and decides which car should answer each call.

    Entities

    Figure SDA-LLD-07-1 · Elevator classes · © forcsguy.com

    One elevator as a state machine

    Figure SDA-LLD-07-2 · Elevator car states · © forcsguy.com

    A simple and effective scheduling rule is the elevator (scan) algorithm: keep two sorted sets of stops (above and below); continue in the current direction, serving stops in order; reverse only when none are left in that direction.

    class Elevator {
      floor = 0; dir: "UP" | "DOWN" | "IDLE" = "IDLE";
      up = new SortedSet<number>(); down = new SortedSet<number>();   // pending stops
    
      addStop(f: number) { (f >= this.floor ? this.up : this.down).add(f); if (this.dir === "IDLE") this.pick(); }
      private pick() { this.dir = this.up.size ? "UP" : this.down.size ? "DOWN" : "IDLE"; }
      step() {                                   // called once per tick
        if (this.dir === "UP") { this.floor++; if (this.up.deleteIfPresent(this.floor)) this.openDoors(); if (!this.up.size) this.pick(); }
        if (this.dir === "DOWN") { this.floor--; if (this.down.deleteIfPresent(this.floor)) this.openDoors(); if (!this.down.size) this.pick(); }
      }
    }
    

    Many cars: the dispatcher

    Figure SDA-LLD-07-3 · Assigning a hall call · © forcsguy.com

    Make the dispatcher a strategy so you can swap "nearest car" for "least loaded" or a smarter estimate without touching Elevator.

    Design notes

    • Concurrency: calls arrive while cars move. Use one event loop per elevator, or a queue per car, so state changes happen one at a time.
    • Safety: doors must not close on a blocked sensor; weight limits stop a car from moving.
    • Peak modes: morning (send idle cars to the lobby) and evening patterns are policies.
    • Extensions: express cars, destination dispatch (people enter their destination at the hall), emergency and maintenance modes.

    Real-world reading

    Open this lesson with its quiz and exercise

Go deeper on this

A path through videos, articles, other case studies and code on the same ideas as Google SRE Book: Distributed Periodic Scheduling with Cron.

  1. Warm upGet the vocabulary first.

  2. WatchHow others solve the same problem, on video.

    Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)

  3. ReadEngineers explain it in their own words.

  4. See it in another companyThe same ideas, a different system.

  5. Read the codeSee how it looks when it is real.

Keep learning

Loading community…