State Backend API (Advanced)
This guide is for advanced users and backend authors who need to configure state engines directly or build custom backends.
Quick Start
Use the typed backend enum plus config dataclasses with StateEngine:
from nf.core.backends.state_engine import (
BackendType,
LocalBackendConfig,
StateEngine,
)
engine = StateEngine(
BackendType.LOCAL,
LocalBackendConfig(path=".nf.out/docs-state-backend-api.tfstate"),
)
This is the simplest direct API: pick a backend type and pass the matching config object.
Backend Selection
Use BackendType to select a built-in backend:
BackendType.LOCALBackendType.S3BackendType.POSTGRESQL
Each built-in backend has a structured config:
LocalBackendConfig(path=...)S3BackendConfig(bucket=..., key=..., region=..., ...)PostgreSQLBackendConfig(host=..., database=..., username=..., ...)
Passing a Backend Instance
If you already have a StateBackend instance, pass it directly instead of going
through BackendType plus config.
from nf.core.backends.state_engine import State, StateBackend, StateEngine
class MemoryBackend(StateBackend):
def __init__(self) -> None:
self._state = State()
self._locked = False
def load(self) -> State:
return self._state
def save(self, state: State) -> None:
self._state = state
def lock(self, info: dict[str, object]) -> bool:
if self._locked:
return False
self._locked = True
return True
def unlock(self) -> None:
self._locked = False
def get_backend_type(self) -> str:
return "memory"
def get_config(self) -> dict[str, object]:
return {"kind": "memory"}
engine = StateEngine(MemoryBackend())
This is the right path for custom in-memory, test, or plugin-provided backends.
Hybrid Execution Integration
HybridExecutionMode uses the same typed backend inputs:
from nf.core import App
from nf.core.backends.state_engine import BackendType, LocalBackendConfig
app = App()
hybrid = app.enable_hybrid_execution(
state_backend=BackendType.LOCAL,
state_backend_config=LocalBackendConfig(path=".nf.out/docs-hybrid.tfstate"),
)
If you already have a backend instance, you can pass that instead of a
BackendType.
Custom Backends
For reusable backends, implement StateBackend and register the class with
BackendRegistry.
from nf.core.backends.backend_registry import BackendRegistry
from nf.core.backends.state_engine import State, StateBackend, StateEngine
class MemoryBackend(StateBackend):
def __init__(self) -> None:
self._state = State()
def load(self) -> State:
return self._state
def save(self, state: State) -> None:
self._state = state
def lock(self, info: dict[str, object]) -> bool:
return True
def unlock(self) -> None:
return None
def get_backend_type(self) -> str:
return "memory"
def get_config(self) -> dict[str, object]:
return {"kind": "memory"}
BackendRegistry.register_state_backend("memory", MemoryBackend, "docs.example")
engine = StateEngine(MemoryBackend())
If your backend also has a construct/configuration surface, register the
matching backend construct separately via
BackendRegistry.register_backend_construct(...).
Backends that store the whole state as one document (a blob, an object, a
key/value entry) can extend nf.core.backends.document_state_backend.DocumentStateBackend
instead and only implement _read_document(), _write_document() and
_state_location(); it provides load, save, save_if_unchanged,
read_state and write_state. _read_document() returns the stored document
with its storage's version token (an ETag, a generation, a modify index; ABSENT
when there is none), and _write_document(data, if_token) writes only while the
stored document is still that version, raising DocumentChangedError otherwise.
The S3, Azure, GCS and Consul backends are built this way; implementing the
_checkpoint_* methods too gives them checkpoints.
Serial, Lineage and Conditional Writes
As Terraform's, a stored State has a lineage, set by its first write and kept
by every later one, and a serial that every write increases (StateVersion).
State written before they existed loads with serial 0 and no lineage.
A resource's entry (ResourceState) may also hold what its provider keeps beside its
state, as Terraform's resource instances do: its private data (private, bytes, written as
base64) and its identity (identity, with identity_schema_version). Each is written only
when the entry has it, so a backend stores them as part of the state document with nothing
to do, and state written before they existed loads without them.
The engine remembers the version it last read or wrote, and writes the next
serial with backend.save_if_unchanged(state, expected). A backend refuses the
write with StateConflictError when the stored state is no longer expected: a
run whose lock lapsed or was taken over (or that wrote without it) cannot
overwrite what another run stored. Check and write in one step with what the
storage offers, and set conditional_writes = True:
| Backend | Precondition |
|---|---|
| Local file | Compared and written while holding the lock (the run's, or one taken for the write): the flock, or without one (Windows) the lock file |
| S3 | Conditional put: If-Match on the ETag, If-None-Match: * for a new object |
| GCS | if_generation_match (0 for a new object) |
| Azure Storage | ETag match (MatchConditions.IfNotModified); a write the lease refuses is a StateLockError |
| Consul | Check-and-set on the key's ModifyIndex (cas=0 for a new key) |
| PostgreSQL | The state row locked FOR UPDATE while compared and written |
| HCP Terraform | Compared and uploaded while holding the workspace lock, which a state version needs |
A backend that cannot keeps the StateBackend default: it writes anyway and logs
a warning. save() stays an unconditional write, for tools that replace state
on purpose (state migration).
Recording State Changes
State changes go through the engine, which applies them to its state on one writer (the thread that opened the batch: the event loop's thread during an apply) and persists them:
from nf.core.backends.state_engine import BackendType, LocalBackendConfig, ResourceState, StateEngine
engine = StateEngine(BackendType.LOCAL, LocalBackendConfig(path=".nf.out/docs-records.tfstate"))
bucket = ResourceState(type="aws_s3_bucket", id="logs", provider="aws", attributes={"bucket": "logs"}, stack_id="main")
engine.record_resource(bucket) # written at once
with engine.batched_saves(): # written every state_persist_interval seconds, and at the end
engine.record_removal("main.aws_s3_bucket.logs")
engine.record_output("main.output.bucket", {"value": "logs", "sensitive": False})
record_resource and record_removal change a resource's or data source's
entry by address, record_output and record_output_removal an output's (keyed
<stack>.output.<name>), and save_state replaces the whole state. A record
that changes nothing writes nothing. Inside batched_saves() a background
thread writes pending changes every state_persist_interval seconds (20 by
default; nf --state-persist-interval or [tool.nf.config]), whether or not anything else happens, so a hard kill loses at most one
interval; the rest is written when the block exits, including on errors. When
the changes cannot be stored at the end they are written to the engine's
errored_state_path (hybrid execution: <outdir>/errored.tfstate) and stay
recorded: later records build on them, a later write stores them all, and a
second failure rewrites the file with every unsaved change. Taking the lock again
drops them from memory (the file holds them). When they cannot be stored because another run stored
state meanwhile, the engine records nothing more until it takes the lock again
(lost_to_another_run). A write whose answer was lost, but which was stored,
is recognized as the engine's own. load_state() is for readers.
Locks and Force-Unlock
The engine gives every lock an ID. A backend reports the lock held, with its
ID, from current_lock(), and force_unlock(lock_id) releases that lock and no
other (set can_force_unlock = True). When the engine cannot take the lock it
logs who holds it and the command that releases it:
nf state force-unlock 3f0c2a5e-8b1f-4c1e-9d5a-2b7e1f0c9a44 --app my-app
A local flock cannot be forced open: only its process can release it, and the
kernel does when that process exits, however it exits.
Checkpoints
Before an apply (with the CHECKPOINT recovery strategy) hybrid execution asks
the backend to keep a copy of the stored state: save_checkpoint(name, keep=5)
returns where the copy is, and load_checkpoint(location) reads it back for
restore_checkpoint(). Document backends keep it as
<state>.checkpoints/<name> beside the state, PostgreSQL as a row of its own,
and HCP Terraform, which keeps every state version, points at the current one. A
backend that keeps none returns None, and the checkpoint is written to
<outdir>/checkpoints/ instead.
Backend Contract Tests
nf.testing.state_backend_contract.StateBackendContract is a reusable
test suite every backend should pass. It checks that missing state loads as an
empty State, that saved state round-trips with its serial and lineage, that a
second instance cannot take a held lock, that unlock() without holding the
lock leaves the holder's lock alone, that the holder can keep writing, that
expiring locks are renewed while held, that a conditional write replaces only
the version it expects (a writer that read before another run wrote, holder of
a lock that was taken over included, is refused), that force_unlock releases
the lock it names and no other, and that checkpoints keep the state as it was.
Subclass it and provide a factory that returns a new backend instance over the
same storage on every call:
import pytest
from nf.testing.state_backend_contract import BackendFactory, StateBackendContract
class TestMemoryBackendContract(StateBackendContract):
# Set this when locks lapse unless renewed (leases, sessions, heartbeats),
# and shorten the backend's renewal interval in the factory to match.
lock_expiry_seconds = None
@pytest.fixture
def backend_factory(self) -> BackendFactory:
storage = SharedMemoryStorage()
return lambda: MemoryBackend(storage)
The built-in backends run it against in-memory fakes of their SDKs (see
test_*_contract.py in each backends/*/tests package), S3 against FakeCloud
too, and PostgreSQL against a real database with pytest --nf-use-containers.
Testing Tips
- Prefer enums and config dataclasses over strings and raw dicts.
- Use
BackendType.LOCALin fast tests unless the backend behavior itself is what you are testing. - For custom backend tests, pass the backend instance directly so the test only depends on the code under test.