Verify service readiness and dependency ordering with systemd
A reporting job connects to a local service as soon as the store's administration backend starts, but occasionally gets a connection refused error. Run it again, and it works. The problem may not be the network at all, but the startup contract: the process exists, yet configuration loading, resource initialization, and listener setup are still incomplete. Adding a fixed sleep to the downstream script only lets the race resurface when the load changes.
This article uses the Python standard library on Ubuntu Server 24.04 LTS to build a test that listens only on the loopback address. The goal is not to monitor ongoing health, but to demonstrate two things: the downstream service runs only after the upstream service explicitly reports readiness, and it cannot proceed if initialization times out. The experiment does not modify production application services or involve a public-facing firewall.
Distinguish the startup stages
With Type=simple, a service can be considered started as soon as its main process has been created. systemd does not wait for the application's internal initialization. Switching to Type=exec only confirms that the program was successfully executed—not that it is ready to handle application work.
Type=notify lets the application determine when startup is complete: systemd waits for a valid READY=1 notification before completing the start job. A downstream service's After= can therefore wait for this boundary.
Configure both Requires= and After=. The former starts the upstream service and, together with the ordering relationship used here, prevents the downstream service from starting if its dependency fails. The latter defines the execution order. Neither directive alone expresses the full intent.
The readiness notification must come from a process that knows the initialization state. Starting a separate script that waits a few seconds before sending the notification merely moves the fixed delay elsewhere; it does not establish a reliable contract.
All durations below are experimental parameters, not service delivery or performance commitments. The experiment uses local port 18080; this is not a default connection port for any product.
Write the notification program
First, confirm that python3 and systemctl are available, and use ss -ltn 'sport = :18080' to check that the port is unused. Run the file creation commands from a session with administrative privileges. If a file already exists, inspect its contents first to avoid overwriting an experiment with the same name.
sudo install -d -m 0755 /opt/readiness-lab
sudo tee /opt/readiness-lab/server.py >/dev/null <<'PY'
import os
import socket
import time
delay = float(os.environ.get("READY_DELAY", "3"))
print("initializing", flush=True)
time.sleep(delay)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 18080))
listener.listen(8)
address = os.environ["NOTIFY_SOCKET"]
if address.startswith("@"):
address = "\0" + address[1:]
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notifier:
notifier.connect(address)
notifier.sendall(b"READY=1\nSTATUS=Local listener ready")
print("ready sent", flush=True)
while True:
connection, peer = listener.accept()
with connection:
connection.sendall(b"ready\n")
PY
The program first simulates initialization, then binds the socket and starts listening, and only then sends the notification. Linux abstract Unix socket addresses are represented with a leading @ in the environment variable. Before calling the socket API, that character must be replaced with a leading null byte; otherwise, notification delivery will fail in some environments.
A real application should notify systemd only after validating the required configuration, preparing resources, and becoming capable of handling requests. If the listener is already open but initialization is still running in the background, the notification point in this example is not directly applicable.
Set up the dependency experiment
Create the upstream service. Use DynamicUser=yes to avoid leaving a permanent account behind after the experiment. Read-only access to the script directory is sufficient; the dynamic user does not need write permission.
sudo tee /etc/systemd/system/readiness-lab.service >/dev/null <<'UNIT'
[Unit]
Description=Local readiness experiment
[Service]
Type=notify
NotifyAccess=main
DynamicUser=yes
Environment=READY_DELAY=3
ExecStart=/usr/bin/python3 -u /opt/readiness-lab/server.py
TimeoutStartSec=15
Restart=no
UNIT
NotifyAccess=main explicitly restricts accepted notifications to the main process. In this example, the main process sends the notification directly, so no additional notification utility or broader notification permissions are needed.
Next, create the downstream one-shot probe. It connects and reads a specific response rather than treating a successful port connection as the entire acceptance test.
sudo tee /etc/systemd/system/readiness-probe.service >/dev/null <<'UNIT'
[Unit]
Description=Readiness dependency probe
Requires=readiness-lab.service
After=readiness-lab.service
[Service]
Type=oneshot
DynamicUser=yes
ExecStart=/usr/bin/python3 -c "import socket; s=socket.create_connection(('127.0.0.1',18080),timeout=2); s.settimeout(2); f=s.makefile('rb'); data=f.readline(32); f.close(); s.close(); assert data == b'ready\n', repr(data); print('probe passed',flush=True)"
UNIT
sudo systemctl daemon-reload
sudo systemd-analyze verify \
/etc/systemd/system/readiness-lab.service \
/etc/systemd/system/readiness-probe.service
sudo systemctl start readiness-probe.service
Fix any unit errors reported by verification before running the start command. After a successful run, the probe normally returns to inactive because RemainAfterExit=yes is not set. That does not mean it failed; assess the exit result together with the logs.
Trigger an initialization timeout
First, save evidence of the successful path. Read the logs for the same startup attempt. The expected sequence is initialization, notification sent, and probe passed. Application output in the logs helps with diagnosis; the actual ordering guarantee comes from the notification protocol and unit dependencies.
systemctl show readiness-lab.service \
-p ActiveState -p SubState -p Result -p StatusText
systemctl show readiness-probe.service -p Result -p ExecMainStatus
sudo journalctl -b \
-u readiness-lab.service \
-u readiness-probe.service \
-o short-monotonic --no-pager
Then stop both units and set the initialization delay to exceed the startup timeout. The upstream service must be stopped first: running start on an already running service does not test initialization again.
sudo systemctl stop readiness-probe.service readiness-lab.service
sudo install -d /etc/systemd/system/readiness-lab.service.d
sudo tee /etc/systemd/system/readiness-lab.service.d/test.conf >/dev/null <<'UNIT'
[Service]
Environment=READY_DELAY=20
UNIT
sudo systemctl daemon-reload
sudo systemctl start readiness-probe.service
systemctl show readiness-lab.service -p ActiveState -p Result
The last start command is expected to return a nonzero exit status. The upstream service should report Result=timeout, and the downstream start job must not run because its dependency failed. Inspect the logs for this attempt and confirm that no new probe passed entry appears. Do not mistake a successful entry from the previous run for evidence from this one, or require the downstream service to show a particular fixed Result value.
If the timeout test still passes, first check Environment and TimeoutStartUSec in the effective configuration, then verify that the original process was stopped. Do not simply increase the startup timeout to hide a discrepancy in the experiment.
Restore the configuration and hand over evidence
Remove the delay override created for this test, reload the configuration, and clear the failed state. Then start from the downstream service to confirm that the normal path works again.
sudo rm /etc/systemd/system/readiness-lab.service.d/test.conf
sudo systemctl daemon-reload
sudo systemctl reset-failed readiness-lab.service readiness-probe.service
sudo systemctl start readiness-probe.service
systemctl cat readiness-lab.service readiness-probe.service
Keep four items in the handover record: the effective unit contents, the successful startup logs, the timeout failure logs, and the probe result after restoration. If application initialization fails, the application should exit with a failure status rather than send a readiness notification and then attempt repairs.
Define the limits of readiness
Startup readiness is not a continuous health check. Database disconnections, worker thread exits, or application processing failures after notification require separate monitoring mechanisms. Do not treat STATUS= as a readiness signal either: it supplies status text and cannot replace READY=1.
The downstream service should still use connection timeouts and bounded retries. Startup ordering reduces initialization races but cannot eliminate connection interruptions during operation. Applications that support starting offline should not automatically be given a hard dependency.
When the experiment is complete, stop both units, remove the units, empty override directory, and script created for this test, then run daemon-reload. Do not run enable, so the experiment does not start at boot. The final acceptance criteria are a successful normal path, a blocked timeout path, and another successful run after restoration—not merely a line that says active.
Frequently asked questions
Does After= wait for application initialization?
Not by itself. After= orders start jobs, while the upstream service type determines when startup is complete. Type=notify waits for a valid READY=1 message. Add Requires= or another suitable dependency to start the upstream service as well.
Does READY=1 guarantee continued service health?
No. It only marks completion of the application's startup readiness conditions. It neither replaces ongoing health checks nor guarantees that subsequent business requests will succeed.
AMD EPYC 7543P Dedicated Server
From $461.7/month