Long-running jobs that survive deploys
A deploy on Amazon ECS can stop a worker in the middle of a two-hour job. This design keeps the job alive with Amazon SQS, ECS task scale-in protection, graceful shutdown and idempotent jobs.
- DevOps
- AWS
- ECS
- SQS
A deploy replaces the tasks that run your workers. ECS does not check if a worker is busy. If a job runs for two hours, a deploy can stop it after 45 minutes.
This post shows a design that keeps long-running jobs alive across deploys on Amazon ECS. The design has four parts: Amazon SQS, ECS task scale-in protection, graceful shutdown and idempotent jobs.
The problem: a deploy stops workers in the middle of a job#
When you roll out a new task definition, this sequence occurs:
- 0 s: ECS replaces the task. ECS sends
SIGTERMto the old tasks, busy or idle. - 30 s: the grace period ends. The default
stopTimeoutis 30 seconds. After it, ECS sendsSIGKILL. - Result: the job stops halfway. The output can be partial. The message returns to the queue, and the job starts again from zero.
A simple picture: a restaurant kitchen#
| In the kitchen | In AWS |
|---|---|
| Order tickets wait on a rail. | Jobs wait in the SQS queue. |
| A chef takes a ticket. No other chef can take it. | The visibility timeout hides the message. |
| A "busy" sign: the manager waits for the chef. | Task scale-in protection. |
| Closing time: finish the dish, take no new orders. | The SIGTERM handler. |
| The chef writes "step 3 done" on the ticket. | A checkpoint in DynamoDB. |
| The ticket number stops the same dish twice. | The idempotency key. |
Terms#
| Term | Meaning |
|---|---|
| SQS message | One job. It stays in the queue until a worker deletes it. |
| Visibility timeout | The time that a received message stays hidden from other workers. |
| DLQ (dead-letter queue) | A queue for messages that fail too many times. |
| ECS task | One running copy of the worker container. |
| Scale-in protection | A flag that tells ECS: do not stop this task. |
SIGTERM / SIGKILL | The "please stop" and "stop now" signals. |
| Idempotent | Two runs give the same result as one run. |
| Checkpoint | Saved progress. The job continues from it and does not restart. |
The design: four parts#
| Part | What it does |
|---|---|
| 1. Decouple | Jobs wait in Amazon SQS, not in worker memory. |
| 2. Protect | A busy worker turns on ECS task scale-in protection. |
| 3. Shut down gracefully | On SIGTERM, the worker stops polling and saves its state. |
| 4. Resume safely | Idempotent jobs and checkpoints make a retry safe. |
Parts 2 and 3 handle planned stops. Parts 1 and 4 handle every failure, planned or not.
How the parts connect#
Producer (API, cron or event)
│ send
▼
SQS job queue (visibility timeout + heartbeat)
│ │ after 3 failed tries
│ poll ▼
│ Dead-letter queue (alarm if depth > 0)
▼
ECS workers
A: busy, protected
B: busy, protected
C: idle, can stop
│ save progress
▼
DynamoDB (checkpoints and job IDs)
The producer is any code that creates a job. Workers A and B are protected while they run a job. ECS can stop worker C at any time.
Running example: the monthly invoice job#
The job emails invoices to 50,000 customers. It runs for 2 hours, from 10:00. A deploy starts at 10:45. At 10:45, the job has sent 18,750 emails.
Part 1: Decouple – put every job in an SQS queue#
Jobs live in the queue, not in worker memory. If a worker stops, the job waits for the next worker.
- Visibility timeout. Set it longer than a normal job. While a worker holds the message, other workers do not see it.
- Heartbeat. For long jobs, call
ChangeMessageVisibilityevery few minutes. Each call sets a new timeout that starts at the time of the call. The total limit is 12 hours from the receive. - Dead-letter queue. After
maxReceiveCountreceives without a delete (for example, 3), SQS moves the message to the DLQ. Set an alarm on the DLQ depth.
Each release at shutdown also counts as a receive. Set maxReceiveCount high enough for the stops that you expect during one job.
Example: one message, two workers#
- At 0 min, Worker A receives the message. SQS hides it for 10 minutes.
- At 5, 10 and 15 min, the heartbeat of Worker A sets the timeout to 10 minutes from that time. The message stays hidden until 25 min.
- At 17 min, Worker A crashes. No more heartbeats occur.
- At 25 min, the message becomes visible again. Worker B receives it and resumes from the checkpoint.
Part 2: Protect – tell the orchestrator that a worker is busy#
| Compute | How the worker protects itself | What to know |
|---|---|---|
| ECS service (Fargate or EC2) | PUT $ECS_AGENT_URI/task-protection/v1/state with ProtectionEnabled = true | Deploys and scale-in skip protected tasks. Expiry: 2 h default, 48 h maximum. The worker can renew it. |
| EC2 Auto Scaling | SetInstanceProtection at job start. Remove it at job end. | For instance refresh, set ScaleInProtectedInstances to Wait. |
| AWS Batch | No code. Each job runs in its own task. | For compute environment updates, set terminateJobsOnUpdate to false. |
Task scale-in protection works only for tasks that an ECS service starts. A standalone task from RunTask cannot use it.
Example: a task turns protection on and off#
Idle ──protect ON──▶ Busy ──protect OFF──▶ Finished
▲ │
└──────────── poll the next message ─────────┘
- Idle. No protection. ECS can stop the task at any time.
- Busy. Protected. Deploys and scale-in skip the task.
- Finished. The worker deletes the message and turns protection off.
Task B receives the invoice job at 10:00. It turns on protection with a 180-minute expiry. The 10:45 deploy skips Task B. At 12:00, the job ends, protection goes off, and ECS replaces the task.
Part 3: Shut down gracefully – handle SIGTERM in the worker#
Protection does not stop every termination. Spot interruptions, manual task stops and expired protection still send SIGTERM.
SIGTERMarrives. ECS or a Spot interruption starts the stop.- Stop polling. The worker takes no new messages.
- Finish or save. If time allows, the worker finishes the job. If not, it writes a checkpoint.
- Release and exit. The worker sets the message visibility to 0 and exits with code 0.
Time budget: stopTimeout. The default is 30 s. The Fargate maximum is 120 s. After it, ECS sends SIGKILL.
Use the exec form of CMD in the Dockerfile: CMD ["python", "worker.py"]. In the shell form, /bin/sh is process 1 and does not pass SIGTERM to the worker.
Example: the invoice worker gets SIGTERM#
| Time | Event |
|---|---|
| 0 s | SIGTERM arrives. The handler sets stopping = True. |
| 1 s | The loop takes no new messages. |
| 20 s | The job ends its current batch. It saves a checkpoint: customer 18,750. |
| 21 s | The worker sets the message visibility to 0. Another worker can receive it now. |
| 22 s | The worker exits with code 0. |
| 120 s | SIGKILL would arrive here. It is not necessary. |
With stopTimeout set to 120 s, the shutdown uses 22 s. 98 s stay as spare time.
Part 4: Resume safely – make every job safe to run twice#
SQS standard queues deliver each message at least once. Any job can run twice. The result must stay the same.
- Idempotency key. Write the job ID to DynamoDB with a conditional put. If the ID is already done, skip the job.
- Checkpoints. Save progress every N items. A new worker reads the last checkpoint and continues from there.
- Small chunks. Split a 6-hour job into 360 one-minute messages. A stop then loses 1 minute, not 6 hours.
Example: the job runs twice, and nobody gets two emails#
The checkpoint row in DynamoDB:
| Attribute | Value |
|---|---|
job_id | inv-2026-10 |
status | IN_PROGRESS |
last_customer | 18750 |
updated_at | 10:45:20 |
Worker B does these steps:
- It reads the row:
last_customer = 18750. - It continues at customer 18,751.
- Before each email, it writes the key
inv-2026-10#cust-N. If the key exists, the write fails, and Worker B skips that email. - At the end, it sets
status = DONE. A late copy of the message seesDONEand stops.
The conditional write in step 3:
from botocore.exceptions import ClientError
def claim(table, key):
try:
table.put_item(
Item={"pk": key},
ConditionExpression="attribute_not_exists(pk)",
)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False # another run already sent this email
raise
This order accepts a missed email to prevent a duplicate email. If the worker stops between the write and the send, that one customer gets no email. To find these cases, record the send result on the same item.
In practice: what happens during a deploy#
- Deploy starts. ECS starts tasks from the new task definition.
- Old tasks selected. ECS selects old tasks to stop.
- Busy tasks wait. ECS skips protected tasks. Idle tasks stop now.
- Job ends. The worker deletes the message and turns protection off.
- Clean stop. ECS sends
SIGTERM. The idle worker exits immediately.
Without protection, step 3 sends SIGTERM to busy tasks. The job stops after stopTimeout.
Trade-off: a deploy ends only when the longest active job ends. Plan deploy windows for it. If CloudFormation runs your deploys, a stack update fails after 3 hours. Keep the protection expiry at 3 hours or less, or deploy the service outside CloudFormation.
The worker loop#
import signal
stopping = False
def on_sigterm(signum, frame):
global stopping
stopping = True # part 3: take no new messages
signal.signal(signal.SIGTERM, on_sigterm)
while not stopping:
resp = sqs.receive_message(
QueueUrl=Q, WaitTimeSeconds=20, MaxNumberOfMessages=1
)
for msg in resp.get("Messages", []):
protect(True, minutes=180) # part 2: deploys skip this task
hb = heartbeat(msg, every_s=60) # part 1: keep message hidden
done = False
try:
job = load_checkpoint(msg) # part 4: resume, not restart
done = run(job, stop=lambda: stopping) # saves on stop
finally:
hb.stop() # stop first: a late beat re-hides a released message
if done:
sqs.delete_message(
QueueUrl=Q, ReceiptHandle=msg["ReceiptHandle"]
)
else:
release(msg) # visibility 0: the next worker resumes
protect(False) # ECS can stop the task now
protect() calls the ECS agent endpoint. heartbeat() and release() call ChangeMessageVisibility:
import os
import threading
import requests
def protect(enabled, minutes=None):
body = {"ProtectionEnabled": enabled}
if enabled and minutes:
body["ExpiresInMinutes"] = minutes
url = os.environ["ECS_AGENT_URI"] + "/task-protection/v1/state"
requests.put(url, json=body, timeout=5).raise_for_status()
def release(msg):
sqs.change_message_visibility(
QueueUrl=Q,
ReceiptHandle=msg["ReceiptHandle"],
VisibilityTimeout=0,
)
class heartbeat:
def __init__(self, msg, every_s=60, timeout_s=600):
self._done = threading.Event()
self._thread = threading.Thread(
target=self._beat,
args=(msg, every_s, timeout_s),
daemon=True,
)
self._thread.start()
def _beat(self, msg, every_s, timeout_s):
while not self._done.wait(every_s):
sqs.change_message_visibility(
QueueUrl=Q,
ReceiptHandle=msg["ReceiptHandle"],
VisibilityTimeout=timeout_s,
)
def stop(self):
self._done.set()
self._thread.join()
Pick the compute by job length#
| Longest job | Run workers on | Why |
|---|---|---|
| Under 15 min | Lambda with an SQS trigger | Lambda stops at 15 min. A deploy does not stop invocations that already run. |
| 15 min to 48 h | ECS service with task scale-in protection | Protection holds the task through deploys. Renew it for jobs near 48 h. |
| Many hours, batch work | AWS Batch, or Step Functions with ECS RunTask | Each job runs in its own task, outside any service. A service deploy does not touch it. |
Checklist before a worker goes to production#
- Visibility timeout longer than a normal job.
- Heartbeat for jobs longer than the visibility timeout.
- DLQ with
maxReceiveCountof 3 to 5. - Task scale-in protection on during each job.
SIGTERMhandler: stop polling, save, release.stopTimeoutset to 120 s on Fargate.- Idempotency key and checkpoints in DynamoDB.
- Alarms on DLQ depth and
ApproximateAgeOfOldestMessage.
Questions for your setup#
- How long does your longest job run: minutes, hours or days?
- Which compute runs your workers today: ECS on Fargate, ECS on EC2, EC2 or Lambda?
- How do you start deploys: GitHub Actions, CodePipeline or manually?
Use the first answer with the compute table above to select a starting point.