Skip to content

Lesson 4 of 9 · 23m

Service Lifecycle and Supervision: Restart Policy Done Right

How systemd tracks main processes, what restart settings mean in practice, and how to build services that recover without flapping.

systemd is a process supervisor, but not a magical one. It can restart dead processes, enforce limits, and capture logs. It cannot decide whether a wedged process is healthy. Your unit needs an honest lifecycle model.

What systemd is tracking

systemd tracks the main PID inside the service cgroup. systemctl status metrics-api.service shows the cgroup path, memory, tasks, exit codes, restart count, and recent logs. Children do not escape supervision by forking; they remain in the cgroup.

Restart policies have precise meanings

[Unit]
StartLimitIntervalSec=120
StartLimitBurst=5

[Service]
Restart=on-failure
RestartSec=5s
  • no: never restart automatically.
  • always: restart after any exit, including clean exits.
  • on-failure: restart after nonzero exit, signal, timeout, or watchdog failure.
  • on-abnormal: signals/watchdog failures, but not ordinary nonzero exits.
  • on-abort: unexpected signals not sent by systemd.

For most daemons, on-failure is the right default. RestartSec gives downstream dependencies time to recover. Rate limits mean five crashes in two minutes leave the unit failed instead of flapping forever and filling disks.

Clean stop behavior matters

systemd sends SIGTERM, waits TimeoutStopSec, then escalates to SIGKILL if processes remain.

[Service]
TimeoutStopSec=30s
KillMode=mixed
KillSignal=SIGTERM

A good server stops accepting work, finishes in-flight requests, then exits. If the application cannot do that, no unit directive will invent graceful behavior. TimeoutStopSec=infinity may be right for some databases, but remember that you are also delaying reboots.

KillMode=control-group is the normal default. mixed sends TERM to the main process and KILL to leftovers. Use narrower modes only when the daemon intentionally manages its own children.

Health is separate from aliveness

A process can be alive and useless. systemd's watchdog requires application support:

[Service]
WatchdogSec=15s

The application must call sd_notify("WATCHDOG=1") within the interval. Do not enable it for software that does not implement watchdog pings. For HTTP services, external health checks usually answer the real user-facing question better.

Field notes

  • Inspect failure state with systemctl show unit -p Restart -p NRestarts -p ExecMainStatus.
  • systemctl reset-failed clears state; it does not fix the crash loop.
  • A nonzero exit during deploys is still nonzero; use SuccessExitStatus= only for documented application semantics.
  • Restart storms are capacity events. Rate limits exist so broken software fails closed.

Was this lesson helpful?

Sign in to rate