Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 14: Orchestration and Recovery

Week 14 / Lesson 3

Coordinating concurrent workers

Prevent stale or duplicate workers from committing conflicting results.

Section 3.1 1 of 7

Overview

Focus

Prevent stale or duplicate workers from committing conflicting results.

Your route through the lesson

  • 3.2 At-least-once job delivery
  • 3.3 Leases, fencing tokens, and conditional updates
  • 3.4 Transactional results and queue-age metrics
  • 3.5 Put it into practice
  • 3.6 Guided comparison
  • 3.7 A paused worker returning after lease expiry

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 7

At-least-once job delivery

Focus

Design for duplicate delivery while separating jobs, attempts, and results.

A queue may deliver a job more than once when acknowledgments are lost or workers fail. At-least-once delivery means eligible work is not intentionally lost, while duplicates remain possible. Treating every delivery as a new business operation can duplicate effects. Job identity should remain stable across attempts; attempt identity can change to support diagnostics.

Suppose job J calculates one invoice total. Worker A receives J, computes a result, and pauses. The queue redelivers J to worker B. Both workers now have legitimate historical reasons to be running, but only one current result should be committed. Deduplicating messages before work helps efficiency, yet storage must also reject conflicting final writes because a duplicate can escape earlier checks.

Use a unique result key for the logical job and a conditional commit that checks current ownership or generation. A count of worker completions is not a count of distinct jobs. Report deliveries, attempts, and accepted logical results separately. This makes duplicate handling visible and avoids claiming exactly-once execution when the actual guarantee is one accepted result despite multiple executions.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Job J is delivered twice to two workers. How many logical jobs exist?
2. Two workers execute J but storage accepts one result. Accurate guarantee?
3. Why report deliveries separately from accepted results?

Section 3.3 3 of 7

Leases, fencing tokens, and conditional updates

Focus

Use fencing tokens so storage rejects an expired worker even if it resumes.

A lease grants a worker temporary ownership. If the worker stops responding, the lease can expire and a replacement can take over. Expiry alone does not stop the old process: it may be paused by scheduling or a network partition and resume later. A local check saying my lease was once valid cannot protect storage from that stale worker.

A fencing token is a monotonically increasing generation assigned on takeover. Worker A receives token 1. Replacement B receives token 2. Every commit carries its token, and storage accepts only the current token. After takeover, a delayed token-1 write is rejected even if A still believes it owns the job.

The crucial check is at the resource accepting the result. Checking only in the worker leaves a gap between checking and writing. A database conditional update can require matching job identifier, token, and an empty result slot in one statement. rowcount reports how many rows changed: one means the condition matched, zero means the attempt failed. A lease is a liveness mechanism for replacing workers; fencing provides the stale-write safety boundary.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Worker A token 1 resumes after B gets token 2. What must storage do with A output?
2. Why is checking a lease only before computation insufficient?
3. A conditional update matches zero rows for a stale token. What does rowcount=0 mean?

Section 3.4 4 of 7

Transactional results and queue-age metrics

Focus

Commit results transactionally and measure waiting separately from work duration.

A worker result, its accepted token, and the terminal task status should agree. A transaction can publish them together so a crash cannot leave a done status beside a missing result. A unique job key and conditional write prevent duplicate attempts from producing multiple accepted rows. These storage constraints complement rather than replace correct computation.

The weekly fixture uses two real threads with separate SQLite connections. BEGIN IMMEDIATE acquires write access before the replacement increments the token and commits its result. The old thread is deliberately paused using threading.Event. An event is a signal: set marks it ready, and wait blocks until it is set or a timeout expires. Timeouts bound a broken demonstration instead of hanging indefinitely.

Operational metrics should distinguish queue age from execution time. Queue age measures how long an eligible job has waited since enqueueing; execution time measures a started attempt. A workflow can have fast workers and poor response time if jobs wait behind capacity limits. Track stale commit rejections and duplicate deliveries too. Rising counts may reveal overly short leases or unstable workers even when final correctness remains protected.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Workers run quickly but jobs wait ten minutes before starting. Which metric exposes this?
2. Why use separate SQLite connections for the two worker threads?
3. Stale commit rejections rise while final results remain correct. Useful interpretation?

Section 3.5 5 of 7

Put it into practice

Focus

Run a genuine concurrent stale-worker rejection against transactional storage.

Download week14.py, save it in an exercise folder, and run python week14.py --lesson 3. This single practice uses two local threads and a temporary SQLite file; no external queue or service is required. The processor-only run normally finishes within seconds, with five- and ten-second timeout guards for unexpected stalls.

The initial jobs row contains job1, token 1, and a null result. NULL represents the absence of a stored value. The old worker reads token 1 and signals that it is paused. The replacement waits for that signal, begins a transaction, advances the token to 2, stores fresh, and commits. Only then does the replacement signal the old worker to resume.

The old worker attempts an update requiring token 1 and result IS NULL. Neither condition now permits its stale write, so rowcount is zero. The replacement's rowcount is one. Final SELECT must return (2, 'fresh'). ThreadPoolExecutor.submit starts each function and returns a future; result(timeout=10) obtains its result or raises a failure. These checks prove a real overlapping execution schedule with storage rejection, while lease expiration itself is represented by the deliberate takeover rather than a production clock service.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Replacement commits token 2 and fresh before old token 1 resumes. Final expected row?
2. Two threads overlap: an old worker pauses, a replacement commits a new token, and SQLite rejects the resumed stale write. What makes this runtime evidence?
3. A test uses real threads and SQLite conditional writes but manually triggers takeover without a lease clock or queue service. What remains simulated?

Section 3.6 6 of 7

Guided comparison

Focus

Explain the accepted and rejected writes in their actual execution order.

The worked schedule is deterministic because events control the critical moments. First the old worker reads generation 1 and pauses. Next the replacement obtains the write transaction, increments generation to 2, and stores fresh in the previously empty slot. Commit makes that state visible before replacement_done is signaled.

The old worker then resumes carrying its old token. Its update checks both token equality and absence of a result. The current token is 2 and the result is already fresh, so storage changes no row. The assertion checks zero rather than assuming that an old worker would voluntarily abandon its result. This matters because stale workers can be buggy, paused, or disconnected from the scheduler.

Final inspection confirms one row, current generation 2, accepted result fresh. Correctness here means conflict control, not correctness of a model-generated answer. Both result strings are fixed fixtures. A production system still needs input validation, result verification, durable ownership transitions, suitable lease durations, and receiver-side effect protection. The storage invariant is a valuable component because it remains effective when the old worker resumes unexpectedly, but it is not a complete orchestration platform by itself.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. An old worker waits for an event; its replacement signals that event only after committing its transaction. What occurs before the old worker resumes?
2. Does a token check prove the accepted answer is mathematically correct?
3. Why assert the stale update rowcount rather than trust a worker promise?

Section 3.7 7 of 7

A paused worker returning after lease expiry

Focus

Reject a paused worker after lease expiry without relying on its cooperation.

A report worker receives lease generation 41 and starts a long calculation. Its process pauses for several minutes. The coordinator expires the lease and assigns generation 42 to a replacement, which publishes the current report. When the first process resumes, it may still hold an in-memory flag saying owner=True.

The worked storage rule accepts a report only when its supplied generation equals the current generation. The resumed worker sends 41; storage has 42 and rejects the write. Its old ownership flag does not matter. If the report must also trigger an external effect, that receiver needs an appropriate idempotency or fencing contract; protecting the report table alone does not automatically protect an unrelated email or payment service.

Lease duration influences efficiency. Too short produces unnecessary takeovers; too long delays recovery after real failure. Neither tuning choice replaces fencing because pauses can exceed any chosen duration. Audit the rejected generation, current generation, job identifier, and reason without treating the rejected worker as a new successful result. This preserves one current accepted artifact while retaining evidence of wasted or stale work.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A resumed worker holds owner=True but generation 41; storage has 42. Which controls commit?
2. Fencing protects a report table. Does it automatically deduplicate an unrelated email service?
3. Increasing lease duration eliminates all stale-worker risk. Correct?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Delegating a verifiable task →