Learning pathsPricingChecking sign-in…
Patterns

Managing Long Running Tasks

Long tasks outlive ordinary HTTP requests and often outlive the process that started them.

What, why, when and how

What is it?

Long-running tasks execute outside the lifetime of an ordinary request and expose durable progress and completion state.

Why is it needed?

A browser disconnect or API timeout should not lose an accepted export, analysis job or media conversion.

When should I use it?

Use asynchronous jobs when work exceeds the response deadline, requires retries or needs bounded scheduling.

When should I choose something else?

Keep fast, predictable work synchronous when that gives a simpler useful response. Moving work to a queue introduces completion delay and operational state.

How do I use it?

Persist a job ID, enqueue durably, lease bounded work, checkpoint useful progress, fence stale workers, and expose status, cancellation and result retention.

Can you show a concrete example?

An export worker loses its lease after writing temporary output. Its replacement receives a newer attempt epoch. Only the current owner can publish the result pointer, so the delayed worker cannot overwrite the replacement output.

Worker A owns job j7 with epoch 9; A loses lease; replacement B owns epoch 10; Publishing rejects epoch 9; B can commit
Managing Long Running Tasks: one concrete example
Read the diagram

Worker A owns job j7 with epoch 9; A loses lease; replacement B owns epoch 10; Publishing rejects epoch 9; B can commit

Open original
Managing Long Running Tasks: worked example
Worker A owns job j7 with epoch 9; A loses lease; replacement B owns epoch 10; Publishing rejects epoch 9; B can commit

Managing Long Running Tasks: one concrete example

Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.

Long tasks outlive ordinary HTTP requests and often outlive the process that started them. The API should promise durable acceptance and provide a way to inspect progress. Reliability comes from explicit state, recoverable ownership, checkpoints, and bounded retries—not from holding a connection open until something eventually finishes.

Learning goals

202 acceptance; job IDs; durable state; leases; heartbeats; checkpoints; retries; cancellation; deadlines; result ownership; fairness.

Reject a stale attempt's finished result

Job j7 runs under worker A's lease epoch 9. A stops heartbeating. After the declared expiry, B acquires epoch 10 and resumes checkpoint 3. A wakes up and reports success for epoch 9. The result store compares the epoch and refuses A's write; B's epoch remains authoritative. A process-local flag or queue visibility timeout alone cannot enforce this at the result store.

RecordBefore pauseAfter takeover
Job j7 owner epoch910
Checkpoint3At least 3 under valid writes
A's late resultNot yet committedRejected as stale
Record / Before pause / After takeover; Job j7 owner epoch / 9 / 10; Checkpoint / 3 / At least 3 under valid writes; A's late result / Not yet committed / Rejected as stale
Reject a stale attempt's finished result
Read the diagram

Record / Before pause / After takeover; Job j7 owner epoch / 9 / 10; Checkpoint / 3 / At least 3 under valid writes; A's late result / Not yet committed / Rejected as stale

Open original
Reject a stale attempt's finished result
Record / Before pause / After takeover; Job j7 owner epoch / 9 / 10; Checkpoint / 3 / At least 3 under valid writes; A's late result / Not yet committed / Rejected as stale

Reject a stale attempt's finished result

A queue redistributes work when acknowledgement/visibility rules require it. A lease identifies current ownership, a heartbeat extends it, and a checkpoint limits repeated compute; these are separate mechanisms. Keep checkpoints deterministic and versioned against input and code. An external email or payment needs its own stable identity because rejecting A's final result cannot undo an earlier external effect.

Separate short interactive jobs from long batch work with bounded queues and scheduling shares. Estimate concurrency from runtime and measured service capacity, not merely queue length. Persist dependency completions and cancellation intent. Cancellation may stop new work while an in-flight effect still resolves; terminal states need a declared precedence and reconciliation policy.

Show answer and explanation

Answer: Accepting A's stale result because “the work completed” violates ownership. Compare epoch 9 to 10 at the commit boundary. Repeated failures enter a diagnosable quarantine/DLQ without losing the job's identity or hiding it as success.

Step-by-step reasoning

1. Create a durable job contract

POST /jobs validates the request, stores a job and outbox event, and returns 202 with a status URL. Record the input version, owner, deadline, and idempotency identity. The status endpoint distinguishes queued, running, succeeded, failed, and cancelled. Progress is informative but should not be mistaken for a committed result.

2. Lease and checkpoint execution

A worker claims an attempt token and renews a lease while active. Checkpoint expensive progress under that attempt’s ownership. If the worker disappears, another can resume from a verified checkpoint or restart. Choose checkpoint frequency by balancing repeated work against checkpoint cost.

3. Fence completion and cancellation

A lease can expire while a paused worker is still alive. Publish results only with the current token and allowed state transition. Cancellation also needs an explicit race rule: if cancellation commits first, later success publication is rejected; if success commits first, cancellation reports that the task already completed. External effects may require compensation.

4. Manage fairness and deadlines

Separate short interactive jobs from large batch tasks, apply tenant quotas, and bound retries. Retry transient infrastructure failures, but do not repeatedly run a permanently invalid input. A deadline should stop useless work and trigger a visible terminal or repair state. Measure oldest job age and time spent in each stage.

Contracts and state

The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.

Contract / pseudocode
Job(id, owner, input_version, state, deadline, current_token)
Attempt(job_id, token, lease_until, checkpoint_ref)
POST /jobs/:id/cancel -> conditional transition
Publish result WHERE state='running' AND token=current_token

Worked example

An export worker finishes generating a file just as the user cancels. If cancellation wins the state transition, the worker must not expose a success link afterward. Its uploaded object becomes cleanup work. If success wins first, the cancellation endpoint returns the completed status. A single authoritative state transition gives the interface a coherent answer even when the two events are nearly simultaneous.

Failure walkthrough

A worker heartbeats successfully but makes no useful progress because one dependency hangs. Heartbeats show liveness, not progress. Track stage duration and checkpoint advancement, apply dependency deadlines, and enforce the job’s overall deadline. When retries exhaust the budget, retain diagnostic state and allow an intentional user or operator retry with clear semantics.

Worker uploads output → User requests cancellation → Cancel transition commits → Worker tries success transition → Reject result; schedule cleanup
Managing Long Running Tasks · scenario walkthrough
Read the diagram

Worker uploads output → User requests cancellation → Cancel transition commits → Worker tries success transition → Reject result; schedule cleanup

Open original
Managing Long Running Tasks · scenario walkthrough
Worker uploads output → User requests cancellation → Cancel transition commits → Worker tries success transition → Reject result; schedule cleanup

Managing Long Running Tasks · scenario walkthrough

Decisions and trade-offs

MechanismPurposeLimitation
LeaseRecover abandoned ownershipOld worker may still run
CheckpointReduce repeated workMust match input and attempt
FencingProtect final stateDestination must enforce it
DeadlineBound useless workExternal effects need cleanup

Check your understanding

An old worker uploads a result after cancellation. What should become visible to the user?

Show answer and explanation

Answer: The authoritative cancelled state should remain if it won the transition. Reject stale result publication and clean up the unreferenced object. Uploading bytes alone must not change the job’s terminal state.

Transfer to a new scenario

Cancel an export while a worker is uploading output and define which terminal result wins.

What stops a worker that lost its lease from committing a stale result?

Continue the connection

Study Multi-step Processes and explain which guarantee from this lesson carries into that topic.

Track ownership and checkpoints independently

Accept a task as a durable resource and return its ID. Workers claim a lease, checkpoint progress and publish terminal state. The queue is a delivery mechanism; the task record explains what the user requested and which attempt currently owns completion. Keep attempt history so retries do not erase evidence.

A checkpoint should represent completed, reusable work. For a video job, that may be a verified chunk output; for a bulk export, a source snapshot and last emitted key. Saving an arbitrary in-memory offset without the associated output commit can skip or duplicate data after recovery.

Cancellation is a request, not a guarantee that every effect vanished. Workers check it at safe boundaries, stop new work and clean up temporary output. Hard termination limits resource use, while conditional result commits prevent a killed or expired attempt from overwriting a newer outcome.

A decision worksheet for Managing Long Running Tasks: read the mechanism and its guarantee together.
A decision worksheet for Managing Long Running Tasks: read the mechanism and its guarantee together.
Read the diagram

Mechanism / Purpose / Limitation; Lease / Recover abandoned ownership / Old worker may still run; Checkpoint / Reduce repeated work / Must match input and attempt; Fencing / Protect final state / Destination must enforce it; Deadline / Bound useless work / External effects need cleanup

Open original
Managing Long Running Tasks choices for this workload
A decision worksheet for Managing Long Running Tasks: read the mechanism and its guarantee together.

A decision worksheet for Managing Long Running Tasks: read the mechanism and its guarantee together.

Operational sketch

Contract / pseudocode
job(id,state,generation,lease_until,checkpoint)
claim increments generation
heartbeat extends only current generation
complete WHERE generation=:mine AND state="running"
cancel records intent; worker acknowledges cancellation

A tempting mistake

A heartbeat can continue while useful work is stuck. Monitor progress age separately from lease age, and bound retries by elapsed time, attempts and business deadline.

Transfer exercise

What if the worker uploads its result then loses the lease before committing?

Show answer and explanation

Answer: The conditional commit fails. Keep the result attempt-specific and let garbage collection remove it unless a current attempt explicitly adopts and verifies it.

Your study notes