systemd Services for Web Workers: Restarts, Limits and Safe Deploys
A background worker needs more than nohup. Use systemd to control its identity, restart behaviour, environment and resource limits, then verify graceful shutdown during a deployment.

A worker launched with nohup can survive a terminal closing. That is a very small part of running a service. It still needs a defined user, logs, restart behaviour, resource limits and a deployment procedure that does not abandon half-finished jobs.
On a Linux host using systemd, a service unit gives those responsibilities a visible place. The unit is not a substitute for durable application logic, but it can stop process management being an undocumented shell command in somebody's history.
Choose a service identity
Run the worker as a dedicated non-login user with only the permissions it needs. Keep application releases separate from writable state. A process should not generally be able to rewrite its own executable files.
Use a stable current symlink for the selected release if that fits your deployment system, and keep writable state under a deliberate directory such as /var/lib/example-worker. The paths in this article are examples, not assumptions about your server.
Check the runtime's actual path and version. A service does not automatically inherit the interactive shell environment that made a command work over SSH. An executable installed through a user's shell profile may not be available to the service user.
Write a conservative unit
This example runs an installed Python worker. The worker script must implement queue claiming and graceful signal handling; systemd cannot invent those behaviours.
[Unit]
Description=Example background worker
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=example-worker
Group=example-worker
WorkingDirectory=/srv/example-worker/current
EnvironmentFile=/etc/example-worker/worker.env
ExecStart=/usr/bin/python3 /srv/example-worker/current/worker.py
Restart=on-failure
RestartSec=5
TimeoutStopSec=90
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
StateDirectory=example-worker
MemoryHigh=512M
MemoryMax=768M
[Install]
WantedBy=multi-user.targetThe memory values are illustrative and must be sized from real measurements. Check directive support on your distribution and systemd version. A sandbox directive that works on one host may be unsupported or behave differently on another.
network-online.target expresses ordering around configured network readiness. It does not guarantee that your database or queue is reachable. The application still needs bounded connection retry and clear failure reporting.
Understand restart behaviour
Restart=on-failure restarts after defined failure conditions rather than an intentional successful exit. Rate limiting prevents an immediate crash loop from consuming the machine indefinitely. When the start limit is hit, inspect and fix the cause before resetting the failed state.
A service that exits successfully while work remains will not necessarily be restarted by this policy. Design the worker as a persistent process, or choose a timer or batch-job arrangement for a finite operation. Do not rely on accidental exit codes to define scheduling.
MemoryMax is a hard boundary, not a graceful pressure signal. A worker exceeding it may be killed. Measure normal and worst-case job usage, control concurrency and reject oversized inputs before the kernel has to make the decision for you.
Handle secrets deliberately
An EnvironmentFile is convenient but not a full secret-management system. Restrict ownership and file permissions, keep it out of source control, and avoid printing its values in startup diagnostics.
For stronger handling, review systemd credential facilities and your infrastructure's secret-delivery mechanism. The correct choice depends on supported systemd versions and how the application reads secrets. Environment values can be visible through privileged process inspection, so do not claim they are intrinsically hidden.
Log only configuration names and whether required values are present. A troubleshooting command that dumps the entire process environment can disclose every credential the worker uses.
Make shutdown part of the application
On stop, systemd normally sends a termination signal and waits up to the configured timeout before escalating. Your worker should stop claiming new jobs, finish or checkpoint the current job, and exit within that budget.
If a job cannot finish before the timeout, leave a durable state another worker can recover. Queue acknowledgement belongs after successful processing, with idempotent handling for duplicate delivery. A graceful process stop does not guarantee exactly-once external side effects.
Test shutdown during actual work. A worker that exits cleanly while idle has not demonstrated that a deployment is safe for a five-minute document analysis.
Deploy with a verification step
Build the release before switching the current symlink. Check dependencies, file ownership and configuration. Validate the unit before loading it:
sudo systemd-analyze verify /etc/systemd/system/example-worker.service
sudo systemctl daemon-reload
sudo systemctl enable --now example-worker.service
sudo systemctl status example-worker.service --no-pager
sudo journalctl -u example-worker.service -n 80 --no-pagerdaemon-reload refreshes unit definitions; it does not restart a running service by itself. After changing the application release, perform the intended restart and verify the worker actually uses the new release. Keep the old release available for rollback.
A running PID is not proof of useful service. Confirm that a test job is claimed, completed and read back through the application. Monitor queue age and completed jobs alongside process uptime.
Add hardening incrementally
ProtectSystem=strict makes much of the filesystem read-only for the service. StateDirectory provides the intended writable state location. If the worker legitimately needs another path, add a narrow exception and document why.
PrivateTmp isolates temporary-directory views. That can break workflows that intentionally exchange files with another service through /tmp; use an explicit shared directory with controlled permissions instead.
Review systemd-analyze security as a checklist, not a score to maximise blindly. Each restriction should match the worker's actual behaviour, and every exception should remain understandable after the person who added it leaves.
A well-run service is boring in a productive way. You can identify its user, inspect its logs, stop it safely, restart it predictably and prove that it completed work. That is a much stronger operational contract than a command somebody remembers typing last month.
Paj Digital Labs
The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.
Related reading

PostgreSQL Connection Budgets: Pooling Without Hiding the Bottleneck
More application workers can exhaust database connections long before CPU is full. Budget the whole fleet, understand pool modes and test session behaviour before adding a pooler.

Restore Drills for a Whole Website: Rebuild the Service, Not Just the Database
A database restore can succeed while the website remains unusable. Test files, configuration, identity, DNS and external dependencies in an isolated recovery environment.

TLS Certificate Renewal: Verify the Served Certificate, Not Just the Cron Job
A successful renewal command does not prove visitors see the new certificate. Trace issuance, reloads, proxy termination and external monitoring before an expiry becomes an outage.