Blog

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.

10 min read

  • 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:

  1. 0 s: ECS replaces the task. ECS sends SIGTERM to the old tasks, busy or idle.
  2. 30 s: the grace period ends. The default stopTimeout is 30 seconds. After it, ECS sends SIGKILL.
  3. 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 kitchenIn 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#

TermMeaning
SQS messageOne job. It stays in the queue until a worker deletes it.
Visibility timeoutThe time that a received message stays hidden from other workers.
DLQ (dead-letter queue)A queue for messages that fail too many times.
ECS taskOne running copy of the worker container.
Scale-in protectionA flag that tells ECS: do not stop this task.
SIGTERM / SIGKILLThe "please stop" and "stop now" signals.
IdempotentTwo runs give the same result as one run.
CheckpointSaved progress. The job continues from it and does not restart.

The design: four parts#

PartWhat it does
1. DecoupleJobs wait in Amazon SQS, not in worker memory.
2. ProtectA busy worker turns on ECS task scale-in protection.
3. Shut down gracefullyOn SIGTERM, the worker stops polling and saves its state.
4. Resume safelyIdempotent 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.

Busy, protected: finishing its jobWorking on the jobStopped in the middle of the jobExited 0: finished cleanly
Case, and when the picture is takenOld taskNew task
No protectionDeploy at 10:45, after 18,750 emails. Picture: after the job ends.18,750 customers get two emails. The job ends at 12:46.
Stopped at customer 18,750
Starts again at customer 1Finished 12:46, exited 0
With the designDeploy at 10:45. Picture: after the job ends.The deploy waits. No duplicate emails. The job ends at 12:00.
Invoice job, protectedFinished 12:00, exited 0
Starts after 12:00, takes new jobs
Spot stop at 10:45Spot sends SIGTERM. Protection cannot block it. Picture: after the job ends.No duplicate emails. The job ends at 12:02, 2 minutes late.
Checkpoint at 18,750, exited 0
Resumes at customer 18,751, 10:47Finished 12:02, exited 0
The old and the new task in each case. ECS replaces the old task during the deploy.

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 ChangeMessageVisibility every 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 maxReceiveCount receives 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#

  1. At 0 min, Worker A receives the message. SQS hides it for 10 minutes.
  2. 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.
  3. At 17 min, Worker A crashes. No more heartbeats occur.
  4. At 25 min, the message becomes visible again. Worker B receives it and resumes from the checkpoint.
Working on the jobHidden from other workersPolling: no messageCrashed
Time, and what occursWorker AWorker BSQS message
0 min · receiveWorker A receives the message.Only Worker A can work on the job.
Working on the job
Polling
Hidden until 10 min
5, 10, 15 min · heartbeatEach heartbeat sets the timeout to 10 minutes from that time.The message stays hidden while A works.
Working, heartbeat sent
Polling
Hidden until 25 min
17 min · crashWorker A stops. No more heartbeats occur.The job stops after its last checkpoint.
Crashed at 17 min
Polling
Hidden until 25 min
25 min · retryThe timeout ends. Worker B receives the message.Worker B resumes from the checkpoint.
No worker
Resumes from the checkpoint
Hidden from others again
One message and two workers. The visibility timeout is 10 minutes. The heartbeat runs every 5 minutes.

Part 2: Protect – tell the orchestrator that a worker is busy#

ComputeHow the worker protects itselfWhat to know
ECS service (Fargate or EC2)PUT $ECS_AGENT_URI/task-protection/v1/state with ProtectionEnabled = trueDeploys and scale-in skip protected tasks. Expiry: 2 h default, 48 h maximum. The worker can renew it.
EC2 Auto ScalingSetInstanceProtection at job start. Remove it at job end.For instance refresh, set ScaleInProtectedInstances to Wait.
AWS BatchNo 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.

  1. SIGTERM arrives. ECS or a Spot interruption starts the stop.
  2. Stop polling. The worker takes no new messages.
  3. Finish or save. If time allows, the worker finishes the job. If not, it writes a checkpoint.
  4. 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#

TimeEvent
0 sSIGTERM arrives. The handler sets stopping = True.
1 sThe loop takes no new messages.
20 sThe job ends its current batch. It saves a checkpoint: customer 18,750.
21 sThe worker sets the message visibility to 0. Another worker can receive it now.
22 sThe worker exits with code 0.
120 sSIGKILL 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:

AttributeValue
job_idinv-2026-10
statusIN_PROGRESS
last_customer18750
updated_at10:45:20

Worker B does these steps:

  1. It reads the row: last_customer = 18750.
  2. It continues at customer 18,751.
  3. 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.
  4. At the end, it sets status = DONE. A late copy of the message sees DONE and 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#

  1. Deploy starts. ECS starts tasks from the new task definition.
  2. Old tasks selected. ECS selects old tasks to stop.
  3. Busy tasks wait. ECS skips protected tasks. Idle tasks stop now.
  4. Job ends. The worker deletes the message and turns protection off.
  5. Clean stop. ECS sends SIGTERM. The idle worker exits immediately.
Busy, protected: finishing its jobNew worker: takes all new jobsIdle: no job, no protectionExited 0: stopped cleanly
Step, and when the picture is takenOld task definitionNew task definition
Step 1 · deploy startsWorker A runs the invoice job. Picture: right after the start.Old and new tasks run side by side.
Worker A, invoice job, protectedWorker C
New worker, starting
Steps 2 and 3 · busy tasks waitECS selects A and C to stop. Picture: after the selection.ECS skips A. C stops now.
Worker A, protectedWorker C, exited 0
New worker
Step 4 · job endsA deletes the message and turns protection off.ECS can stop A now.
Worker A
New worker
Step 5 · clean stopECS sends SIGTERM to A. Picture: after the deploy.The deploy is complete. No job is lost.
Worker A, exited 0
New worker
A deploy with one busy worker (A) and one idle worker (C).

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 jobRun workers onWhy
Under 15 minLambda with an SQS triggerLambda stops at 15 min. A deploy does not stop invocations that already run.
15 min to 48 hECS service with task scale-in protectionProtection holds the task through deploys. Renew it for jobs near 48 h.
Many hours, batch workAWS Batch, or Step Functions with ECS RunTaskEach 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 maxReceiveCount of 3 to 5.
  • Task scale-in protection on during each job.
  • SIGTERM handler: stop polling, save, release.
  • stopTimeout set to 120 s on Fargate.
  • Idempotency key and checkpoints in DynamoDB.
  • Alarms on DLQ depth and ApproximateAgeOfOldestMessage.

Questions for your setup#

  1. How long does your longest job run: minutes, hours or days?
  2. Which compute runs your workers today: ECS on Fargate, ECS on EC2, EC2 or Lambda?
  3. How do you start deploys: GitHub Actions, CodePipeline or manually?

Use the first answer with the compute table above to select a starting point.