Keeping a Service Running: Supervisors, Restart Policies and systemd Unit Files
Keep an application alive after crashes: run a supervisor that restarts a failing program with backoff and a limit, read and lint a systemd unit file, and compare the lint with systemd's own analyser.
In this lesson you will
- Explain what a supervisor does
- Choose a restart policy with backoff
- Read a systemd unit file
- Lint a unit file and check it with systemd-analyze
About 28 minutes
The app that died at three in the morning
Programs crash: a memory leak, a full disk, a bad request, a database that was restarted. If the web application is started by hand, it stays dead until someone notices. A supervisor is a program whose job is to start another program, watch it and start it again when it dies. On modern Linux systems this is done by systemd, which also starts services at boot, in the right order, with the right user and with limits on what they may do. A service is described in a unit file, a short text file in INI style with sections: Unit for the description and the order of starting, Service for what to run and how to restart it, and Install for when to start it.
A restart policy needs thought. Restarting at once in a tight loop can hammer a failing database or fill the logs, so supervisors wait between attempts, often with exponential backoff, and give up after too many failures in a period, leaving the service marked as failed, so that the monitor sees it. In systemd, Restart=on-failure restarts after a crash or a non-zero exit, but not after a clean exit, RestartSec sets the wait, and StartLimitBurst and StartLimitIntervalSec set the give-up rule. A good unit file also limits damage: it runs as an ordinary user, not root, with options such as NoNewPrivileges and ProtectSystem, and uses absolute paths for every command, because services start without your usual search path.
| Setting | Meaning | Good value |
|---|---|---|
| ExecStart | The command, with an absolute path | /usr/bin/python3 /srv/app/app.py |
| Restart | When to restart | on-failure |
| RestartSec | Wait before restarting | 2 seconds, or more |
| User or DynamicUser | Who runs it | Not root |
| NoNewPrivileges | Block privilege escalation | yes |
import subprocess, sys, tempfile, os, json
state = os.path.join(tempfile.mkdtemp(), "count")
open("child.py", "w").write('import sys, os\np = sys.argv[1]\nn = int(open(p).read() or 0) if os.path.exists(p) else 0\nopen(p, "w").write(str(n + 1))\nif n < 3: print("crashing on purpose (start number %d)" % (n + 1)); sys.exit(1)\nprint("started and finished cleanly on start number %d" % (n + 1))')
def supervise(max_restarts, base=0.5, cap=8.0):
delays, attempts, codes = [], 0, []
while True:
r = subprocess.run([sys.executable, "child.py", state], capture_output=True, text=True); attempts += 1; codes.append(r.returncode)
if r.returncode == 0: return "ok", attempts, codes, delays, r.stdout.strip()
if attempts > max_restarts: return "gave up", attempts, codes, delays, r.stdout.strip()
delays.append(min(cap, base * 2 ** (attempts - 1))) # exponential backoff (recorded, not slept, to keep the lesson fast)
res = supervise(max_restarts=5)
print("status:", res[0], "| starts:", res[1], "| exit codes:", res[2], "| waits before each restart:", res[3])
print("last output:", res[4])
open(state, "w").write("0")
res2 = supervise(max_restarts=2)
print("with a limit of 2 restarts: status:", res2[0], "| starts:", res2[1], "| exit codes:", res2[2])
print("DATA " + json.dumps({"a": res, "b": res2}))
status: ok | starts: 4 | exit codes: [1, 1, 1, 0] | waits before each restart: [0.5, 1.0, 2.0]
last output: started and finished cleanly on start number 4
with a limit of 2 restarts: status: gave up | starts: 3 | exit codes: [1, 1, 1]
[Unit]
Description=Pine and Honey web app
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
DynamicUser=yes
WorkingDirectory=/srv/app
ExecStart=/usr/bin/python3 -m http.server 8080 --bind 127.0.0.1
Restart=on-failure
RestartSec=2
NoNewPrivileges=yes
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
import configparser, io, json, sys
def lint(text):
cp = configparser.ConfigParser(strict=False, interpolation=None); cp.optionxform = str; cp.read_string(text)
out = []
svc = cp["Service"] if cp.has_section("Service") else {}
if not svc: return ["no [Service] section"]
exe = svc.get("ExecStart", "")
if not exe: out.append("no ExecStart")
elif not exe.split()[0].startswith("/"): out.append("ExecStart must start with an absolute path")
if svc.get("Restart") not in ("on-failure", "always", "on-abnormal", "no", None): out.append("unknown Restart value: " + svc.get("Restart"))
if "Restart" not in svc: out.append("no Restart policy: a crash leaves the service dead")
if svc.get("User") == "root" or ("User" not in svc and svc.get("DynamicUser") != "yes"): out.append("runs as root: set User= or DynamicUser=yes")
if svc.get("NoNewPrivileges") != "yes": out.append("NoNewPrivileges=yes is recommended")
return out
good, bad = open(sys.argv[1]).read(), open(sys.argv[2]).read()
r = {"good": lint(good), "bad": lint(bad)}
print("good unit:", r["good"] or "no findings"); print("bad unit :"); [print(" -", x) for x in r["bad"]]
print("DATA " + json.dumps(r))
good unit: no findings
bad unit :
- ExecStart must start with an absolute path
- unknown Restart value: sometimes
- runs as root: set User= or DynamicUser=yes
- NoNewPrivileges=yes is recommended
c.service:4: Failed to parse service restart specifier, ignoring: sometimes
c.service:5: Unknown key name 'Bogus' in section 'Service', ignoring.
The supervisor started a child program that crashes on its first three starts and works on the fourth. It restarted the child after each failure, waiting 0.5, 1 and 2 seconds, the exponential backoff, doubling each time up to a cap of 8 (the lesson records the waits and does not sleep). The exit codes, [1, 1, 1, 0], show three failures and then success on the 4th start, and the child’s last output confirms it. With a limit of only two restarts, the same child was started 3 times and the supervisor gave up, leaving the status “gave up”, which is what systemd calls a failed state, and what a monitor should alert on. The policy is a choice: a service that fails three times in a row after a deployment is probably broken by the deployment, and restarting it for ever hides that.
The unit file shown above runs the app as a dynamic, unprivileged user, with an absolute path in ExecStart, binds the server to localhost behind the proxy of lesson 5, restarts on failure after 2 seconds, and uses two hardening options. A small linter in Python read it as an INI file and found no problems. The second file is a typical bad one, and the linter found 4: ExecStart must start with an absolute path; unknown Restart value: sometimes; runs as root: set User= or DynamicUser=yes; NoNewPrivileges=yes is recommended. The relative path would fail because services do not have your search path, the unknown restart value would be ignored, so a crash would not be restarted as intended, and the missing options leave the service running as root with full rights and without sandboxing.
Independent check: systemd’s own analyser, run on the same two files, found nothing to complain about in the good unit, and on the bad unit it reported the problems of syntax that it knows about: the output block shows that it refuses the restart value “sometimes” and the unknown key “Bogus”. It did not flag the relative path or the root user, which are policy and not syntax, and those are exactly the rules that the linter of this lesson adds. The two tools together cover both layers: the tool that knows the format, and the tool that knows your rules.
Check by hand: the waits are 0.5 x 2 to the power of the failure number minus one: 0.5, 1 and 2 seconds, and the cap of 8 would be reached at the fifth wait. Three failures plus one success is four starts. With a limit of 2 restarts, the child is started once and restarted twice, three starts in all, and all three fail.
A bug or a break-in in a root service owns the machine. Use an unprivileged user or DynamicUser, and add sandbox options such as ProtectSystem and NoNewPrivileges.
A service that restarts once a week may be fine, and one that hits its restart limit is down. Monitor the state and the number of restarts.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. Other supervisors, such as Docker restart policies, supervisord and the init systems of other operating systems, work on the same principles. Check the documentation of the one you use.
Practice
Add StartLimitBurst and StartLimitIntervalSec to the unit. Make the supervisor reset its failure count after the child has run for a minute. Write a linter rule that requires a WorkingDirectory.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a supervisor do?
- Starts a program, watches it and restarts it when it fails
- Writes the program
- Encrypts the program
- Compresses logs
systemd does this on Linux.
Why use backoff when restarting?
- To make restarts faster
- To save disk
- To change the user
- To avoid hammering a failing dependency
0.5, 1, 2 seconds and so on.
What does Restart=on-failure do?
- Never restarts
- Restarts after a clean exit only
- Restarts every minute
- Restarts after a crash or a failing exit code
Not after a clean exit.
Why must ExecStart use an absolute path?
- Relative paths are faster
- It is a law
- Services do not have your usual search path
- Python requires it
/usr/bin/python3.
Why run systemd-analyze verify as well as your own linter?
- It is faster
- It replaces the service
- It knows the format; your linter knows your rules
- It restarts the service
Two layers of checking.
Summary
- A supervisor restarts failed programs; systemd is the usual one on Linux.
- Use backoff and a restart limit, and alert when it gives up.
- Unit files: Unit, Service and Install sections.
- Lint your rules and verify the format with systemd-analyze.
Questions
What is the difference between systemd and Docker restart policies?
Both restart failed programs. systemd manages services on the machine, and Docker restart policies manage containers. The ideas of backoff, limits and alerts are the same.
How do I see why a service failed?
With journalctl -u servicename and systemctl status servicename on a systemd machine, which show the output and the exit code.
Should the service start at boot?
Usually yes, with systemctl enable. A server that reboots after maintenance should bring its services back by itself.
