Test Graceful Application Shutdown: SIGTERM and Request Draining

Test Graceful Application Shutdown: SIGTERM and Request Draining

Test Graceful Application Shutdown: SIGTERM and Request Draining

During a service update, the process exits but the client receives an empty response. A background job is marked as claimed, but its output file is only partially written. Failures like these often have nothing to do with insufficient computing power: the shutdown sequence simply did not wait for work in progress to finish. Applications on a dedicated server need an explicit shutdown contract too: which process receives the signal, when new work stops being accepted, how long existing tasks may run, and what evidence remains if that deadline expires.

This article reproduces those boundaries with a standalone test service on Debian 12. It listens only on the loopback address and leaves existing applications unchanged. For an AmdCli server, check the console after payment for the login address and credentials. Connect to Linux over SSH; if multiple addresses are listed, use the first one.

1. Define What Counts as a Successful Shutdown

A “successful shutdown” involves at least three separate outcomes: no new tasks are accepted, previously accepted tasks finish, and the process exits within the allotted time. Checking only whether the process has disappeared misses the distinction between finishing its work and exiting on time.

In this experiment, each request takes eight seconds to process, and the shutdown timeout is twenty seconds. These are test parameters, not delivery timelines or service commitments. Production values must account for actual request durations, task commit points, and upstream timeouts rather than copying the example.

SIGTERM requests that a process exit; it does not prove that a transaction has completed. Applications cannot catch SIGKILL, so do not expect it to run cleanup, commit, or rollback code.

First, confirm that python3, curl, and systemd are available. Run the system configuration steps below from an account with administrative privileges. The test account name, file paths, and port are choices made for this article, not default server settings. Before starting, check that the port is unused:

command -v python3 curl systemctl
sudo ss -ltnp 'sport = :18080'

If something is already listening, choose a different test port and update the subsequent script and request commands accordingly. Do not stop an unfamiliar process.

2. Build a Service with Observable In-Flight Requests

Create a dedicated account without interactive login access. The administrator should own the script; the service account only needs to read and run it. First, check that neither the account name nor the test directory already exists, so you do not overwrite an existing configuration.

getent passwd stop-lab
sudo test -e /opt/stop-lab

Continue only if both are absent:

sudo useradd --system --no-create-home \
  --shell /usr/sbin/nologin stop-lab
sudo install -d -m 0755 /opt/stop-lab
sudo tee /opt/stop-lab/server.py >/dev/null <<'PY'
import signal
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        delay = 30 if self.path == "/slow" else 8
        print(f"request-start delay={delay}", flush=True)
        time.sleep(delay)
        body = b"completed\n"
        self.send_response(200)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
        self.wfile.flush()
        print("request-complete", flush=True)

class Server(ThreadingHTTPServer):
    daemon_threads = False
    block_on_close = True

server = Server(("127.0.0.1", 18080), Handler)
stopping = threading.Event()

def stop(signum, frame):
    if not stopping.is_set():
        stopping.set()
        print("signal-received", flush=True)
        threading.Thread(target=server.shutdown, daemon=True).start()

signal.signal(signal.SIGTERM, stop)
print("ready", flush=True)
try:
    server.serve_forever(poll_interval=0.1)
finally:
    server.server_close()
    print("drain-complete", flush=True)
PY
sudo chmod 0644 /opt/stop-lab/server.py

Two details matter here. Calling shutdown() from another thread avoids making the thread running the accept loop wait for itself to exit. Worker threads are explicitly non-daemon threads, so server_close() waits for accepted requests to finish instead of abandoning them when the main thread exits.

This service is only a test fixture for shutdown behavior, not a production HTTP server. Closing the listener is not an instantaneous way to remove an instance from traffic, either. In a real deployment, the ingress layer must first stop routing new requests to the instance, after which the application can drain its existing requests.

3. Let systemd Manage the Application Process Directly

Save the following unit without adding an automatic restart policy or enabling it at boot. This makes it easier to observe each test separately:

[Unit]
Description=Graceful shutdown acceptance lab

[Service]
Type=simple
User=stop-lab
Group=stop-lab
ExecStart=/usr/bin/python3 -u /opt/stop-lab/server.py
KillSignal=SIGTERM
KillMode=control-group
TimeoutStopSec=20s
SendSIGKILL=yes
StandardOutput=journal
StandardError=journal

The file path is /etc/systemd/system/stop-lab.service. After saving it, check the syntax and start the service:

sudo systemd-analyze verify /etc/systemd/system/stop-lab.service
sudo systemctl daemon-reload
sudo systemctl start stop-lab.service
sudo systemctl show stop-lab.service \
  -p MainPID -p KillMode -p TimeoutStopUSec
sudo journalctl -u stop-lab.service -n 20 --no-pager

The journal should contain ready, and MainPID should point to the Python process. The startup command here does not use a shell wrapper. If an existing service starts through a script, use exec at the end where appropriate to replace the shell, and check the actual process tree.

KillMode=control-group applies the stop signal to processes within the unit. It is not a universal template for every multiprocess application. If the main process coordinates child-process shutdown, choose the signal scope according to that application's process model. Do not hide leftover processes merely to eliminate a timeout.

4. Test Both Completion and Timeout Paths

Verify That an In-Flight Request Completes

Start a request in terminal A:

curl --fail --show-error --max-time 40 \
  http://127.0.0.1:18080/

In terminal B, watch the journal first. Confirm that request-start delay=8 appears for this request before stopping the service:

sudo journalctl -fu stop-lab.service

Once you have confirmed that the request is being processed, stop following the journal and run:

sudo systemctl stop stop-lab.service
sudo journalctl -u stop-lab.service -n 30 --no-pager

A passing result means the client prints completed, the application logs show signal receipt, request completion, and drain completion in that order, and no shutdown timeout occurs. The stop command needs to wait for the in-flight request; that wait is not, by itself, a hang.

Verify That a Shutdown Timeout Is Detectable

Restart the service and request /slow from terminal A. This path simulates a thirty-second task. In terminal B, stop the service after the corresponding request-start entry appears:

sudo systemctl start stop-lab.service
curl --fail --show-error --max-time 40 \
  http://127.0.0.1:18080/slow

The twenty-second stop deadline is too short for this task to finish. The expected result is that the client does not receive a complete response, and the journal reports a shutdown timeout and forced termination rather than drain-complete.

sudo systemctl show stop-lab.service \
  -p Result -p ExecMainCode -p ExecMainStatus
sudo journalctl -u stop-lab.service -n 40 --no-pager

Do not treat this deliberately unsuccessful outcome as an application defect. It demonstrates that the forced-termination path is observable. It also shows that extending the deadline only allows more time to wait; it does not automatically ensure application-level consistency.

5. Apply the Test Criteria to Your Production Application

When applying this approach to a real application, first identify commit points that must not be interrupted. Sending a complete HTTP response, acknowledging a queue message, committing a database transaction, and persisting a file to disk are different events. Log completion only after the relevant operation has actually succeeded.

For long-running tasks, also review the cancellation policy. Work that can be interrupted should release its resources; work that must finish should have a bounded waiting period; work that may be run again should use idempotency keys or deduplication records. Merely extending the shutdown timeout cannot prevent duplicate task claims or partially completed results becoming visible.

Retain at least the following evidence for acceptance testing:

  • The service's actual PID, startup command, and shutdown policy, confirming that the signal reached the application rather than stopping at a wrapper process.
  • Identifiers, start records, and final outcomes for tasks accepted before shutdown, so logs from different requests are not mistakenly combined.
  • A complete client response or a recoverable failure outcome, along with a check for retries by upstream components.
  • Results for both completion within the deadline and exceeding it, plus a check for leftover child processes after shutdown.

Do not deliberately push a long-running task past the shutdown deadline in production. Rehearse on an isolated instance first, then use a controlled rollout batch to verify the sequence of ingress removal, application draining, and process exit. Even after the frontend stops routing new requests to an instance, upstream connection pools may still reuse existing connections. Include that layer in the acceptance test as well.

After the experiment, stop the service, delete the unit and script created for it, and run daemon-reload. Remove the account only after confirming that it has no other use. The final deliverable is not a statement that “graceful shutdown is supported,” but a reproducible set of inputs, complete results, and failure boundaries.

Frequently asked questions

Does setting TimeoutStopSec make an application shut down gracefully?

No. It only sets the stop deadline. The application must handle SIGTERM, stop accepting new work and wait for active work to finish. Under the default stop policy, systemd forcibly terminates remaining processes when that deadline expires.

Does a successful systemctl stop prove that no requests were lost?

No. Verify that the client received a complete response, the application logged completion and the service journal contains no stop timeout or forced termination. Process exit alone does not prove business completion.

AMD EPYC 7543P Dedicated Server

From $463.8/month, with no setup fee or contract.

Configure an AmdCli dedicated server View AmdCli pricing

Compare server configurations and options

Choose memory, bandwidth, and IPv4 options to configure an AmdCli dedicated server for deployment needs.