The Complete Guide to Virtual VPS Server Rental: Everything You Need to Know in 2025

systemd Unit File Tuning on a VPS: Limits, Restart Loops, Ordering and Sandboxing

A systemd unit file is a resource-allocation document that most VPS operators copy from a tutorial and never revisit. The default directives are conservative in the wrong places: no memory ceiling, no restart backoff cap, no ordering guarantee beyond “after basic.target”, and Type=simple even when the process forks and reports readiness late. The result is a service that looks fine in systemctl status while a 40-line PHP worker allocates 900 MB, restart-loops 300 times an hour, and drags the box into swap.

The unit below is a realistic template for a background job runner on a 2 vCPU / 4 GB instance, with every directive justified by a measurement you can reproduce. If your service is already running, the fastest way to see what it actually costs is described in the memory budgeting guide for small VPS instances — get the RSS plateau figure first, then set limits from it rather than from a guess.

Start from a measured baseline

For a week, record what the process actually uses: peak RSS, peak CPU, file descriptors, and how often it forked. systemd-run --scope plus systemd-cgtop gives you per-unit numbers without touching the unit file.

sudo systemd-cgtop -P -m -1 --iterations=1 | head -20
systemctl show myapp.service -p MemoryPeak -p CPUUsageNSec -p TasksMax
# per-process peak right now
systemd-cgtop --depth=1 myapp.service

On a typical PHP worker fleet, peak RSS per child lands at 45–90 MB with OPcache enabled; a Python job runner with pandas loaded can sit at 350–600 MB. Whatever the number is, MemoryMax should be roughly 1.5× the observed peak, and MemoryHigh about 1.1× — the two together give you a soft throttle before a hard kill.

The annotated unit file

[Unit]
Description=myapp background job runner
After=network-online.target redis.service
Wants=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
Type=notify
NotifyAccess=main
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp
Environment=NODE_ENV=production
ExecStartPre=/usr/bin/test -r /srv/myapp/current/app.js
ExecStart=/usr/bin/node /srv/myapp/current/app.js
KillSignal=SIGTERM
TimeoutStopSec=20
Restart=on-failure
RestartSec=2

# resource ceilings
CPUQuota=180%
MemoryHigh=700M
MemoryMax=900M
TasksMax=256
LimitNOFILE=65535
IOWeight=80

# scratch space and permissions
RuntimeDirectory=myapp
RuntimeDirectoryMode=0750
StateDirectory=myapp
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/srv/myapp/storage

[Install]
WantedBy=multi-user.target

Note where StartLimit* lives: in [Unit], not [Service]. Putting them in the service section is silently ignored and is the single most common reason a crash-looping unit restarts forever despite a “burst limit”.

Restart semantics: the settings that cause loops

Restart=always combined with RestartSec=100ms is how a missing environment file turns into a fork bomb. on-failure excludes clean exits, and RestartSec=2 gives dependencies time to come up without waiting the default 100 ms. The burst limit then caps the whole thing at five attempts per five minutes, after which the unit enters failed and stays there — which is what you want, because a service that cannot start should page you, not spin.

# proof of the backoff behaviour
sudo systemctl restart myapp
sudo journalctl -u myapp -f --since "1 min ago"
# watch the attempt counter
systemctl show myapp -p NRestarts -p Result -p ActiveState

# reset the counter after fixing the cause
sudo systemctl reset-failed myapp && sudo systemctl start myapp

Type=notify versus Type=simple

Type=simple tells systemd the service is ready the instant fork() returns. For a Node or Python process that binds a socket two seconds later, everything ordered After=myapp.service starts too early. Type=notify waits for an sd_notify(READY=1) call — supported natively by uvicorn’s --sd-notify, gunicorn’s systemd worker class, and most supervisors via a three-line wrapper.

# uvicorn speaks sd_notify directly
ExecStart=/usr/bin/uvicorn app:api --host 127.0.0.1 --port 8000 --sd-notify

# verify readiness is actually reported
systemd-analyze verify /etc/systemd/system/myapp.service
systemctl show myapp -p Type -p NotifyAccess

Ordering, dependency direction and the timeouts that hide bugs

Timeouts deserve the same scrutiny. TimeoutStopSec=20 with KillSignal=SIGTERM gives a worker 20 seconds to drain in-flight jobs; the default 90 seconds means a hung job delays every restart and, during shutdown, delays reboot by up to 90 seconds per unit. Check with systemd-analyze blame | head after a reboot — a long tail there is almost always stop timeouts, not start time.

Sandbox directives and what they cost

ProtectSystem=strict, PrivateTmp=yes and NoNewPrivileges=yes are free at runtime and prevent the classic post-exploitation path of dropping a binary into /tmp and executing it. The measured cost is in start time, not throughput: systemd-analyze shows roughly 3–6 ms extra namespace setup per start on a KVM VPS, which is irrelevant. The real cost is debugging — a service that writes to /var/lib/myapp without StateDirectory= will fail under ProtectSystem=strict with an EROFS the app may not log clearly.

# find what the unit is allowed to touch when it misbehaves
systemd-analyze security myapp.service
# list the effective sandbox settings
systemd-analyze cat-config systemd/system/myapp.service

Verify the limits are enforced, not just declared

A unit file that passes systemd-analyze verify can still be silently misconfigured if the cgroup hierarchy does not support the controller. Confirm each limit at runtime.

cat /sys/fs/cgroup/system.slice/myapp.service/memory.max
cat /sys/fs/cgroup/system.slice/myapp.service/cpu.max
cat /sys/fs/cgroup/system.slice/myapp.service/pids.max

# force a memory breach and watch the counter
systemctl show myapp -p MemoryCurrent -p MemoryEvents

sudo systemctl daemon-reload
sudo systemctl restart myapp
systemctl status myapp --no-pager

If memory.max still reads max, your unit was written for cgroup v1 syntax (MemoryLimit=) or the kernel booted with systemd.unified_cgroup_hierarchy=0. MemoryLimit= is not an alias — it is ignored on v2, and that mismatch is invisible until a memory-hungry process takes down the box. Pair these limits with a memory ceiling on any database on the same instance, and if the box is genuinely undersized for the workload, upgrading to a larger VPS plan is cheaper than tuning a 1 GB instance into swap thrash.

Leave a Reply