Home Server & Self-Hosting

systemd Path Units on a Home Server - React to File Changes Without Treating Events as a Queue

systemd Path Units on a Home Server - React to File Changes Without Treating Events as a Queue

A home server may need to rebuild an index when content changes, import a file after it arrives, or reload generated data after a local process replaces it. Running a cron job every minute is easy to understand, but it asks the same question repeatedly even when nothing happened. Can systemd start the work from a filesystem change instead?

A .path unit can do that for modest local workflows. The useful model is narrower than “reliable event processing,” however. The path unit notices filesystem state and activates another unit; it does not turn the filesystem into a durable queue. That distinction shapes which directive to choose, how the worker should behave, and when a timer or application-level queue remains the safer design.

The path unit watches; the service does the work

The systemd project’s systemd.path documentation defines a path unit as configuration for path-based activation. By default, site-index.path activates site-index.service. A Unit= setting can select a different target, but matching base names make the relationship easier to inspect.

This separation is useful. The .path file says when to ask for work; the .service file says which process runs, under which account, and how its result is recorded. For finite work such as rebuilding an index, Type=oneshot is a natural starting point: the systemd.service manual describes it as a service whose start command runs to completion before the start operation is considered finished.

Internally, path units use Linux inotify. This makes them event-driven for supported local filesystems, but it also gives them the same boundaries as that API. It is better to think of a path unit as a doorbell than a ledger: it can tell the worker to look outside, but it is not a permanent list of every visitor.

Choose a directive by the condition you actually need

The directive names look similar, yet their activation semantics differ:

  • PathChanged= watches a file or directory for changes. For a watched file, it does not activate on every write; it activates when a file opened for writing is closed.
  • PathModified= is similar but additionally reacts to simple writes. That may be too noisy when a program writes a file in several steps.
  • PathExists= activates while one exact path exists.
  • PathExistsGlob= activates when at least one path matches a glob.
  • DirectoryNotEmpty= activates while a directory contains at least one file.

All of these settings require absolute paths, and multiple checks may be combined. The Debian 12 systemd.path(5) page documents the same set in systemd 252, so the example does not depend only on a newer upstream manual.

The most important design difference is between a change and a state that remains true. If a PathExists= target already exists, or a DirectoryNotEmpty= directory already contains a file when the watcher starts, systemd activates the target immediately. When the service exits, systemd checks the paths again. If the worker leaves that condition true, it may be started again until rate limiting stops the cycle.

That behavior can be exactly right for an inbox worker that moves successfully processed files elsewhere. It is wrong for a service that only logs the name and leaves every file in place. PathChanged= is often a clearer fit when the goal is to rebuild derived state after a local content directory changes.

A minimal site-index example

Suppose content lives in /srv/example-site/content, and an existing program called /usr/local/sbin/rebuild-site-index can safely rebuild its search index. The following files are a generic pattern, not a claim about the configuration of this website.

Create /etc/systemd/system/site-index.path:

[Unit]
Description=Watch for content changes that require a site index rebuild

[Path]
PathChanged=/srv/example-site/content

[Install]
WantedBy=multi-user.target

Because the base names match, an explicit Unit=site-index.service would be redundant. Keeping the default also removes one place where two names could drift apart.

Then create /etc/systemd/system/site-index.service:

[Unit]
Description=Rebuild the example site index

[Service]
Type=oneshot
User=sitebuilder
Group=sitebuilder
ExecStart=/usr/local/sbin/rebuild-site-index /srv/example-site/content

The worker path is intentionally explicit. systemd does not interpret ExecStart= as a shell command line by default, so shell operators, redirections, and pipelines should not be slipped into it as if it were a crontab. If shell behavior is truly needed, put it in a reviewed script with a clear interpreter and make that script the executable.

The service account needs read access to the content and only the write access required for the generated index. A path activation is not an authorization check: if an untrusted account can alter the watched directory, it may be able to cause repeated service starts and supply input to the worker. The worker must still validate what it reads.

Verify before enabling

Administrator-created system units belong under /etc/systemd/system, as described by both the upstream unit search path and the Debian Reference. Before asking PID 1 to load them, check both files together:

sudo systemd-analyze verify \
  /etc/systemd/system/site-index.path \
  /etc/systemd/system/site-index.service

The systemd-analyze manual says verify can report problems such as unknown directives, missing required units, and unavailable commands. It cannot prove that the indexer handles malformed files, writes atomically, or produces the right index. Syntax validation is one gate, not an integration test.

After a clean review, reload unit definitions and enable the watcher:

sudo systemctl daemon-reload
sudo systemctl enable --now site-index.path
systemctl status site-index.path

Enabling the .path unit makes the watcher available after boot; the oneshot service itself does not need to be enabled. A controlled content change can then test activation. Inspect both units and the service journal rather than assuming that an active watcher means successful work:

systemctl status site-index.path site-index.service
journalctl -u site-index.path -u site-index.service

When either unit file changes later, run daemon-reload and restart the path unit so the active watcher uses the reviewed definition. If rate limiting has placed a unit in a failed state, fix the persistent trigger or failing worker first; repeatedly resetting failure without removing the cause only resumes the loop.

Write the worker to reconcile state, not count events

The Linux inotify(7) manual explains why an event count is a weak foundation. Identical unread events may be coalesced. The event queue can overflow. A filename may have been renamed or deleted by the time a consumer handles the notification. The API also does not identify the user or process that caused an event.

A robust oneshot worker should therefore read the current source of truth and make the derived state match it. An index builder can scan the current content set and replace the completed index atomically. An inbox worker can claim a file through a safe rename, record completion outside the inbox, and tolerate another invocation. The exact mechanism depends on the application, but the useful properties are consistent:

  • Running the worker twice should not corrupt the result.
  • A stale or missing filename should be an expected race, not a surprise.
  • Partial output should not replace the last known-good output.
  • Failures should leave enough journal context to diagnose and retry deliberately.
  • The worker should inspect current state instead of assuming one start equals one filesystem event.

systemd also applies protection against rapid activation loops. Path units have trigger rate-limit settings, and the triggered service is subject to unit start limits. These controls contain a loop; they do not make the workflow lossless. If a rate limit is reached, the relevant unit can enter a failed state and stop watching until the problem is corrected and the unit is restarted.

Know what path activation cannot promise

The limits are not merely theoretical footnotes:

  • Remote changes may be invisible. inotify reports filesystem operations observed locally. The systemd documentation specifically warns that path units cannot monitor changes made by other machines on remote NFS filesystems.
  • Directory watching is not recursively complete. inotify does not automatically watch every nested subdirectory. A dedicated watcher that manages a changing tree of watches may be necessary.
  • Events may be merged or lost. Coalescing and queue overflow rule out using notifications as an audit log or exact counter.
  • Memory-mapped changes have caveats. The inotify manual says accesses and modifications through mmap, msync, and munmap are not reported by the API.
  • Hidden files are generally ignored by systemd path monitoring. A workflow that depends on dotfiles needs explicit testing or a different mechanism.
  • A trigger carries no trust. Activation says that a condition was observed, not that the input is safe or that a particular actor caused it.

These boundaries help choose a better tool. A systemd timer is often preferable when periodic reconciliation is acceptable or the storage is remote. A durable application queue is appropriate when every job needs an identifier, retry state, ordering, ownership, or an audit trail. A dedicated watcher is better when recursive trees and event details matter. Sometimes a path unit can provide a quick reaction while a slower timer periodically reconciles state, but that is defense in depth, not exactly-once processing.

Conclusion

A systemd path unit is a compact way to connect a local filesystem condition to a supervised service. It removes a polling loop, keeps the worker’s logs and identity in the systemd model, and can make small home-server automations easier to inspect.

Its strength comes from staying within that modest role. The path unit is a signal to examine current state, not a durable record of every change. Choose the directive by whether the condition is transient or persistent, make the worker idempotent, validate both units, and test the failure path as carefully as the happy path. If the workflow cannot tolerate a coalesced or missed event, the open question is no longer how to tune .path; it is which durable queue or reconciliation design should replace it.

References