September 6, 2026
Runtime Directories Done Right: systemd-tmpfiles and systemd-sysusers
A service that runs as root, creates whatever directories it needs and leaves ownership hidden in startup scripts is not really integrated with the system. It is only running on it.
Many embedded Linux services begin with a small executable and a small unit file. Then the setup around them grows:
mkdir -p /run/device-agent
chown device-agent:device-agent /run/device-agent
chmod 0750 /run/device-agent
Maybe this lives in a startup script. Maybe it moves into ExecStartPre=. Maybe the daemon performs the same work itself. A package hook creates the user. Another component later needs a shared directory and adds another script with slightly different permissions.
The device boots, but the operational contract is now spread across shell fragments, package behavior and assumptions that are difficult to review.
Systemd gives us a better separation:
- the service unit can declare directories that belong to one service;
tmpfiles.dcan declare filesystem state with a broader lifecycle, including cleanup;sysusers.dcan declare the static service users and groups that own that state.
The important result is not prettier configuration. It is a reviewable ownership model: who runs the process, which state is volatile, which state survives reboot, what is shared, and who is responsible for cleanup.
Note
This is the fifth article in the Systemd in Embedded Linux series. The previous posts introduced systemd as more than systemctl, explained unit dependencies and boot failures, and then covered production service lifecycle: readiness, restart and shutdown. This article focuses on the evidence those services leave behind when something goes wrong.

The actual problem is not mkdir
Creating a directory is easy. Defining its owner, lifetime and failure behavior is the real work.
Consider a daemon that exposes a local Unix socket, stores a registration database and downloads update metadata. Those objects should not all be treated as the same kind of filesystem state.
| State | Typical location | Expected lifetime | Good first tool |
|---|---|---|---|
| Unix socket, lock, transient IPC data | /run | Service or boot lifetime | RuntimeDirectory= |
| Database, enrollment state, durable queue | /var/lib | Survives service restart and reboot | StateDirectory= |
| Rebuildable cache | /var/cache | May survive reboot but is disposable | CacheDirectory= |
| Filesystem logs when required | /var/log | Product retention policy | LogsDirectory= |
| Administrator or image configuration | /etc | Persistent, normally not daemon-owned | ConfigurationDirectory= or explicit read-only access |
| Shared spool, import area, retention-managed state | Product-specific | Explicit product contract | tmpfiles.d |
Once these categories are mixed, subtle bugs appear. A socket placed in /var/lib leaves stale runtime evidence behind. A database stored under /run disappears on reboot. A rebuildable cache becomes too dangerous to clean because somebody started treating it as source-of-truth state.
Declaring a writable directory is not a filesystem sandbox
StateDirectory= or RuntimeDirectory= gives the service a managed location. It does not automatically prevent the process from writing to every other path its Unix identity can access. Restricting the filesystem view belongs to the hardening layer with settings such as ProtectSystem= and carefully chosen writable exceptions.
Start with directories owned by one service
When a directory belongs to one service, first ask whether the unit can declare it directly. For the standard service paths this is normally clearer than maintaining a separate tmpfiles.d rule.
[Service]
Type=exec
User=device-agent
Group=device-agent
RuntimeDirectory=device-agent
RuntimeDirectoryMode=0750
StateDirectory=device-agent
StateDirectoryMode=0750
CacheDirectory=device-agent
CacheDirectoryMode=0750
ExecStart=/usr/bin/device-agent
Restart=on-failure
The manager creates the paths before executing the service:
RuntimeDirectory=device-agentcreates/run/device-agent.StateDirectory=device-agentcreates/var/lib/device-agent.CacheDirectory=device-agentcreates/var/cache/device-agent.
For these service-owned directories, systemd can also apply the configured owner and top-level directory mode. The daemon does not need to start as root merely to prepare its own filesystem layout.
ConfigurationDirectory= is slightly different. It creates configuration below /etc, but unlike the state, cache, log and runtime directory settings, it is not automatically made owned by the service’s User= and Group=. That is normally desirable: static configuration should usually be provided by the image or administrator rather than rewritten by the daemon.
Existing state deserves attention
If one of the managed state directories already exists with different ownership, systemd may recursively correct ownership below it. On a small directory this is useful. On a large persistent data tree or after a UID migration it can be expensive and operationally surprising. Test upgrades with real state, not only with an empty development image.
Use the directory environment variables instead of duplicating paths
Systemd exposes the resulting paths to the process through variables including RUNTIME_DIRECTORY, STATE_DIRECTORY, CACHE_DIRECTORY, LOGS_DIRECTORY and CONFIGURATION_DIRECTORY.
That lets the executable consume the directory contract instead of independently hardcoding the same paths:
#include <cstdlib>
#include <filesystem>
#include <stdexcept>
#include <string>
namespace fs = std::filesystem;
fs::path requiredDirectory(const char* variable)
{
const char* value = std::getenv(variable);
if (value == nullptr || *value == '\0') {
throw std::runtime_error(
std::string{"Missing systemd directory variable: "} + variable);
}
return fs::path{value};
}
int main()
{
const fs::path runtimeDirectory =
requiredDirectory("RUNTIME_DIRECTORY");
const fs::path stateDirectory =
requiredDirectory("STATE_DIRECTORY");
const fs::path controlSocket =
runtimeDirectory / "control.sock";
const fs::path database =
stateDirectory / "devices.db";
// Bind controlSocket.
// Open or create database.
// Privileged mkdir/chown setup is not application work.
}
This example configures one directory for each setting. If a setting declares several directories, its environment variable may contain multiple paths rather than one simple filesystem path, so code that supports that case must parse the contract accordingly.
The application still needs normal error handling. Storage can be full, the filesystem can become read-only and an I/O operation can fail. The difference is that privileged provisioning is no longer mixed into application startup.
Runtime state and persistent state must not be confused
The most important distinction is usually between RuntimeDirectory= and StateDirectory=.
A runtime directory is for state that only makes sense while the service is alive: Unix sockets, lock files, transient IPC metadata and similar objects.
By default, a directory declared with RuntimeDirectory= is removed when the service stops. RuntimeDirectoryPreserve=restart can keep it across restart operations, while RuntimeDirectoryPreserve=yes keeps it after ordinary stops as well. Regardless, system-level /run remains volatile across reboot.
A state directory is different. It is for durable data that should survive ordinary service restarts and reboots: local databases, enrollment state, persistent queues or other application-owned state.
Rule of thumb
If losing the data at reboot is correct, it is probably runtime state. If losing it requires recovery, reenrollment or reconstruction from an authoritative source, it is probably persistent state.

Do not make tmpfiles.d the answer to everything
tmpfiles.d is broader than “create my daemon directory.” It can create files and directories, adjust ownership and modes, create links and devices, and remove or age out declared filesystem content.
That makes it useful when the filesystem contract is independent of one service lifecycle:
- several components share an import or spool area;
- a path must exist independently of whether one particular daemon is currently running;
- the platform owns a periodic retention policy;
- the image needs a symlink, ownership rule or other filesystem object;
- an upgrade needs to normalize declared filesystem state.
For example:
# /usr/lib/tmpfiles.d/device-platform.conf
#
# Type Path Mode User Group Age Argument
d /var/lib/device-platform/incoming 2770 root device-import 14d -
This ensures the directory exists, applies the declared ownership and mode, and makes its contents eligible for cleanup when the tmpfiles cleanup operation runs.
The SGID bit in 2770 helps newly created entries inherit the directory group, but it does not by itself guarantee that new files remain group-writable. The creating process’s requested mode and umask still matter. For a real shared-workflow design, test the permissions of files created by every producer, not only the top-level directory.
Read a tmpfiles.d line as a lifecycle contract
Type Path Mode User Group Age Argument
For directory-oriented product configuration, three types cover many practical cases:
| Type | Meaning | Typical use |
|---|---|---|
d | Create the directory if needed, adjust its declared mode/ownership and optionally age-clean its contents | Declared shared or platform-owned directory |
D | Like d, but its contents are also removed when --remove is requested | State explicitly designed to disappear during a remove operation |
e | Operate on an existing directory without creating it; can adjust mode/ownership and clean aged content | Another subsystem creates the directory, tmpfiles owns retention or normalization |
The important word in the Age column is eligible. A rule containing 14d does not mean “delete every file whose modification time is fourteen days old.” tmpfiles evaluates filesystem timestamps according to its aging rules, and recent access or metadata activity may keep an entry from being removed.
Also remember that an age rule is policy, not a continuously running garbage collector. Cleanup happens when systemd-tmpfiles --clean is executed, commonly through systemd-tmpfiles-clean.timer. On a reduced embedded image, verify that the cleanup mechanism you expect is actually enabled.
Retention rules are deletion code
Do not put an age field on a path merely because old files “probably should go away.” Define whether partially processed files, files currently open by another service and data needed for field diagnosis may be removed. Test the rule with realistic timestamps and access patterns.
During development, restrict operations to the intended subtree:
sudo systemd-tmpfiles --create \
--prefix=/var/lib/device-platform
sudo systemd-tmpfiles --clean \
--prefix=/var/lib/device-platform
--prefix= limits processing by path, but it can still match rules from more than one configuration file. Inspect the effective configuration before destructive cleanup. On newer systemd versions that provide --dry-run, use it as another safety layer, but do not assume that option exists on an older embedded target.

sysusers.d gives a static service a declared identity
A unit may contain:
User=device-agent
Group=device-agent
If DynamicUser= is not being used, that account must exist before systemd invokes the process. Instead of hiding account creation in a package shell script, a systemd-oriented product can declare it:
# /usr/lib/sysusers.d/device-agent.conf
#
# Type Name ID GECOS Home Shell
u device-agent - "Device agent service account" - -
A u record creates a system user if it does not already exist and also creates the matching same-name primary group. The - ID asks the system to allocate an appropriate system UID/GID instead of embedding an arbitrary number in this file.
Additional shared groups can be declared explicitly:
# /usr/lib/sysusers.d/device-platform.conf
g device-import -
u device-agent - "Device agent service account" - -
m device-agent device-import
That gives the service a controlled way to participate in a shared filesystem contract without running as root or making a directory world-writable.
A shared group is not automatically a safe protocol
If one process can replace, rename or modify paths while another process consumes them, treat that directory as an IPC and trust boundary. Consider atomic handoff rules, safe file-opening patterns and whether a socket or D-Bus API would make ownership clearer.
Names are not numerical ownership
A filesystem inode stores numerical UID and GID values. The names shown by ls -l are mappings supplied by the account database.
Automatic system-ID allocation is a good default when the account is local to one image and nothing outside that environment depends on its numerical ID. Do not hardcode IDs merely because fixed numbers feel more deterministic.
But persistent data can change the requirement. Ask whether the same data partition must remain meaningful after an A/B image switch, factory reflash, recovery boot, major distribution update or offline maintenance operation.
If several independently built environments must interpret the same numerical ownership, establish a stable UID/GID policy or an explicit migration strategy. Test that policy during the image-update workflow.
sysusers is not a general account migration engine
Do not assume that changing a sysusers.d line will rewrite an already existing account and repair all persistent ownership. Treat identity changes as migrations and test them as such.
Vendor files, runtime policy and local overrides
Both tmpfiles.d and sysusers.d use layered configuration:
/usr/lib/...d/is normally where a package or product image installs its default configuration;/run/...d/provides transient runtime configuration;/etc/...d/is the administrator or product-integration override layer.
The safest override pattern is usually to use the same configuration filename in the higher-priority directory. That file shadows the lower-priority file with the same name.
Do not assume that adding a random 99-local.conf will always override an earlier rule for the same tmpfiles path. Configuration files are also processed in lexicographic order, and conflicting entries have their own ordering rules. Inspect the effective configuration instead of reasoning only from directory precedence.
Do not edit vendor files under /usr/lib on the target
Those files belong to the installed image or package and may be replaced by an update. Put deliberate local policy in the appropriate override layer and keep the reason for the override reviewable.

Putting identity, private state and shared state together
Consider a device agent with four requirements:
- run unprivileged as
device-agent; - expose a Unix socket while running;
- persist its registration database across reboot;
- consume files from a group-controlled import directory whose old unprocessed content may be removed after fourteen days.
1. Declare the identity
# /usr/lib/sysusers.d/device-agent.conf
u device-agent - "Device agent service account" - -
g device-import -
m device-agent device-import
2. Declare independent shared filesystem state
# /usr/lib/tmpfiles.d/device-platform.conf
d /var/lib/device-platform/incoming 2770 root device-import 14d -
3. Declare the private service state
[Service]
Type=exec
User=device-agent
Group=device-agent
RuntimeDirectory=device-agent
RuntimeDirectoryMode=0750
StateDirectory=device-agent
StateDirectoryMode=0750
ExecStart=/usr/bin/device-agent
Restart=on-failure
Now each mechanism has one job:
sysusers.ddeclares the static identity and shared group;tmpfiles.ddeclares a path whose lifetime and cleanup policy are independent of the daemon;- the service unit owns the private runtime and persistent state tied directly to that service.
The daemon no longer needs privileged directory setup at startup. Its socket belongs under /run/device-agent, its private database under /var/lib/device-agent, and the platform-owned import area has a separate contract.
On a conventional systemd boot, static identities must be available before ownership-bearing filesystem setup needs them. When building an offline root filesystem, manufacturing image or custom Yocto integration, preserve the same logical dependency: establish the account database before applying filesystem rules that refer to those accounts.
Immutable images change when sysusers should run
If the deployed root filesystem does not permit runtime changes to the account database, do not rely on first boot magically creating the service identity. Materialize the required users and groups during image construction or provide an explicit writable account mechanism as part of the product design.

DynamicUser= is an alternative identity model, not merely a security checkbox
Systemd can also allocate the service identity dynamically:
[Service]
DynamicUser=yes
StateDirectory=device-agent
CacheDirectory=device-agent
This does not mean persistent state is impossible. When DynamicUser= is combined with managed state, cache and log directories, systemd uses additional protection so recycled dynamic UIDs do not simply give a later service instance access to somebody else’s persistent files.
That makes DynamicUser= attractive when the identity only matters while the service runs and all writable persistent state can remain inside systemd-managed directories.
A static sysusers.d account is still often clearer when:
- another service or offline tool must refer to the identity;
- shared files outside the managed directory model use its UID/GID;
- an external filesystem or recovery environment must interpret ownership;
- the product deliberately exposes a stable service account as part of its integration contract.
The decision is therefore not “static good, dynamic advanced.” It is whether the identity itself is persistent product state.
Permissions are more than one directory mode
A correct owner and a 0750 directory are only part of the access model.
- The daemon’s
UMask=influences newly created files. - An SGID directory can preserve group ownership across producers.
- Default ACLs may be appropriate when simple owner/group bits are insufficient.
- SELinux, SMACK or AppArmor policy can still deny access even when Unix permissions look correct.
- A read-only or overlay filesystem can change what is writable regardless of ownership.
This is why checking only the top-level directory with ls -ld is not enough. Verify the complete path and representative files created by the real service.
Inspect and test the result on the target
Do not stop when the service reaches active. Inspect the effective identity and filesystem contract.
# Does the identity exist?
getent passwd device-agent
id device-agent
# What unit configuration is actually installed?
systemctl cat device-agent.service
# Inspect effective declarative configuration.
systemd-sysusers --cat-config
systemd-tmpfiles --cat-config
# Apply only tmpfiles rules below the product subtree.
sudo systemd-tmpfiles --create \
--prefix=/var/lib/device-platform
namei -l /var/lib/device-platform/incoming
# Start the service and inspect its private runtime state.
sudo systemctl start device-agent.service
namei -l /run/device-agent
namei -l /var/lib/device-agent
# Read service diagnostics from this boot.
journalctl -u device-agent.service -b --no-pager
Then test lifecycle and upgrade behavior:
- Boot a clean image and verify account allocation, directory owners and modes.
- Start the daemon and verify its runtime socket appears in the expected directory.
- Stop it and verify runtime state disappears according to the configured preservation policy.
- Reboot and verify persistent state survives while runtime state is recreated.
- Exercise cleanup with disposable test files whose timestamps and access patterns resemble production.
- Perform an actual software update over populated persistent data and check numerical UID/GID ownership afterward.
- Test shared-directory producers and consumers together, including file modes, incomplete writes and replacement races.
Common mistakes
- Creating standard service directories inside the daemon. Prefer the unit directory settings when the path belongs to that service.
- Assuming a declared directory restricts all other writes. Provisioning and sandboxing are separate concerns.
- Putting runtime state in
/var/libor durable state in/run. Match location to lifetime. - Using
tmpfiles.dfor every private directory. Use it where the filesystem lifecycle is genuinely broader than one unit. - Making shared storage world-writable. Define the trust boundary, ownership protocol and handoff semantics instead.
- Assuming
14dmeans “mtime older than fourteen days.” Test actual tmpfiles aging behavior on the target. - Changing service UIDs without an upgrade plan. Files remember numbers, not names.
- Assuming a sysusers override migrates an existing account. Identity changes require deliberate migration.
- Editing vendor configuration under
/usr/lib. Use the intended override layer. - Testing only a clean image. Most ownership failures appear during upgrade, recovery and long-lived persistent state.
The key idea
Remember the ownership split
Use the service unit for standard directories that belong to one service. Use tmpfiles.d when filesystem state has an independent, shared or cleanup-managed lifecycle. Use sysusers.d when the service needs a static system identity.
That separation makes the product easier to review. An engineer can see which identity runs the daemon, where its private state lives, what survives reboot, which paths are shared and which data the platform may delete.
It also creates a cleaner starting point for hardening. Once legitimate writable state is explicit, the next step is to restrict everything else: filesystem visibility, privileges, capabilities, kernel interfaces and the blast radius of a compromised daemon.
That is where the next article in the series will go.