August 25, 2026

Writing Production-Grade Systemd Services: Readiness, Restart, and Shutdown

A process that exists is not necessarily a service that is ready. A process that exits is not necessarily a failure that should be restarted. And a service that receives SIGTERM is not necessarily shut down safely.

Those three distinctions are where many otherwise reasonable .service files become fragile in production.

A minimal unit can launch an executable:

[Service]
ExecStart=/usr/bin/device-daemon

That may be enough for a quick experiment. It is rarely enough for a daemon that must boot reliably on a device, expose an API to other components, recover from crashes and shut down without leaving corrupted state behind.

In the first article, Systemd Is More Than systemctl: A Practical Map of the Linux System Manager, we built the broad map: units, lifecycle, logging, identities, filesystem state, cgroups and activation. In the second article, How Systemd Thinks: Units, Dependencies, Ordering, and Boot Failures, we moved into the dependency graph and separated requirements from ordering.

This third article moves one level deeper. Once systemd has decided that a service should start and when its start job may run, the next question is what contract the service itself exposes to the manager and to the rest of the product.

Series context

This article focuses on one long-running service: when it becomes usable, which failures should trigger recovery, how repeated failure is contained and what graceful shutdown actually means. The next article will move from lifecycle into observability with systemd-journald.

A production service needs an explicit lifecycle contract:

  • Readiness: when may other components safely depend on this service?
  • Restart policy: which failures should trigger recovery, and which failures should remain visible instead of creating a loop?
  • Shutdown: what must happen after a stop request but before systemd eventually forces termination?
  • Diagnostics: how do we make the failure reason visible to the engineer debugging the target at 2 a.m.?

lifecyclecontract

The production question is not “did the process start?”


With the default Type=simple, systemd considers the service started extremely early: after the main service process has been forked. It does not wait for the new process to complete its own initialization, and it does not even use a successful execve() as the startup boundary.

The daemon may still be parsing configuration, opening a device, connecting to a message bus, restoring state, creating sockets or starting worker threads when ordered follow-up units are allowed to proceed.

That creates a common boot failure:

  1. client.service is ordered after device-daemon.service.
  2. systemd starts the process for device-daemon.service.
  3. The service reaches the startup boundary defined by its Type=.
  4. systemd is allowed to continue with client.service.
  5. The client immediately calls the daemon’s socket or D-Bus API.
  6. The daemon is still initializing, so the call fails or the client enters its own retry loop.

The units were ordered correctly. The real-world dependency was still not ready.

Ordering is not readiness

After=device-daemon.service only defines ordering when both units participate in the transaction. It does not define what “ready to serve requests” means for your application. The service type and, where needed, an explicit readiness protocol define that boundary.

Choose the service type based on the readiness contract


The Type= setting is not cosmetic. It tells systemd which event marks successful startup and therefore when ordered follow-up units may proceed.

Service typeWhat systemd treats as startup completionGood useImportant limitation
simpleThe main process has been forkedForeground processes where the earliest possible startup boundary is acceptableDoes not wait for successful execve() or application initialization
execThe service executable has been successfully invokedModern foreground daemons that do not expose a stronger readiness protocolStill does not mean sockets, hardware or application APIs are ready
notifyThe service sends READY=1Daemons that must declare a meaningful ready stateThe daemon must implement the notification protocol correctly
dbusThe service acquires the configured BusName=D-Bus services where owning the well-known name is the readiness boundaryOwning the name may still be weaker than full product readiness
oneshotThe start command exits successfullyFinite setup, migration or configuration workNot a long-running daemon model
forkingThe original process forks and the parent exitsLegacy self-daemonizing programs you cannot changeAvoid for new software when possible; main-PID tracking and readiness are weaker

For a new daemon you control, there are usually two practical starting points:

  • Use Type=exec when a successful process setup and execve() is enough, and other units do not need a stronger readiness promise.
  • Use Type=notify when dependents must wait until the daemon has completed meaningful initialization and can accept its intended work.

Do not choose Type=notify only because it sounds more advanced. Choose it when your service can make a truthful and useful statement about readiness.

startedisnowalwaysready

Readiness is an application decision


There is no universal definition of ready. For one daemon, it might mean:

  • configuration has been parsed and validated;
  • the persistent state database has been opened and migrated;
  • the local Unix socket is listening;
  • the D-Bus API has been exported and can answer requests;
  • a required hardware interface has been opened and placed in a known state;
  • the service can accept local requests, even if a remote peer may reconnect later.

Notice the last point. A daemon that manages a remote cloud connection may still be ready before the cloud is reachable. Its lifecycle contract may be “I can accept commands and manage reconnection,” not “the internet and backend are currently healthy.”

That distinction prevents a large class of bad boot design. Do not delay system startup forever because an optional remote server is unavailable. Let the daemon become ready when its own local control plane is ready, then expose remote connectivity as a separate runtime state.

A useful readiness test

Ask: “What could another local component safely do immediately after I declare readiness?” If the honest answer is “nothing yet,” the signal is too early.

Use Type=notify when readiness needs to be explicit


Type=notify lets the daemon tell systemd when startup has finished. The application sends a message through systemd’s notification protocol:

#include <systemd/sd-daemon.h>

// Call this only after the daemon can accept the work
// promised by its readiness contract.
sd_notify(0, "READY=1\nSTATUS=Ready to process requests");

Until that notification arrives, the service remains in its activating state. Ordered follow-up units wait. If startup never reaches that point before TimeoutStartSec=, systemd treats the startup attempt as timed out and applies the configured failure and restart policy.

A production-oriented unit might look like this:

[Unit]
Description=Device control daemon
Documentation=man:systemd.service(5)
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Type=notify
NotifyAccess=main

User=device-daemon
Group=device-daemon

RuntimeDirectory=device-daemon
RuntimeDirectoryMode=0750
StateDirectory=device-daemon
StateDirectoryMode=0750

ExecStart=/usr/bin/device-daemon \
    --config /etc/device-daemon/config.json

Restart=on-failure
RestartSec=3

TimeoutStartSec=30
TimeoutStopSec=20

[Install]
WantedBy=multi-user.target

This is a production-oriented shape, not a universal template. The correct values depend on the device, service role, failure budget and startup contract. The important point is that each line answers an operational question that a one-line ExecStart= unit leaves ambiguous.

SettingQuestion it answers
Type=notifyWhen does the application declare that it is ready?
NotifyAccess=mainWhich process may send lifecycle notifications?
User= and Group=Which Linux identity owns this daemon?
RuntimeDirectory=Where may the service place volatile sockets and runtime files?
StateDirectory=Where may the service keep persistent state?
Restart=on-failureWhich unexpected exits and failures should trigger recovery?
StartLimit*When should repeated start attempts be rate-limited?
TimeoutStartSec=How long may initialization take before it is considered stuck?
TimeoutStopSec=How long may graceful shutdown take before termination is escalated?

Use NotifyAccess=main deliberately. It keeps lifecycle notifications associated with the main service process. Do not casually switch it to all just so a helper can report ready: that makes the boundary less trustworthy because any process belonging to the unit may be allowed to notify the manager.

whattypnnotifychanges

A C++ readiness and shutdown shape


The notification call itself is small. The important part is where it appears in the application lifecycle.

This trimmed example shows the shape for a foreground C++ daemon linked with libsystemd:

#include <systemd/sd-daemon.h>

#include <chrono>
#include <csignal>
#include <cstdint>
#include <cstdlib>

namespace
{
volatile std::sig_atomic_t stopRequested = 0;

extern "C" void requestStop(int) noexcept
{
    stopRequested = 1;
}
}

int main()
{
    struct sigaction action {};
    action.sa_handler = requestStop;
    sigemptyset(&action.sa_mask);

    sigaction(SIGTERM, &action, nullptr);
    sigaction(SIGINT, &action, nullptr);

    Application application;

    if (!application.initialize())
    {
        sd_notify(0,
            "STATUS=Startup failed while initializing device state");
        return EXIT_FAILURE;
    }

    // The daemon now owns its API, event loop and local resources.
    // This is the earliest point where dependents may use it safely.
    sd_notify(0, "READY=1\nSTATUS=Ready to process requests");

    std::uint64_t watchdogUsec = 0;
    const bool watchdogEnabled =
        sd_watchdog_enabled(0, &watchdogUsec) > 0;

    auto nextWatchdog =
        std::chrono::steady_clock::now() +
        std::chrono::microseconds{watchdogUsec / 2};

    while (!stopRequested)
    {
        application.processOneEvent(
            std::chrono::milliseconds{100});

        if (watchdogEnabled &&
            std::chrono::steady_clock::now() >= nextWatchdog)
        {
            sd_notify(0, "WATCHDOG=1");

            nextWatchdog =
                std::chrono::steady_clock::now() +
                std::chrono::microseconds{watchdogUsec / 2};
        }
    }

    sd_notify(0, "STOPPING=1\nSTATUS=Stopping cleanly");

    application.stopAcceptingNewWork();
    application.flushAndClose();

    return EXIT_SUCCESS;
}

The example intentionally keeps the application-specific work behind methods such as initialize(), processOneEvent() and flushAndClose(). Those methods are where the real lifecycle contract lives.

  • initialize() should validate configuration, establish local resources and leave the daemon capable of serving the promised API.
  • READY=1 must come after that work, not immediately after main() begins.
  • The signal handler does only the minimum safe work: it records a stop request. A larger Linux event loop may instead integrate signals through signalfd or another event-loop mechanism.
  • STOPPING=1 reports that the daemon has entered its shutdown path; the actual cleanup still belongs to normal application code.
  • WATCHDOG=1 is optional and should be emitted only by a loop that can credibly represent service liveness.

To link a C++ daemon with the notification library through CMake:

find_package(PkgConfig REQUIRED)

pkg_check_modules(SYSTEMD REQUIRED IMPORTED_TARGET libsystemd)

target_link_libraries(device-daemon
    PRIVATE
        PkgConfig::SYSTEMD
)

Do not use a watchdog as a decorative ping

A watchdog catches a service that stops reporting progress. It does not prove that all business logic is correct. If a separate heartbeat thread keeps sending WATCHDOG=1 while the real event loop is deadlocked, systemd sees a healthy heartbeat and the broken service remains alive.

Startup should fail clearly, not wait forever


A daemon can fail during startup for normal reasons: invalid configuration, permission problems, a missing mandatory device, schema migration failure, incompatible hardware state or an already-bound socket.

For failures that cannot recover inside the process, log the cause and exit. Let systemd record the result and apply the restart policy. Do not spin in an unbounded internal startup loop that hides the fact that the service never became ready.

TimeoutStartSec= protects the other direction: a daemon that has neither completed startup nor exited. With Type=notify, failure to send READY=1 before that deadline is a startup timeout.

The timeout should represent a justified upper bound. It should not be a random huge number added only to silence intermittent test failures.

  • Too short: legitimate cold boot, state recovery or hardware initialization fails unnecessarily.
  • Too long: a genuine boot fault blocks dependents and delays diagnostics for an unreasonable time.
  • Infinite: an initialization deadlock can make the relevant part of the boot graph appear hung indefinitely.

For occasional long operations that can report progress, a notifying service can extend a start or stop timeout with EXTEND_TIMEOUT_USEC=. That is an advanced tool, not a substitute for defining a sane ordinary timeout. It is appropriate only when the daemon can honestly say it is still making progress toward a bounded operation.

Restart is recovery policy, not a crash-loop generator


For most long-running daemons, Restart=on-failure is the sensible starting point. It can recover from an unsuccessful exit, an abnormal termination, a relevant timeout or a watchdog failure, while an explicit systemctl stop does not cause an automatic restart.

That is different from:

Restart=always

Restart=always also restarts after a clean process exit. That can be valid for a deliberately supervised worker, but it is usually surprising for an ordinary product daemon. A clean exit should have an intentional meaning, not be treated automatically as “something crashed.”

SettingUseful interpretationTypical use
Restart=noNo automatic recoveryOne-shot setup, manual test process, externally supervised software
Restart=on-failureRecover from unsuccessful exits, abnormal termination, relevant timeouts and watchdog failuresMost long-running product daemons
Restart=on-abnormalRecover from abnormal signals, timeouts and watchdog events, but not ordinary non-zero exitsDaemons where non-zero exit may intentionally communicate a final outcome
Restart=on-watchdogRecover only after watchdog expirySpecial cases where normal exits must not cause restart
Restart=alwaysRestart after clean and unclean exitsDeliberate supervisor-style patterns

Exit status is part of the lifecycle contract

The opening statement of this article matters here: a non-zero exit does not always mean “please restart me.” Sometimes the daemon has discovered a permanent fault that cannot change until configuration, firmware or the image changes.

For example, suppose the application deliberately returns exit status 78 for an invalid product configuration. You can keep ordinary crash recovery while preventing that specific result from creating a restart loop:

[Service]
Restart=on-failure
RestartPreventExitStatus=78

The service still failed and the failure remains visible, but systemd does not automatically restart it for that status. Similarly, SuccessExitStatus= can declare additional exit codes or signals as clean when the application’s contract genuinely defines them that way.

Give exit codes semantics

If the application can distinguish a transient runtime failure from a permanent configuration error, let the unit policy preserve that distinction instead of restarting both cases blindly.

A restart policy is safe only when restart itself is safe. The process must tolerate being launched again after a partial failure.

  • Do not rely on a stale PID file from the previous process.
  • Do not leave a lock or Unix socket that prevents the next process from starting.
  • Make database and state transitions crash-safe enough that recovery does not make corruption worse.
  • Make externally visible operations idempotent where retries are possible.
  • Do not restart a process merely to repeat a destructive hardware action without first checking the device’s current state.

That is why restart policy belongs in service design, not merely in deployment configuration.

restartpolicyneedscircuitbreaker

Rate limiting is the circuit breaker for repeated failure


Without a limit, a broken service can repeatedly start, fail, write logs, consume CPU, contend for a device and hide the original cause under a flood of repeated messages.

Use a restart delay and a start-rate limit together:

[Unit]
StartLimitIntervalSec=60
StartLimitBurst=5

[Service]
Restart=on-failure
RestartSec=3

In this example, up to five starts may occur inside a sixty-second window. A further start request inside that window is refused by the rate limiter. The limit counts starts, not only crash-triggered restarts, so it is best understood as protection around unit activation rather than as a special “crash counter.”

Hitting the limit is not a permanent lock. Once the interval has passed, a later start request may be allowed again. systemctl reset-failed also clears the failed state and the start-rate counter, which is useful after you have corrected the underlying problem.

The exact values are product decisions. A crash in a human-facing UI may justify a different retry budget than a power-management service. A daemon that talks to an occasionally unavailable modem may need a slower retry path than a daemon whose configuration is permanently invalid.

Separate permanent faults from transient faults

Invalid configuration, missing firmware and incompatible database schema are usually permanent until the image or configuration changes. Temporary network loss and a busy external device may be transient. Design the daemon’s internal retry policy, exit status and systemd restart policy around that difference.

When a unit has hit its start limit, inspect the evidence before clearing it:

systemctl status device-daemon.service --no-pager
journalctl -u device-daemon.service -b --no-pager

systemctl reset-failed device-daemon.service
systemctl start device-daemon.service

Graceful shutdown is part of the API contract


Stopping a service is not just “kill the PID.” A healthy daemon should receive a stop request, stop accepting new work, complete or cancel existing work according to its contract, flush durable state where necessary, close external resources and exit before the shutdown deadline.

When no custom synchronous ExecStop= path takes over the stop procedure, the normal signal-based shutdown begins with SIGTERM by default. systemd then waits up to TimeoutStopSec=. If processes remain, it escalates to SIGKILL by default.

The default KillMode=control-group also matters: remaining processes in the service’s cgroup are managed together, not just one remembered main PID. That is generally what you want. A daemon that spawns workers should not leave those workers alive after systemd believes the unit has stopped.

A SIGKILL is not a graceful shutdown

SIGKILL cannot be handled by the process. It is the manager’s final safety net. If your normal shutdown path reaches it, in-memory work may be lost and cleanup code will not run. Treat repeated stop timeouts as a real defect, not as a normal operating mode.

A service that handles SIGTERM should usually follow this order:

  1. Record that shutdown was requested.
  2. Stop accepting new requests, connections or jobs.
  3. Tell worker loops and background tasks to stop.
  4. Finish, cancel or persist in-flight work according to the API’s documented rules.
  5. Flush only the state that genuinely must be durable before exit.
  6. Close handles, unregister from external systems where needed and exit.

Do not attempt every cleanup action from inside the signal handler itself. A signal handler should do the minimum safe thing: set a signal-safe flag, write to a self-pipe or wake an event-loop mechanism. Let normal application code perform the real shutdown work.

whathappenswhensystemctlstopruns

ExecStop is not a replacement for signal-aware application shutdown


ExecStop= can be useful. For example, it may run a synchronous control command that asks a daemon to execute its own documented graceful shutdown protocol and waits until that protocol completes.

But it is easy to misuse:

[Service]
ExecStop=/usr/bin/kill -TERM $MAINPID

This adds little value. Without such an ExecStop=, systemd already owns the signal-based stop path according to the unit’s kill settings. Worse, an ExecStop= command that merely sends an asynchronous request and exits can tell systemd that the stop command itself has finished even though the daemon has not completed shutdown.

Use ExecStop= when it performs meaningful synchronous work or communicates with a daemon-specific shutdown mechanism and waits for completion. Use ExecStopPost= for post-stop cleanup or diagnostics that should also run after a partially failed startup attempt.

Use a watchdog for “alive but broken” failures


A restart policy helps when the process exits. It does not help when the process remains alive but the event loop is stuck, a deadlock occurred or the daemon stopped making progress.

A systemd watchdog adds a heartbeat contract:

[Service]
Type=notify
NotifyAccess=main
WatchdogSec=30s
Restart=on-failure

After startup, systemd expects the service to send WATCHDOG=1 often enough to satisfy the configured watchdog interval. If the heartbeat is missed, systemd treats the service as failed, terminates it using the watchdog failure path and then applies the restart policy.

Use this only when the ping is tied to meaningful liveness. A good watchdog source is usually the main loop that drives the real service responsibilities. A separate “heartbeat thread” that continues while the rest of the service is frozen creates false confidence.

Later in this series, watchdogs deserve their own article because the details matter: internal versus hardware watchdogs, coredumps after watchdog aborts, timeout selection and how to avoid proving only that one thread still wakes up.

A practical testing workflow


A unit is not production-ready because it starts once on a developer laptop. Test the lifecycle deliberately on the target or on a realistic development image.

TestWhat you should verify
Cold bootThe service reaches active state, declares readiness at the correct point and does not delay unrelated boot work.
Invalid configurationStartup fails clearly, logs the reason and does not enter an uncontrolled retry loop.
Crash during operationRestart=on-failure restarts the service; state recovery is safe and observable.
Permanent failure exitAn exit status intentionally excluded from restart remains failed and visible instead of looping.
Repeated crashStart-rate limiting stops repeated activation attempts from becoming an uncontrolled storm.
systemctl stopThe daemon drains or cancels work as designed and exits before TimeoutStopSec=.
systemctl restartStop then start happens cleanly; stale sockets, locks and workers do not survive.
Dependency starts after this unitThe dependent observes a usable API, not merely an existing PID.
Watchdog failureOnly if enabled: missed heartbeat causes failure and recovery exactly as intended.

Useful commands during those tests:

# Show the current service state and recent journal lines.
systemctl status device-daemon.service --no-pager

# Show unit properties that describe the lifecycle and last result.
systemctl show device-daemon.service \
  -p ActiveState \
  -p SubState \
  -p Result \
  -p MainPID \
  -p ExecMainCode \
  -p ExecMainStatus \
  -p NRestarts \
  -p StateChangeTimestamp

# Read all logs for this service from the current boot.
journalctl -u device-daemon.service -b --no-pager

# Follow logs while stopping or restarting the daemon.
journalctl -u device-daemon.service -f

# Validate syntax and inspect the effective unit configuration.
systemd-analyze verify /etc/systemd/system/device-daemon.service
systemctl cat device-daemon.service

When testing a readiness protocol, do not stop at systemctl is-active. Add an integration test that starts the consumer immediately after the service becomes active and proves that the consumer can use the API promised by the readiness contract.

Test the contract, not the PID

A successful test is not “systemd says the service is active.” A successful test is “the service is active, its promised API is usable, it recovers from expected failures and it exits cleanly within the shutdown budget.”

productionservicelifecycletest

Common mistakes


  • Sending READY=1 as soon as the process starts. This defeats the purpose of Type=notify.
  • Using Type=simple while dependents need a real readiness boundary. With simple, even successful execve() is not the readiness contract.
  • Using Restart=always by habit. It changes the meaning of a clean exit and can make intentional process termination surprising.
  • Treating every non-zero exit as transient. Use explicit exit semantics when a permanent fault should remain failed instead of restarting.
  • Restarting immediately forever. Use RestartSec= and start-rate limits so a permanent fault becomes visible.
  • Ignoring stale state after a crash. Restart only helps if the next process can safely reclaim sockets, files, locks and persistent state.
  • Handling SIGTERM by abruptly exiting. That can lose work or state that the daemon’s public contract promised to preserve.
  • Making the stop timeout infinite. It replaces one shutdown problem with an unbounded shutdown hang.
  • Using ExecStop= only to send a signal. systemd already owns the normal signal-based stop path; use ExecStop= for meaningful synchronous shutdown work.
  • Adding a watchdog ping from an unrelated thread. A heartbeat is valuable only when its source reflects the liveness you actually care about.

Production checklist


  1. Define what “ready” means in one sentence that a dependent service can rely on.
  2. Use Type=exec or Type=notify deliberately; avoid self-daemonizing new code unless you have a concrete compatibility reason.
  3. If using Type=notify, send READY=1 only after the service can meet its readiness promise.
  4. Set a realistic TimeoutStartSec= and make startup failures visible in the journal.
  5. Use Restart=on-failure for most long-running daemons, then decide which exits should be treated differently.
  6. Use RestartPreventExitStatus= or SuccessExitStatus= when the application’s exit contract needs more precision than zero versus non-zero.
  7. Add RestartSec=, StartLimitIntervalSec= and StartLimitBurst= to contain restart storms.
  8. Design startup and recovery to tolerate stale state from a previous interrupted process.
  9. Handle SIGTERM by transitioning the normal event loop into an orderly shutdown path.
  10. Set a justified TimeoutStopSec=, then treat regular use of SIGKILL as a defect to investigate.
  11. Add WatchdogSec= only after you can implement a credible liveness signal.
  12. Test cold boot, invalid config, permanent-failure exits, crash recovery, crash loops, stop, restart and immediate use by dependents.

The key idea


If you remember only one thing, remember this:

Tip

A production systemd service does not merely launch a process. It defines a lifecycle: when the service becomes usable, which failures justify recovery, which failures should remain visible, how repeated failure is contained and how the process exits without relying on forced termination.

Once that lifecycle is explicit, systemd stops being a wrapper around ExecStart=. It becomes the manager that can coordinate your daemon with the rest of the device: wait for a meaningful readiness boundary, observe failures, restart safely and enforce a bounded shutdown.

The next practical layer is observability. A good lifecycle contract is only useful when the team can see what happened on a real device, which makes systemd-journald the natural next topic in the series.