• Published
  • Reading time13 min
  • Sections11
  • Byheap.page

A job spans two systems without one transaction

Your database can commit a job record; ECS can accept a task launch. They do not share a transaction. The critical case is a crash after ECS accepts RunTask but before your database saves the task ARN. The job looks unstarted while compute is already running. A new token on retry can turn one customer request into two tasks.

Persist server-authorized intent first: owner, immutable launch input, stable clientToken, original expiry and capacity reservation. Then call ECS outside the database transaction. A lost response is an unknown outcome. Recover it using the saved request and token while the ECS idempotency window is valid, and keep an unresolved state when recovery is not yet possible.

The ledger and the task are different state machines. The ledger records what your service authorized and still owes; ECS records what compute actually did. Events help them converge quickly, while periodic reconciliation repairs missed observations and controller crashes. Neither system’s temporary silence is proof that the other did nothing.

The invariant, independent of language
authorize owner → reserve capacity → persist immutable intent
submit the same request with the same clientToken
record the task ARN, or preserve an unknown outcome
at expiry: request StopTask and keep observing
on confirmed STOPPED: release the slot once
retry external-data cleanup independently

Database uniqueness is only one piece. An ON CONFLICT result does not authorize a second caller, reserve a global slot or prove that two launch requests match. Compare the canonical request under the same owner. Reserve per-owner and global capacity transactionally, and increment counters only for newly admitted work.

There are three different clocks

A retry window, a job deadline and a shutdown grace period are not interchangeable.
ObservationWhat it meansWhat to check
ECS clientToken retentionDeduplicates the same supported request within ECS’s retention window.For RunTask, the window is the shorter of 24 hours and task lifetime plus one hour. It is not an indefinite exactly-once guarantee.
Application deadlineStates when your service must begin terminating the job.Persist one UTC expires-at value. A retry, lease renewal or restarted watcher must not move it forward.
stopTimeoutAllows graceful shutdown after the stop signal before forced termination.It is not a task execution TTL. A local waiter or network read timeout does not cancel AWS compute.

A trusted reconciler must live outside the task and independently of the request process. It reads bounded batches of due or unresolved jobs, claims them under expiring leases and reclaims abandoned leases. It also handles reserved jobs without an ARN, ambiguous submissions and jobs already marked stopping. Running a watcher in a terminal does not supply those recovery properties.

A deadline is not an instantaneous hard kill. Reconciliation cadence, API latency, shutdown grace and resource deprovisioning add overshoot. Measure expiry-to-STOPPED time and set a documented bound from the workload. Pair runtime limits with admission caps, maximum configured resources and output limits; billing alerts report spend but do not stop task creation.

Cancellation has its own authorization and race conditions. Resolve the job owner before contacting AWS, persist stopping intent, then call StopTask. A completion event can arrive at the same time as cancellation. Both paths must converge on one terminal transition and one capacity release. Do not put StopTask permission in the untrusted task to let it enforce its own budget.

Correctness lives at the failure boundaries

Test the moments between durable state and external effects.
ObservationWhat it meansWhat to check
Response lost after launchECS may already have accepted the task.Recover the original task with the exact request and token; require one reservation and no second launch.
Controller dies before expiryA request-process timeout is not a compute deadline.The independent reaper must observe expiry and reach STOPPED. Measure the overshoot instead of assuming zero delay.
Repeated stop eventsEvents and observations can be duplicated or arrive late.Keep terminal transitions idempotent; release one slot and never resurrect a stopped ledger row from an older event.
Idempotency window expiresReusing the token no longer supplies the original deduplication guarantee.Reconcile saved identifiers and unresolved launch evidence. Do not blindly create a new token for the original job.

RunTask can return an HTTP success response containing placement failures. Inspect failures and task count before recording an accepted launch. Keep known placement failures separate from an API response that was never received: the retry and reservation decisions are different.

Find the state that stopped progressing

Track counts and maximum age of reserved, running, stopping and unresolved jobs. Correlate the internal job ID, original expiry, task ARN, task-definition revision and last observation. An HTTP error-rate dashboard misses a controller that returned success and then abandoned compute.

Repair the transition rather than hiding the symptom.
ObservationWhat it meansWhat to check
Task outlives deadlineThe expiry or recovery path was not enforced.Check worker heartbeat, claim lease, original UTC expiry and StopTask outcome. Do not extend expiry to make the alert disappear.
StopTask AccessDeniedThe trusted control identity cannot stop the intended resource.Identify caller, action, task and cluster; inspect applicable policy boundaries before adding only the missing permission.
Stuck stoppingStop intent is not yet a confirmed terminal observation.Compare the request time, grace period and ECS state. Keep the unresolved reservation visible and escalate persistent failures.
Capacity stays fullCompute termination and reservation release have diverged.Join terminal task evidence with unreleased slots; repair through the same idempotent transaction, not a guessed counter reset.

Recovery ends with two receipts

The first receipt is confirmed compute termination with the stopped reason and container outcome. The second is completed external-data cleanup under your retention policy. A failed object deletion must remain visible without turning a stopped task back into a running job or decrementing its capacity twice.

Before retiring a test environment, close admission, inspect every non-terminal or unresolved ledger row and compare it with actual task state. Do not delete the ledger first. Preserve enough evidence to recover an uncertain launch after a process restart, and keep cleanup attempts bounded with an explicit next owner when the retry budget is exhausted.

Worked example: the API times out after AWS accepts the task

Imagine a report job accepted at 12:00 with an absolute expiry of 12:10. The controller commits its job row, concurrency reservation, immutable launch parameters and client token. At 12:00:02 it sends RunTask. AWS accepts the request, but the response is lost before the controller stores the task ARN. The customer retries at 12:00:05. Starting again with a new token could create two reports and consume two tasks while the database still shows one reservation.

The retry should find the original job identity and recover the original launch intent. Within ECS’s documented idempotency scope and token lifetime, repeat the same request with the same token and parameters. A changed image, role or subnet is a different request, not a harmless retry. If the idempotency window has expired or the state cannot be resolved, keep the launch marked outcome-unknown and reconcile observed tasks. Do not invent a failure result merely because your HTTP client stopped waiting.

At 12:10, the independent deadline worker records stop intent. It requests StopTask and retains the capacity reservation while termination is unconfirmed. A successful stop request is not the terminal receipt. The reconciler observes STOPPED, records the stopped reason and container outcome, and releases the reservation exactly once. Output collection and external-data deletion remain separate transitions. A late success event must not resurrect an expired job or publish a report after the owner has cancelled it.

These times are illustrative policy choices, not recommended universal limits. The important invariant is that every actor preserves the original expiry. A retry does not get another ten minutes. A lease renewal does not extend the customer’s deadline. If shutdown and reconciliation can continue after the deadline, define that cleanup interval explicitly and budget for it. Otherwise “ten-minute maximum” silently means ten minutes plus an unbounded period of orphaned compute.

Launch idempotency does not make the work exactly once

Stripe’s idempotency essay addresses an ambiguity common to distributed systems: the caller may not know whether the server acted before a connection failed. A stable operation identity lets a retry recover an earlier result. Applied here, that principle protects task creation. It does not automatically protect a payment, email or database write made by the code inside the task. Those effects need their own stable business key and durable acceptance rule.

Suppose a report task writes an output object and then loses connectivity before updating its job record. A later attempt should not overwrite unrelated output or send the customer two completion emails. Publish through a trusted commit step keyed by the logical job, recording the accepted artifact digest and version. A conditional database transition can choose one accepted result. Multiple temporary artifacts may still exist and need cleanup; choosing one result is not the same as proving there was one physical execution.

Define three identities: the logical job, an execution attempt and the AWS task ARN. The logical job carries customer authorization and the final business outcome. The attempt carries an immutable launch request, token, timing and diagnostics. The ARN identifies observed compute. Merging these into a single status column makes an ambiguous launch indistinguishable from a retry that definitely ran, and makes it difficult to explain why two task ARNs belong to one user-visible operation.

Use a short transaction to claim an expired reconciliation lease, then perform network operations outside the database lock. On return, update with a compare-and-set condition tied to the lease or state version. A slow worker whose lease expired must not overwrite newer evidence from its successor. Leases coordinate trusted workers; they do not fence side effects performed by malicious application code. For those effects, enforce authorization and idempotency at the destination that actually accepts them.

What Step Functions and Scheduler do—and what remains yours

Yan Cui’s timeout discussion helps separate a state’s timeout from the lifetime of the entire workflow. A task-level catcher is not a universal handler for an execution-level timeout. With an ECS .sync integration, Step Functions can attempt to cancel underlying work when the state is aborted, but the documented cancellation is best effort and depends on permissions and service behavior. Treat a workflow timeout as a trigger for reconciliation, not proof that compute has disappeared.

EventBridge Scheduler has another boundary: delivery of the target invocation. Delivery retries and a dead-letter queue address failure to deliver the scheduled action. They do not observe whether a container launched successfully, processed every record or committed its business output. Cloudonaut’s older resilient scheduling article makes this distinction useful, although its original architecture predates today’s Scheduler service. Apply the principle to the current target integration rather than copying the old service arrangement.

For an important nightly import, retain a durable record of the intended business date before launching compute. If yesterday’s import is absent, the recovery path should know whether it was never requested, failed placement, ran and failed, or completed but failed publication. Scheduler delivery metrics alone cannot answer those questions. Conversely, a failed business job should not cause an unconstrained loop that launches another task every time a timer fires. Admission limits and a retry budget remain explicit application policy.

Choose orchestration for the state you need to own. Step Functions can remove substantial custom workflow code, and Scheduler can reliably express invocation times. Neither choice eliminates the need to define artifact ownership, duplicate side effects, absolute expiry and the final stop receipt. If the workflow already supplies durable transitions, do not build a second competing workflow engine in your database; keep only the business facts and reconciliation records necessary to close the external-service gap.

A recovery drill should stop the controller, not just the task

A useful failure exercise kills the controller at each boundary: before launch, after sending the request, after receiving an ARN and after issuing a stop. Restart it and verify that the same logical job remains explainable. Force an authorization denial on the stop path using a synthetic task, then restore the intended permission and verify recovery. Do not use production customer tasks for a drill or silently grant broad access to make it pass.

Measure the age of outcome-unknown launches and stopping jobs as well as their count. A queue depth of one can hide an orphan that has run for a day. Alert on expired leases, unreleased reservations and tasks with no matching ledger entry. Events can make the system responsive, but a periodic bounded reconciliation pass should recover missing or delayed events. Its own page size, request budget and ownership rules need limits so an incident does not generate an API storm.

The acceptance criterion is conservation: every admitted job has one accounted reservation, every known live task has a responsible logical job, and every released reservation has terminal compute evidence. External cleanup has its own outstanding count. When those numbers diverge, repair the transition with recorded evidence. Resetting a global concurrency counter may restore traffic briefly while allowing the underlying resource leak to continue unnoticed.

Independent engineering & research

Original analysis by heap.page, informed by the references below. Historical research and vendor accounts are identified explicitly; current AWS behavior is checked against the service documentation.

AWS documentation & further study

Reviewed November 16, 2026. Service availability and limits can change; check the linked documentation for your Region.

Optional implementation files

Original teaching fixtures, checked locally against the documentation. They have not been deployed as a production baseline. Use a disposable account and review the resources, permissions and cost before running them.

Prepaid · USD

Top up balance

Available balance: $0.00

Your balance works across Heap tools. A failed lookup or generation releases its reserved amount.