Skip to content

Schedule work without losing ownership

10 min reading

Design recurring/delayed work, worker claims and recovery

Page details

System Design · Move work through time

10 min reading · 23 min with practice

Sources

Published · Last edited:

Prerequisite: Choose queues, streams and pub-sub. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. Northwind’s cleanup scheduler pauses after claiming unfinished image intents. A replacement begins recovery, then the original resumes with its earlier work list. Both processes intend to help, but their overlapping effects may violate the publication rules.

Dev: “The old claim expired, so we started another worker.”

Priya: “What tells the effect boundary to reject the old worker when it returns?”

Separate a due time, a logical occurrence and authority to carry out its effects. Choose overlap and missed-run behavior deliberately. Keep object readiness and pending publication from page 17 in the cleanup contract rather than treating every old object as removable.

Which occurrence is due, and who may finish it?

A schedule defines when an occurrence should become eligible to run. A durable occurrence record can distinguish due, claimed, running, completed and unresolved work. A process noticing the clock is not sufficient evidence that the intended occurrence was created once or completed successfully.

For this hypothetical sweep, identify an occurrence by the schedule identity and its intended scheduled instant. A delayed attempt should retain that identity rather than becoming a new logical occurrence merely because it starts later. Attempts and occurrences are separate in the same way that deliveries and product-update intents were separate in Page 20.

State what a sweep does. Here it inspects expired upload intents and decides which require recovery or are eligible for cleanup. It does not blindly delete every object absent from one momentary query result. Pending publication, allowed rollback and in-flight readers still constrain the decision.

Claim work under an explicit rule

Several scheduler or worker instances can inspect the same due set. A claim mechanism must make the selected ownership transition exclusive under its database or coordination contract. Merely reading “unclaimed,” then writing an owner in a separate unprotected action, leaves a race where two processes can both proceed.

A claim can include owner identity, an expiry and a monotonically advancing ownership generation. Heartbeats can renew a valid claim. Expiry permits recovery after a lost worker, but it does not reach into a paused process and prevent its later instructions from executing.

Expiry permits reassignment but does not stop an old processOne durable occurrence is first claimed with generation seven. After expiry it is reassigned with generation eight. The effect boundary checks current authority and rejects a resumed generation-seven worker.One occurrenceDurable identityOld claim: generation 7Paused, then resumedNew claim: generation 8Current authorityEffect boundary must reject obsolete authority.
A timer supplies evidence for recovery; enforcement protects the effect.

Make a lease token visible to the effect target

Hypothetical scenario. Cleanup occurrence C owns generation 7 until its claim expires. A replacement obtains generation 8. The earlier worker can remain paused through expiry and then resume; its own duration clock cannot establish that no replacement exists.

Make a lease token visible to the effect target — selected design evidence
IdentitySelected valueWho enforces it
Occurrencecleanup C at scheduled instantScheduler state
Claim generation7 then 8Atomic claim authority
Effect tokengeneration 8 requiredMetadata target transition
Expiry permits replacement; target enforcement prevents a resumed old owner from changing protected state.Expiry permits replacement; target enforcement prevents a resumed old owner from changing protected state. Old worker 7 to Claim authority: 1 · pause; lease expires; Claim authority to Target: 2 · generation 8 becomes current; Old worker 7 to Target: 3 · stale generation 7 rejected.Old worker 7Claim authorityTarget1 · pause; lease expires2 · generation 8 becomes current3 · stale generation 7 rejected
Expiry permits replacement; target enforcement prevents a resumed old owner from changing protected state. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

The protected metadata target must reject generation 7 after accepting generation 8 under the selected fencing rule. A process checking its lease before starting a network call leaves a pause window between check and effect. A token carried only in logs has no enforcement power. The target needs a monotonic comparison at the guarded transition, combined with the object publication and retained-reference rules.

Calendar scheduling answers when an occurrence is due. A monotonic duration clock helps measure local elapsed waiting. Neither makes a remote lease holder disappear. Choose whether missed calendar occurrences are skipped, coalesced or replayed, and retain their stable occurrence identities. Recovery capacity must cover the selected missed-run policy without launching every historical sweep at once.

Work through overlapping runs

Hypothetical worked example. Choose a sweep interval of sixty seconds and a run duration of ninety seconds. A run starts at time zero and would finish at ninety. The next scheduled instant is sixty. If both run, their overlap is 90 − 60 = 30 seconds.

A policy can permit overlap, skip a new occurrence while the previous one is active, or request replacement of the old execution. These choices are not equivalent. Allowing overlap needs safe concurrent effects; skipping affects when unfinished work is inspected; replacement needs recovery from an interrupted attempt.

A replacement request is not proof that every old external operation was cancelled. A process can be delayed after it sent a request, and a remote effect can finish later. The protected state transition must still recognize which authority or object version was permitted to act.

Follow a lease through a pause

Choose a claim made at time zero with a thirty-second lease and generation 7. Its worker pauses and does not renew. At time thirty-five, another worker obtains generation 8 under the selected atomic claim rule. The old worker resumes at time forty.

The old worker is 40 − 30 = 10 seconds beyond its original expiry. That arithmetic does not prevent its code from running. A protected effect needs to reject generation 7 after generation 8 became authoritative. This exclusion is often called fencing; it must be enforced at a boundary the old worker cannot bypass.

If the external object operation cannot enforce that generation directly, the application needs another supported protocol. For cleanup, a conditional metadata decision plus a carefully controlled object-deletion path may be part of it. A local ownership flag alone cannot certify safety for an unconstrained remote deletion.

Account for inspection capacity

For a separate selected sweep estimate, choose one hundred candidate intents and a worker inspecting twenty per second. The scan portion takes 100 ÷ 20 = 5 seconds before recovery actions, object operations and retries. A ninety-second observed run therefore cannot be explained by that scan count alone.

Inspect the other stages rather than increasing scan concurrency reflexively. A remote deletion path, lock wait or repeated unresolved object check can dominate. An oldest-unfinished-intent signal tells a different story from the count of scheduler ticks that fired.

Define missed occurrences before an outage

If the scheduler is unavailable across several intended instants, decide whether to replay every occurrence, coalesce into one current sweep or declare old work expired. A current-state cleanup scan may not need one run for every missed minute. A required periodic financial calculation could have a very different obligation.

Also define the clock and time-zone interpretation for calendar schedules. A repeated local clock reading is not automatically a unique occurrence. The next lesson develops event identities and order; here the schedule record must preserve the intended occurrence independently of an attempt’s wall-clock start.

In the wild: CronJob policy has a bounded scope

Kubernetes CronJob documentation describes scheduling behavior and concurrency policy. It also explains why scheduled work should tolerate the possibility of repeated or missed creation. Use the documented policy scope rather than assuming a scheduler provides a universal once-only business effect.

Northwind still owns its occurrence identity, cleanup eligibility and external-effect protection. A deployment controller can manage process lifecycle while a separate application protocol determines whether deleting a particular object remains authorized.

When the old cleanup list resumes

Hypothetical failure scenario. The original sweep decides that an upload object is unreferenced, pauses, and resumes after another worker finishes publishing that object. Deleting from the old list now breaks a ready product reference. The earlier read was evidence about an earlier state, not permanent authority to delete.

Revalidate the required object/version and publication state at the protected decision boundary. Ensure the chosen deletion protocol cannot act on obsolete authority after publication wins. A shorter lease or faster heartbeat does not repair this stale-decision race by itself.

Schedule only the obligation the product needs

Use recurring scheduling when time-based eligibility is a real requirement. Prefer an event-triggered task where a known state change directly identifies required work, while retaining a sweep for recovery if justified. Running the same full scan ever more frequently can hide a missing state transition and add load.

Northwind chooses a recoverable sweep with explicit overlap, missed-run and cleanup rules. The next page gives occurrences, logical operations and delivery attempts distinct identities, then separates identity from chronological and causal order.

Challenge the proposed mechanism

An object delete API cannot compare fencing tokens. Can a token on the scheduler row make that delete safe?

Reveal the design reasoning

No. Guard deletion eligibility through an enforceable metadata lifecycle or choose a target protocol that supports the needed condition. Identify the last irreversible operation and close the pause window there. Do not claim fencing beyond that boundary.

Decision and reconsideration: Fence the protected transition and bound missed-run admission. Revisit the design when a new effect bypasses the guarded target.

Inspect the owner at the effect

  1. A ninety-second job runs every sixty seconds. What overlap occurs if both execute?

    Compare duration and interval

    Thirty seconds in the selected example. An overlap policy must explain effects during that interval rather than merely counting active processes.

  2. The old lease expired ten seconds ago. Can its paused worker still send a deletion?

    Separate expiry from enforcement

    Yes, the process may resume. Safety requires rejecting obsolete authority or state at the relevant effect boundary, not assuming expiry stopped the process.

  3. Should every missed minute create another current-state cleanup sweep?

    Choose missed-run semantics

    Not necessarily. Coalescing may satisfy this inspection contract, while other scheduled obligations require each occurrence. State the product meaning before selecting replay behavior.

A scheduler needs a stable way to identify an occurrence and distinguish it from later attempts. Page 23 develops identity and ordering without treating a wall-clock timestamp as an answer to every question.

Northwind decision log

Identify the scheduled occurrence separately from its execution attempts.
Choose overlap and missed-run behavior explicitly.
Protect cleanup at the effect boundary against obsolete claims and stale decisions.

Go deeper: concurrency and recovery