Skip to content

Backend Implementation Guide

This guide explains how to implement a custom state backend for netherframe. For Terraform backend constructs, see docs/architecture/backend-construct-guide.md.

Strict Requirements

netherframe enforces strict implementation requirements for all backends. There are no default implementations or fallback behavior.

All backends MUST inherit from StateBackend and implement ALL abstract methods. Any attempt to instantiate a backend without all methods implemented will result in a TypeError.

Required Interface

All state backends must inherit from StateBackend and implement the following abstract methods:

Core Methods (Required)

from typing import Any

from nf.core.backends.state_engine import State, StateBackend


class MyCustomBackend(StateBackend):
    def load(self) -> State:
        """Load state from backend storage."""
        return State()

    def save(self, state: State) -> None:
        """Save state to backend storage."""

    def lock(self, info: dict[str, Any]) -> bool:
        """Acquire state lock. Return True if successful."""
        return True

    def unlock(self) -> None:
        """Release state lock."""

Configuration Methods (Required)

These methods are abstract and MUST be implemented:

from typing import Any

from nf.core.backends.state_engine import State, StateBackend


class MyCustomBackend(StateBackend):
    def __init__(self, endpoint: str, bucket: str, key: str) -> None:
        self.endpoint = endpoint
        self.bucket = bucket
        self.key = key

    def get_backend_type(self) -> str:
        """Return the backend type identifier.

        REQUIRED: Must return your registered backend type.
        """
        return "mybackend"  # Your backend's registered type

    def get_config(self) -> dict[str, Any]:
        """Return backend configuration needed to recreate this instance.

        REQUIRED: Must return complete configuration.
        """
        return {
            "endpoint": self.endpoint,
            "bucket": self.bucket,
            "key": self.key,
            # Include all parameters needed for recreation
        }

    # The core methods are required too (see above)
    def load(self) -> State:
        return State()

    def save(self, state: State) -> None:
        pass

    def lock(self, info: dict[str, Any]) -> bool:
        return True

    def unlock(self) -> None:
        pass


backend = MyCustomBackend(endpoint="https://example.invalid", bucket="b", key="k")
assert MyCustomBackend(**backend.get_config()).get_config() == backend.get_config()

These have defaults, but a backend shared by several runs should override them (see State Backend API):

  • save_if_unchanged(state, expected) and conditional_writes = True: write only while the stored state is still the StateVersion (serial, lineage) the writer read, with the storage's own precondition, and raise StateConflictError otherwise. The default writes anyway, with a warning.
  • current_lock(), force_unlock(lock_id) and can_force_unlock = True: report the lock held (with its ID) and release it by its ID when its run crashed.
  • save_checkpoint(name, keep=...) and load_checkpoint(location): keep a copy of the stored state beside it before an apply. The default keeps none, and hybrid execution writes the copy to its output directory instead.

Why These Methods Are Required

The get_backend_type() and get_config() methods are essential for:

  1. State migration tools - Need to recreate backends from configuration
  2. Debugging and logging - Provides clear backend identification
  3. Backend registry - Proper backend identification and factory operations

Example Implementation

import json
from typing import Any

from nf.core.backends.state_engine import State, StateBackend


class GCSStateBackend(StateBackend):
    """Google Cloud Storage state backend."""

    def __init__(self, bucket: str, prefix: str, project: str | None = None) -> None:
        self.bucket = bucket
        self.prefix = prefix
        self.project = project
        self._client = self._create_client()

    def _create_client(self):
        from google.cloud import storage  # imported when a backend is built

        return storage.Client(project=self.project)

    def _get_blob(self, name: str = "terraform.tfstate"):
        return self._client.bucket(self.bucket).blob(f"{self.prefix}/{name}")

    def get_backend_type(self) -> str:
        """Return the registered backend type."""
        return "gcs"  # Matches registration: BackendRegistry.register_state_backend("gcs", GCSStateBackend)

    def get_config(self) -> dict[str, Any]:
        """Return configuration for recreating this backend."""
        config = {
            "bucket": self.bucket,
            "prefix": self.prefix,
        }
        if self.project:
            config["project"] = self.project
        return config

    def load(self) -> State:
        """Load state from GCS."""
        blob = self._get_blob()
        if not blob.exists():
            return State()

        content = blob.download_as_text()
        return State.from_dict(json.loads(content))

    def save(self, state: State) -> None:
        """Save state to GCS."""
        blob = self._get_blob()
        content = json.dumps(state.to_dict(), indent=2)
        blob.upload_from_string(content)

    def lock(self, info: dict[str, Any]) -> bool:
        """Acquire a lock: create the lock object only if it does not exist."""
        from google.api_core.exceptions import PreconditionFailed

        try:
            self._get_blob("terraform.tflock").upload_from_string(json.dumps(info), if_generation_match=0)
        except PreconditionFailed:
            return False
        return True

    def unlock(self) -> None:
        """Release the lock."""
        self._get_blob("terraform.tflock").delete()

Registering Your Backend

Register your backend with the BackendRegistry:

from typing import Any

from nf.core.backends.backend_registry import BackendRegistry
from nf.core.backends.state_engine import State, StateBackend


class GCSStateBackend(StateBackend):
    """The backend from the example above, reduced to what registering needs."""

    def __init__(self, bucket: str, prefix: str, project: str | None = None) -> None:
        self.bucket = bucket
        self.prefix = prefix
        self.project = project

    def get_backend_type(self) -> str:
        return "gcs"

    def get_config(self) -> dict[str, Any]:
        return {"bucket": self.bucket, "prefix": self.prefix}

    def load(self) -> State:
        return State()

    def save(self, state: State) -> None:
        pass

    def lock(self, info: dict[str, Any]) -> bool:
        return True

    def unlock(self) -> None:
        pass


# Register the backend class
BackendRegistry.register_state_backend("gcs", GCSStateBackend)


# Optionally register a factory function for more complex initialization
def create_gcs_backend(config: dict[str, Any]) -> GCSStateBackend:
    # Add validation, defaults, etc.
    return GCSStateBackend(bucket=config["bucket"], prefix=config.get("prefix", "terraform/state"), project=config.get("project"))


BackendRegistry.register_backend_factory("gcs", create_gcs_backend)

Testing Your Backend

Run the shared backend contract (nf.testing.state_backend_contract.StateBackendContract) against your backend, and check that a StateEngine can use it:

from nf.core.backends.state_engine import StateEngine

from typing import Any

from nf.core.backends.state_engine import State, StateBackend


class MemoryBackend(StateBackend):
    """Keeps state in the process: enough to show the required methods."""

    def __init__(self, name: str = "default") -> None:
        self.name = name
        self._state = State()
        self._locked = False

    def get_backend_type(self) -> str:
        return "memory"

    def get_config(self) -> dict[str, Any]:
        return {"name": self.name}

    def load(self) -> State:
        return self._state

    def save(self, state: State) -> None:
        self._state = state

    def lock(self, info: dict[str, Any]) -> bool:
        if self._locked:
            return False
        self._locked = True
        return True

    def unlock(self) -> None:
        self._locked = False


backend = MemoryBackend(name="test")
engine = StateEngine(backend)
state = engine.load_state()