Stop Restarting Services for Backups: Practical cgroup v2 Freezing on Linux
At 02:00 the snapshot job wants a quiet database. The usual options are bad ones: stop PostgreSQL and pay for a cold restart (then hope it comes back), or copy a moving target and hope crash recovery is graceful.
There is a third option that gets skipped because it sounds too easy: freeze the service's cgroup, take the snapshot, thaw it. No restart, no lost in-memory state, no gap in the process's lifetime.
Freezing is not stopping, and it is not SIGSTOP. It is a state bit on a cgroup subtree, exposed by systemd since v246, and it has sharper edges than the one-line command suggests. I spent a morning measuring those edges on Debian 13 (kernel 6.12.118+deb13-amd64, systemd 257.13-1~deb13u1, unified cgroup v2). Everything below is from that box unless marked otherwise.
The short version:
- Freeze stops CPU time for a whole cgroup subtree while keeping memory and sockets; thaw resumes exactly where it left off.
- Freeze is asynchronous.
systemctl freeze && lvcreateis a race; wait forFreezerState=frozenorcgroup.events. -
systemctl stopandrestartare refused while frozen,pscannot see it, and a backup that dies at the wrong moment can leave the unit frozen with nothing in systemd to time it out.
What "frozen" means at the kernel level
Every non-root cgroup in the v2 hierarchy has a cgroup.freeze file. Write 1 and the kernel freezes that cgroup and every descendant cgroup. Write 0 and it unfreezes. The default is 0.
The kernel documentation is explicit about the important parts:
Writing "1" to the file causes freezing of the cgroup and all descendant cgroups. This means that all belonging processes will be stopped and will not run until the cgroup will be explicitly unfrozen. Freezing of the cgroup may take some time; when this action is completed, the "frozen" value in the cgroup.events control file will be updated to "1".
Two consequences follow directly:
- It is asynchronous. The write returns before the cgroup is fully frozen. The completion signal is
frozen 1incgroup.events. - It is hierarchical. A cgroup is frozen if its own bit is set or any ancestor's is. Descendants you create later inherit the freeze, and a process moved into a frozen cgroup stops on arrival.
There is also cgroup.kill, which writes SIGKILL to every process in the subtree. Freeze is the reversible version of that idea; the kernel notes frozen processes can still be killed by a fatal signal, so freeze is not a way to make something unkillable.
This interface landed in Linux 5.2 for cgroup v2. systemd exposes it as systemctl freeze / thaw (added in v246), and only on systems using the unified hierarchy. On a v1 or hybrid setup, the command is not available.
The distinction that matters day to day:
systemctl stop | SIGSTOP | systemctl freeze | |
|---|---|---|---|
| Scope | whole unit cgroup | one process | whole unit cgroup, recursively |
| In-memory state | destroyed | preserved | preserved |
| New TCP connections | refused | accepted, queued | accepted, queued |
ps state | gone | T | S (looks idle) |
| Reversal | start, cold caches | SIGCONT | thaw, resumes mid-instruction |
| Children included | yes | no | yes |
| Fatal signal still works | yes | yes | yes |
What it looks like when you measure it
CPU time stops, exactly
A shell loop incrementing a counter and writing it to a file every 50 ms:
- before freeze: counter at 20
- after two seconds frozen: counter still at 20
-
CPUUsageNSec: 33,448,000 before, 33,536,000 after (the 88-microsecond difference is noise from the freeze/thaw path; the loop itself made no progress)
ps cannot tell you
A busy loop, while :; do :; done, pinned at 100% CPU:
- before:
State: R (running) - frozen:
State: S (sleeping) -
CPUUsageNSec: 630,706,000 at freeze, identical one second later - after thaw:
State: R, CPU time continuing at 1,143,914,000
So a frozen process does not look stopped. It looks asleep. ps, top, and your process exporter will all report a perfectly normal sleeping task that is burning zero CPU. The only reliable signals are FreezerState in systemd or frozen 1 in the cgroup.
Memory is not returned
A Python process holding a 64 MiB bytearray:
-
MemoryCurrentbefore freeze: 71,737,344 bytes - after freeze: 71,737,344 bytes
Freezing is not swapping, not suspension, and not a memory reclaim hint. The pages stay charged to the cgroup. If the service holds 8 GiB, you still need those 8 GiB while it is frozen.
Freeze is fast, but not instant
Three runs freezing a spinning shell, measured from invoking systemctl freeze until frozen 1 appeared in cgroup.events:
- 13 ms, 13 ms, 14 ms
That includes the systemctl process startup. Fast enough to be tempting, slow enough to lose a race on a loaded box. Which is exactly why the naive one-liner is dangerous: it usually works.
Sockets stay open and keep queueing
This is the part that surprises people. A Python process doing nothing but accept() on port 9099, then frozen:
-
exec 3<>/dev/tcp/127.0.0.1/9099succeeded: the TCP handshake completed -
ss -ltnshowedLISTEN 1 8— one connection sitting in the accept queue, backlog 8 - reading a byte from that socket timed out
The kernel completes handshakes and queues connections whether or not the process is scheduled. So a frozen service does not fail fast. Clients connect, wait, and time out. Load balancers that only check "can I open a TCP connection" will keep sending traffic to a process that will not answer until you thaw it. Freeze after draining, or accept that in-flight requests hang for the duration.
The systemd interface (and the one thing not to do)
systemctl freeze accepts unit names, globs, and slices:
systemctl freeze postgresql.service systemctl show -p FreezerState --value postgresql.service # running | freezing | frozen | thawing | frozen-by-parent systemctl thaw postgresql.service For system units this needs root, or a polkit rule that allows the action; user units work with systemctl --user.
FreezerState is the systemd-side view. CanFreeze tells you whether the unit supports it at all: on my box init.scope reports no, which is sensible.
There is no --state=frozen for systemctl list-units. A frozen unit still shows as active running, and systemctl list-units --state=frozen returns nothing. If you want to know what is frozen, ask each unit:
for unit in $(systemctl list-units --type=service --state=active --no-legend --plain | awk '{print $1}'); do state=$(systemctl show -p FreezerState --value "$unit") if [ "$state" != "running" ]; then printf '%-48s %s\n' "$unit" "$state" fi done Two systemctl calls per unit is fine for dozens of units and unpleasant for thousands. Cache it, or query the cgroup tree directly if you are monitoring at that scale.
For scripts, the D-Bus methods avoid shell quoting entirely:
busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \ org.freedesktop.systemd1.Manager FreezeUnit s postgresql.service The one thing not to do: writing cgroup.freeze directly. It works if the cgroup is delegated to you, and the kernel obeys. But systemd keeps its own freezer_state and does not adopt your write. I froze a unit by writing 1 to /sys/fs/cgroup/.../fz-d.service/cgroup.freeze: the kernel reported frozen 1, while systemctl show -p FreezerState still said running. From then on, systemctl thaw and your monitoring disagree with reality. Pick one interface, and for units systemd owns, that interface is systemctl or D-Bus.
A snapshot script that thaws itself
The shape of a safe freeze window is: freeze, wait for the kernel to confirm, flush, snapshot, thaw, verify. The snapshot itself is fast; the copy happens later from the snapshot, never while the service is frozen.
#!/usr/bin/env bash # /usr/local/sbin/snapshot-root.sh set -euo pipefail UNIT="postgresql.service" VG="vg0" LV="root" SNAP_NAME="prebackup-$(date +%Y%m%dT%H%M%S)" SNAP_SIZE="8G" # sized for writes during the snapshot's lifetime FROZEN=0 thaw() { if [ "$FROZEN" -eq 1 ]; then systemctl thaw "$UNIT" || true FROZEN=0 fi } trap thaw EXIT trap 'exit 130' INT TERM HUP systemctl freeze "$UNIT" FROZEN=1 # Freezing is asynchronous: do not snapshot until the kernel confirms. state="" for _ in $(seq 1 100); do state=$(systemctl show -p FreezerState --value "$UNIT") [ "$state" = "frozen" ] && break sleep 0.1 done if [ "$state" != "frozen" ]; then echo "refusing to snapshot: $UNIT is $state" >&2 exit 1 fi sync # push dirty page cache to the block layer before the snapshot lvcreate --size "$SNAP_SIZE" --snapshot --name "$SNAP_NAME" "$VG/$LV" systemctl thaw "$UNIT" FROZEN=0 # Prove it, do not assume it. for _ in $(seq 1 100); do [ "$(systemctl show -p FreezerState --value "$UNIT")" = "running" ] && break sleep 0.05 done if [ "$(systemctl show -p FreezerState --value "$UNIT")" != "running" ]; then echo "WARNING: $UNIT did not thaw" >&2 exit 1 fi echo "snapshot ready: /dev/$VG/$SNAP_NAME" Why each step is there:
- The
trapcovers normal exit, errors, Ctrl-C, and a plainkill. It does not cover SIGKILL or the OOM killer, which is why the systemd unit below adds a second line of defence. - The wait loop turns an asynchronous operation into a precondition. Without it,
lvcreateoccasionally runs against a half-frozen cgroup. -
syncflushes dirty file data and metadata. Persync(2), Linux waits for I/O completions, so this is a real barrier, not a suggestion. -
lvcreatewith-screates a classic snapshot; size it for the write rate over the snapshot's lifetime, not for the origin volume. On a thin pool, omit--sizeand snapshot the thin volume directly:lvcreate -s -n "$SNAP_NAME" "$VG/$LV". - The thaw check loops because thaw is asynchronous too.
thawingis a state, and a script that exits on it will report a false failure.
The freeze window includes everything between systemctl freeze and the thaw, and sync is inside it. On a host with a lot of dirty data, that flush can take seconds. Measure it on your hardware before you promise a sub-second pause.
You do not need fsfreeze here. The fsfreeze(8) man page says it plainly:
fsfreeze is unnecessary for device-mapper devices. The device-mapper (and LVM) automatically freezes a filesystem on the device when a snapshot creation is requested.
That automatic freeze is brief and filesystem-level, which is exactly what a snapshot needs. fsfreeze is for hardware RAID controllers that snapshot a volume without telling the kernel. Stacking both is not "extra safe"; it is two mechanisms with different lifetimes waiting to confuse your recovery.
The unit that runs it, with a belt-and-braces thaw:
[Unit] Description=Consistent root snapshot for backup After=postgresql.service [Service] Type=oneshot ExecStart=/usr/local/sbin/snapshot-root.sh ExecStopPost=-/usr/bin/systemctl thaw postgresql.service TimeoutStartSec=10min Nice=10 IOSchedulingClass=best-effort IOSchedulingPriority=7 ExecStopPost runs after the main process exits for any reason, including a start timeout or SIGKILL. The leading - makes a failed thaw non-fatal. It also runs on success, where the thaw is a harmless no-op because the script already did it.
Five ways it bites
1. systemctl stop and restart are refused while frozen
systemctl stop postgresql.service on a frozen unit prints:
Cannot perform operation on frozen unit postgresql.service. It exits 1. Same for restart, start, and reload. This is not an accident of the CLI: unit_start(), unit_stop(), and unit_reload() in systemd return -EDEADLK when freezer_state != FREEZER_RUNNING (v257 source, still present in v258). The man page says a unit is thawed just before a job runs, but do not build a deployment pipeline on that sentence. Thaw first, then stop.
A direct signal still works. systemctl kill --signal=TERM postgresql.service on a frozen unit succeeded, the unit went inactive, and the freezer returned to running. SIGKILL works too; the kernel documentation says frozen processes remain killable.
The practical failure mode: a deploy or config-management run does systemctl restart, gets a non-zero exit, and the retry loop hammers a unit that cannot be restarted until someone thaws it. Put the thaw in the deploy pre-hook, not in the retry logic.
2. Freeze is hierarchical; thaw is not
Freeze a slice with two services in it:
systemctl freeze batch.slice systemctl show -p FreezerState --value batch.slice # frozen systemctl show -p FreezerState --value batch-worker@1.service # frozen-by-parent Now try to thaw one child:
$ systemctl thaw batch-worker@1.service Failed to thaw unit batch-worker@1.service: Unit is frozen by a parent slice That is correct behaviour, not a bug. The ancestor's bit is still set, so the child stays frozen. You must thaw at the level you froze, or above it: systemctl thaw batch.slice.
The same rule catches people who freeze a whole slice for a consistent multi-service snapshot and then try to bring services back one at a time. It also means freezing a slice freezes every new process started into it, including health-check sidecars and the shell you forgot was running there.
3. There is no freeze timeout
systemd has no FreezeTimeoutSec. Nothing will thaw a unit because it has been frozen too long. If the backup script is SIGKILLed, the node's OOM killer picks it, or the automation platform cancels the job, the target stays frozen: sockets queue, health checks fail, and the service looks "up" to systemd.
The monitoring loop above plus an alert on FreezerState != running for longer than your snapshot window is the minimum. The ExecStopPost thaw is the second line.
There is a nastier variant that I hit while testing, and it is worth knowing before it pages you. I froze a unit whose service had RuntimeMaxSec=3s. When the runtime limit expired, systemd killed the process, and the unit failed. The freezer state did not go with it:
active=failed result=timeout FreezerState=frozen ControlGroup= $ systemctl start ... -> Cannot perform operation on frozen unit $ systemctl thaw ... -> Failed to thaw unit: Unit is not active The cgroup was gone, but systemd's FreezerState still said frozen, so start and thaw both refused. The recovery is to clear the failed state:
systemctl reset-failed postgresql.service systemctl show -p FreezerState --value postgresql.service # running systemctl start postgresql.service That reproduced consistently on systemd 257.13. It looks like a bookkeeping bug when a frozen unit's cgroup disappears without a systemd job, and it may be fixed in a later release, but the lesson generalises: do not freeze units that are close to their RuntimeMaxSec deadline, and put reset-failed in the runbook for "unit is frozen but not active".
4. A process freeze is not a filesystem freeze
Freezing stops your tasks. It does not stop the kernel's writeback threads, which are not in your unit's cgroup, and it does not flush dirty pages. A snapshot taken immediately after systemctl freeze returns can catch dirty pages and an uncheckpointed journal: recoverable on mount, but not the clean image you thought you took.
That is what sync is for. And fsfreeze is for the case where the snapshot is taken below the filesystem, by hardware that does not coordinate with the kernel. For LVM, device-mapper already does the filesystem freeze during lvcreate -s, so adding fsfreeze is redundant.
Freezing also does not make a database internally consistent. It stops new transactions from starting, which is a useful quiesce point, but PostgreSQL's WAL, checkpoints, and your backup tool's start/stop protocol are still what make the backup restorable. If you use pg_basebackup or pg_backup_start(), use those; freeze is for the volume-snapshot path.
5. Direct cgroup writes desync systemd
Already demonstrated above, but it deserves its own line because it is the kind of shortcut that works in a test and fails in production. The kernel will accept your write to cgroup.freeze if the cgroup is delegated. systemd will keep reporting the old state, and its thaw will be a no-op from its point of view. Use systemctl or FreezeUnit, never the file, for units systemd manages.
When freezing is the wrong tool
- Request-serving services without a drain step. Clients connect and hang. If you cannot drain first, a freeze is a latency incident with a fancy name.
- Anything with a hard latency SLO and no queue. Same reason, with money attached.
- Databases using native backup mode. Use the database's protocol. Freeze the volume only when you are deliberately taking a crash-consistent snapshot and have tested recovery.
- Containers.
podman pausealready does this through the container runtime's cgroup, with the runtime's bookkeeping intact. Freezing a unit that wraps the runtime from the outside is the direct-write problem again, one layer up. - cgroup v1 systems. systemd will not offer the command; do not script around it with the v1 freezer files.
A rollout checklist
stat -fc %T /sys/fs/cgroup # expect cgroup2fs systemctl --version | head -1 # 246 or newer for systemctl freeze Then rehearse on a transient unit, not on the database:
systemd-run --user --unit=fz-test sleep 300 systemctl --user freeze fz-test.service systemctl --user show -p FreezerState --value fz-test.service # frozen systemctl --user thaw fz-test.service systemctl --user stop fz-test.service In staging, with the real unit:
- Freeze it, confirm
frozen, and watch your health check go from healthy to timing out. Know how long that takes and whether the load balancer ejects it. - Run the snapshot script end to end and confirm
FreezerState=runningafterwards. - Kill the script with SIGKILL mid-window and confirm your
ExecStopPostthaw or your alert catches it. - Rehearse
reset-failedon a unit that failed while frozen, so the runbook is tested before it is needed. - Alert on any unit whose
FreezerStateis notrunningfor longer than the snapshot window.
Freezing is a good primitive: cheaper than a restart, more precise than a stop, reversible in a way that SIGSTOP is not. It is also a kernel state with no timeout, invisible to ps, and guarded by systemd semantics that will refuse your cleanup commands. Treat it like a lock: short hold times, always released, and monitored.
Sources
- Linux kernel documentation, cgroup v2:
cgroup.freeze,cgroup.events,cgroup.kill, hierarchical freeze — https://docs.kernel.org/admin-guide/cgroup-v2.html -
systemctl(1), systemd 257:freeze/thaw, added in v246, unified hierarchy only, automatic thaw note — https://man7.org/linux/man-pages/man1/systemctl.1.html - systemd source,
src/core/unit.c(v257):unit_start(),unit_stop(),unit_reload()return-EDEADLKwhile frozen — https://github.com/systemd/systemd/blob/v257/src/core/unit.c -
org.freedesktop.systemd1(5):FreezeUnit,ThawUnit,FreezerState,CanFreeze— https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.systemd1.html -
fsfreeze(8): filesystem freeze semantics; automatic freeze by device-mapper/LVM during snapshot — https://man7.org/linux/man-pages/man8/fsfreeze.8.html -
sync(2): Linux waits for I/O completions — https://man7.org/linux/man-pages/man2/sync.2.html -
lvcreate(8): snapshot options — https://man7.org/linux/man-pages/man8/lvcreate.8.html - Linux 5.2 changelog: freezer controller for cgroups v2 — https://kernelnewbies.org/Linux_5.2
-
podman-pause(1): pausing all processes in a container — https://docs.podman.io/en/latest/markdown/podman-pause.1.html
Measured on Debian 13, kernel 6.12.118+deb13-amd64, systemd 257.13-1~deb13u1, cgroup v2 unified, on an idle host. Your latencies will differ; the semantics should not.