Every unit file on a stock Debian 12 or Ubuntu 24.04 system is written for a machine with time to spare. The defaults assume the process will be given CPU when it asks, that memory is available, and that the journal has room to grow. On a 2 vCPU / 4 GB VPS none of those assumptions hold under load, and the observable symptoms — a web app that takes 40 seconds to drain on reload, a worker that restarts 200 times an hour, journald pinning a core — are all traceable to specific unit file directives that nobody changed from the default.
The directives below were verified on a KVM instance running systemd 255, with every number read from systemctl show, systemd-analyze or systemd-cgtop before and after the change. See virtualserversvps.com for the base images these units run on.
The measurement setup: what “before” looked like
The test service was gunicorn (4 workers) plus a background queue worker, both under documentation-default units, serving 60 req/s of mixed static and dynamic traffic:
systemctl show -p IPAccounting myapp-webreported no data at all — the default unit collects nothing, so per-service resource attribution was impossible.systemd-cgtop -m -n 1showed the web service peaking at 1.9 GB RSS during a reload, which on a 4 GB box with PostgreSQL resident put the machine 18% into swap.systemd-analyze blameattributed 6.4 s of the 31 s boot to a unit waiting onnetwork-online.targetthat did not need the network.journalctl --disk-usagereached 1.7 GB in 19 days, and the-o jsonformatting cost showed up as 9% of one core inpidstatduring a log-heavy job.
Memory accounting is off by default — turn it on before tuning
The single most common mistake is setting MemoryHigh or MemoryMax and assuming they work. They only take effect when the service is placed in its own cgroup v2 hierarchy with accounting enabled, which systemd does implicitly for services but which you cannot observe without MemoryAccounting=yes. Without it, MemoryCurrent reads [not set] and memory.events is empty, so an OOM kill arrives with no warning data.
systemctl show -p MemoryAccounting,MemoryCurrent,MemoryPeak myapp-web
# before: MemoryAccounting=no MemoryCurrent=[not set]
# after: MemoryAccounting=yes MemoryCurrent=412352512 MemoryPeak=1987342336
With accounting enabled, memory.events becomes the primary signal: high counts throttles, max counts hard-limit hits, oom_kill counts kills. A rising high with zero max is the intended shape — reclaim and throttle instead of kill.
Two-tier memory limits: MemoryHigh reclaims, MemoryMax kills
MemoryHigh is not a soft warning; it is a reclaim throttle. Above it the kernel forces page-cache reclaim and then puts tasks to sleep in direct reclaim — slowing the service rather than killing it. MemoryMax is the OOM boundary; keep them at least 30% apart so reclaim has room to act.
| Directive | Baseline (no limit) | Tuned value | Measured effect |
|---|---|---|---|
MemoryHigh | unset | 1G | peak RSS 1.9 GB → 1.02 GB; p99 latency +7 ms |
MemoryMax | unset | 1.4G | memory.events high 0→411/24h, oom_kill stays 0 |
TasksMax | 15838 (kernel default 15%) | 512 | fork-bomb worker capped, host stayed responsive |
CPUQuota | unset | 150% | host load average 14.2 → 5.1 during batch |
IOWeight | 100 | 300 | worker fsync p95 41 ms → 12 ms under DB load |
LimitNOFILE | 1024 | 65536 | removed EMFILE bursts above 800 rps |
150% on a 2 vCPU host leaves half a core for the database. In cpu.stat, nr_throttled climbing while throttled_usec stays under a few ms per period means the quota is close to right.
Restart policy: bound the loop instead of hiding it
Most generated units use Restart=no, so a crashed worker stays dead; Restart=always without a limit is worse, respawning a failing service in a tight loop. The start limit bounds that, but as of systemd 229 the rate-limit directives moved from [Service] to [Unit] — units that put StartLimitBurst under [Service] silently ignore it.
[Unit]
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Restart=on-failure
RestartSec=2
RestartPreventExitStatus=78
RestartSec=2 rather than 100 ms is deliberate: an instant respawn against a saturated connection pool just re-fails. RestartPreventExitStatus=78 is sysexits EX_CONFIG; a malformed config never succeeds on retry, so the unit should go failed and alert. Check systemctl show -p NRestarts myapp-worker — a large number means a start limit is too generous or absent. If the app can call sd_notify(), add WatchdogSec=, which catches the case a restart policy cannot: a process that is alive but wedged.
Ordering: network-online.target is not what you think
Ordering failures cause a disproportionate share of slow boots. network.target is reached when the stack is configured, often before an address is routable; network-online.target waits for systemd-networkd-wait-online.service and on a DHCP cloud image adds 5–10 s of dead time. A server binding 0.0.0.0 does not need it; a worker connecting to a remote queue does.
# measure what a unit actually waits for
systemd-analyze critical-chain myapp-web.service
systemd-analyze blame | head -15
systemctl list-dependencies --after myapp-web.service
Use After= for ordering and Wants= for a soft dependency; Requires= propagates failure and takes your web service down when an optional cache restarts. For PostgreSQL, After= plus Wants= is enough — it orders at start, not readiness, so the app must retry.
Startup type and timeouts
Type=simple declares the service started when fork() succeeds, so systemctl start returns before the socket is bound and After= chains race the listener. Type=notify (or notify-reload), or Type=exec if the app cannot notify, makes ordering meaningful; switching the measured web unit cut deploy-time “connection refused” errors that had been blamed on the load balancer. Set TimeoutStopSec= slightly above your slowest request: after SIGTERM, systemd escalates to SIGKILL on the whole cgroup.
Hardening directives that cost nothing at runtime
Most sandboxing directives are namespace and seccomp setup applied once at exec with no steady-state cost. The exceptions: MemoryDenyWriteExecute=yes (breaks JITs) and SystemCallFilter=@system-service, which added 1–2% on a syscall-heavy benchmark.
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/myapp /var/log/myapp
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
LockPersonality=yes
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
ProtectSystem=strict makes the filesystem read-only except /dev, /proc and /sys; anything writable needs an explicit ReadWritePaths=, which catches apps writing into their own install directory. Score the result with systemd-analyze security myapp-web.service: a hardened web unit lands near 3.5 “OK” exposure versus 9.6 “UNSAFE” bare.
Journal cost per unit, not just globally
Global journald.conf limits are blunt; per-unit rate limiting is per unit. If one service is chatty, redirect it to StandardOutput=append:/var/log/myapp/app.log and let logrotate take it.
[Service]
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp-web
LogRateLimitIntervalSec=30
LogRateLimitBurst=1000
The budget is per interval: 1000 in 30 s is ~33/s sustained, which a healthy app never exceeds; beyond it systemd writes one “Suppressed N messages” line, visible in journalctl -u myapp-web. Pair with SystemMaxUse=500M and MaxRetentionSec=14day.
Verify the applied state, not the file
Any directive above is silently ignored if misplaced or misspelled. systemctl show prints the merged effective value including drop-ins; systemctl cat shows which files contributed.
systemctl daemon-reload
systemd-analyze verify /etc/systemd/system/myapp-web.service
systemctl show myapp-web -p MemoryMax -p MemoryHigh -p CPUQuotaPerSecUSec \
-p TasksMax -p Restart -p StartLimitBurst -p NRestarts
systemctl status myapp-web --no-pager
systemd-cgtop -m -n 3 --depth=1
Run daemon-reload after any edit; limit changes need a restart, or systemctl set-property myapp-web MemoryMax=2G, which applies immediately and persists under /etc/systemd/system.control/. Ship unit files with the application and keep systemd-analyze as the regression test.


Leave a Reply
You must be logged in to post a comment.