FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Docker gives your Python worker 10 seconds to stop. Use them well

A handler that only sets a flag, an exec-form ENTRYPOINT and jobs safe to run twice keep each deploy from leaving half-written records.

ShareLinkedInFacebookX

In brief

  • docker stop waits only 10 seconds for Linux containers; Kubernetes and Heroku wait 30. After that comes SIGKILL.
  • The handler should only set a flag, never raise an exception; threads should be non-daemon and stop on a threading.Event.
  • A shell-form ENTRYPOINT swallows SIGTERM, and jobs must tolerate being processed twice because queues deliver at least once.
Horizontal bar chart of default grace periods before SIGKILL: Docker 10 seconds (highlighted in orange), Kubernetes 30 seconds, Heroku 30 seconds. A dashed line marks a 25-second document summary job. The job overruns Docker's limit but stays within those of Kubernetes and Heroku.
For a 25-second job, the 10-second default of docker stop cuts it off midway, while the 30 seconds allowed by Kubernetes and Heroku is just enough. Source: Docker, Kubernetes and Heroku documentation cited in the article.

Run docker stop on a Linux container and, unless configured otherwise, Docker sends SIGTERM to the main process and waits just 10 seconds before firing SIGKILL. Kubernetes gives a Pod 30 seconds; Heroku also gives 30. Past that mark, the job in progress is cut off mid-flight, connections are left open and temporary files stay behind.

On a client deployment, workers that process documents, call models and write results to the client’s database are restarted on every rollout and every time the autoscaler shrinks the cluster.

If the worker cannot shut down gracefully, every deploy leaves a half-written record or a job that runs twice, and the person explaining it in the meeting is you.

This guide builds a small Python worker that listens for SIGTERM, packages it correctly in Docker, then adjusts it for Kubernetes and a queue. You need Python 3 and Docker on a laptop. Pulling jobs from a queue is simulated with time.sleep to keep things short; on a real project, swap in the client’s queue library.

Step 1: the handler may only set a flag

The Python documentation states two things that decide how the handler should be written. Handlers always run in the main thread of the main interpreter, even if the signal arrives in another thread, and only the main thread may register a handler.

The documentation also advises complex or high-reliability applications not to raise exceptions from a handler, because the exception can surface after any bytecode instruction, which means in the middle of a database write.

So the handler does exactly one thing: it sets a flag. Create worker.py:

import signal
import threading
import time

stop = threading.Event()

def on_term(signum, frame):
    # Only set the flag. No raising, no cleanup here.
    stop.set()

signal.signal(signal.SIGTERM, on_term)
signal.signal(signal.SIGINT, on_term)

def process(job_id):
    print(f"started job {job_id}", flush=True)
    time.sleep(3)  # simulate real work
    print(f"finished job {job_id}", flush=True)

job_id = 0
while not stop.is_set():
    job_id += 1
    process(job_id)

print("stopped gracefully, close connections here", flush=True)

The loop checks the flag between jobs, so the job in progress always completes. Heroku notes that a process may receive more than one SIGTERM; with this handler, a second signal simply calls stop.set() again and does no harm.

Step 2: why can a Dockerfile swallow SIGTERM?

The Dockerfile reference explains that the shell form of ENTRYPOINT runs the program under /bin/sh -c, and that shell does not pass signals on. Your application never sees the SIGTERM from docker stop, sits through the full 10 seconds and dies by SIGKILL.

FROM python:3.12-slim
COPY worker.py /app/worker.py
# Wrong: ENTRYPOINT python /app/worker.py
ENTRYPOINT ["python", "/app/worker.py"]

The exec form (a JSON array) is the form the documentation recommends. Check it straight away:

docker build -t worker-demo .
docker run --name w1 worker-demo
# in another terminal
docker stop w1

The correct result: the log prints “finished job” for the running job, then “stopped gracefully”, and docker stop returns after a few seconds rather than exactly 10. If the command hangs for the full 10 seconds and the last line never appears, the signal was blocked somewhere.

There is one more trap. Linux treats the process at PID 1 in a container specially: it ignores any signal left at its default action. A worker with its own handler, like the one above, is fine, but a script that does not handle SIGTERM will not exit by itself. For processes like that, the --init flag of docker run puts an init process at PID 1.

Step 3: how do you stop multiple threads?

Real workers usually run several threads in parallel. The threading documentation warns that daemon threads are stopped abruptly at shutdown and their resources may not be released. Its own advice: use non-daemon threads and a signaling mechanism such as threading.Event.

The code below replaces the while loop at the end of the Step 1 file (from job_id = 0 down); keep the imports, the stop flag, the handler and the process function.

def run_worker(n):
    while not stop.is_set():
        process(f"{n}-{time.time():.0f}")

threads = [threading.Thread(target=run_worker, args=(i,)) for i in range(4)]
for t in threads:
    t.start()

while not stop.is_set():
    stop.wait(1)  # keep the main thread free so the handler can run

for t in threads:
    t.join()
print("all 4 threads have stopped", flush=True)

The main thread does no heavy work and only waits, because that is the only place the handler runs. One detail is easy to miss: a long computation that runs entirely in C, such as a regex match over a large block of text, can run uninterrupted for an arbitrary length of time, and the Python handler is only called once it finishes.

If the main thread gets stuck in something like that, the flag is set late and most of the deadline is gone.

Step 4: what if a job takes longer than the deadline?

This is where the arithmetic matters. Say a job takes 3 seconds: whenever SIGTERM arrives, the worker still finishes before Docker’s 10-second mark. Now say a document-summarization job takes 25 seconds. On Kubernetes, with a 30-second grace period, that just fits; under a default docker stop, the job is killed by SIGKILL at the 10th second, halfway through.

Heroku offers two sensible options: stop accepting new jobs, then either finish the work in progress or return the job to the queue for another worker.

With Amazon SQS, “returning” is almost automatic: a message that is not deleted before its visibility timeout expires (30 seconds by default) reappears in the queue for another consumer to pick up.

The rule is to delete a message only after its result has been written.

The consequence is that a job can run twice. SQS delivers at least once, so jobs must tolerate repeat processing: write by the job’s key instead of inserting a new record, and check whether a result already exists before calling the model. Graceful shutdown reduces how often jobs repeat; idempotency is what makes the repeats harmless.

Step 5: Kubernetes keeps time differently than you think

When a Pod is terminated, the kubelet asks the container runtime to send TERM to process 1 in each container. terminationGracePeriodSeconds defaults to 30 seconds; if processes are still running when it expires, they get SIGKILL. For a 25-second job, extend it:

spec:
  terminationGracePeriodSeconds: 60

The trap is the preStop hook. According to a Google Cloud blog post on Pod termination, the grace-period clock runs in parallel with the preStop hook and SIGTERM; Kubernetes does not wait for preStop to finish before it starts counting. A preStop that sleeps for 20 seconds has already eaten 20 of the worker’s seconds. Add the two together when you budget time.

Step 6: asyncio and existing libraries

If the worker is written with asyncio, use loop.add_signal_handler(). According to the Python documentation, callbacks registered this way may interact with the event loop, unlike handlers set with signal.signal(). The SIGINT/SIGTERM example in the documentation works only on Unix.

import asyncio, signal

async def do_one_job():
    # stub: replace with your real job
    await asyncio.sleep(3)

async def main():
    loop = asyncio.get_running_loop()
    stop = asyncio.Event()
    loop.add_signal_handler(signal.SIGTERM, stop.set)
    while not stop.is_set():
        await do_one_job()

asyncio.run(main())

When the client already uses a queue library, read carefully how it interprets SIGTERM. Celery treats TERM as a warm shutdown: it finishes the running tasks before exiting.

Huey does the opposite, for historical reasons: SIGINT is its graceful stop, while SIGTERM interrupts running tasks immediately. Most process managers stop processes with SIGTERM, so a Huey consumer needs to run with -g TERM to reverse this.

Four mistakes that send SIGTERM astray

Across all six steps, most incidents come down to four places. A shell-form ENTRYPOINT leaves the signal stuck at /bin/sh -c, never reaching Python. Daemon threads are cut off at shutdown, so connections and temporary files are never cleaned up.

The other two are harder to spot. A long preStop hook quietly eats into the grace period, because Kubernetes counts in parallel rather than waiting for the hook to finish.

And a Huey consumer running with defaults treats SIGTERM as an order to stop immediately, with no graceful shutdown. When a worker breaks jobs after every deploy, check these in exactly this order before suspecting the business logic.

On a client’s system, ask about the deadline first

When starting work on a client’s system, the first question to ask is which platform the workers run on and how long the grace period is. Default Docker, Kubernetes and Heroku give different numbers, and that number sets the longest job you can afford to finish.

Next, open their Dockerfile and look for a shell-form ENTRYPOINT; it is often the answer to “every deploy breaks a few jobs.”

For your career, this belongs on a CV as one concrete sentence: you fixed the worker shutdown path so rollouts no longer broke jobs, together with how you measured it, such as the number of jobs that had to be rerun before and after the fix.

To tell that story in an interview, practice explaining the signal’s whole path: who sends it, who can swallow it, and how many seconds the worker has left.

A worker that shuts down gracefully does not make the demo look any better. It is what makes the tenth deploy on a client’s system as uneventful as the first.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
12 sources
Read next on the roadmap · Stage 1: FoundationsPython 3.14 lets pdb into a hung process, but not always at onceThe new pdb -p PID option attaches a debugger to a live CPython process with no restart, though one blocked on I/O will keep you waiting.