#Persistence Ops Runbook
Version: 0.51.0 Updated: 2026-11-22 Applies to: ranvier-runtime Category: Guides
#1. Adapter Selection Guide
Choose the adapter that matches your durability, latency, and infrastructure requirements.
| Criterion | InMemoryPersistenceStore |
PostgresPersistenceStore |
RedisPersistenceStore |
|---|---|---|---|
| Durability | None (process-scoped) | Committed database rows; checkpoint state and event append commit in one transaction | Depends on an operator-configured Redis RDB/AOF policy; not implied by the adapter |
| Checkpoint latency | Deployment-dependent; benchmark locally | Deployment- and pool-dependent | Deployment- and network-dependent |
| Resume after process crash | No | Yes, from a committed non-terminal checkpoint | Conditional on Redis persistence and failover policy; not verified by the default fixture |
| Multi-process access | No (node-local) | Shared database | Shared Redis service |
| Best for | unit tests, local dev | production workflows | high-throughput, ephemeral checkpoints |
| Feature flag | none | persistence-postgres |
persistence-redis |
#Decision tree
graph TD
Q1{"Need to survive\nprocess restart?"} -->|No| MEM["InMemoryPersistenceStore\n(tests only)"]
Q1 -->|Yes| Q2{"Need strong durability?\n(audit trail, compensation log)"}
Q2 -->|Yes| PG1["PostgresPersistenceStore"]
Q2 -->|No| Q3{"Need sub-millisecond\ncheckpoint latency?"}
Q3 -->|Yes| RED["RedisPersistenceStore"]
Q3 -->|No| PG2["PostgresPersistenceStore\n(default-safe choice)"]#PostgreSQL setup
# Cargo.toml
[features]
persistence-postgres = ["ranvier-runtime/persistence-postgres"]let pool = sqlx::PgPool::connect(&env::var("DATABASE_URL")?).await?;
let store = PostgresPersistenceStore::new(pool.clone());
store.ensure_schema().await?; // idempotent -- call once at startupensure_schema() checks the store format (see "Store format and version 1
data" below), creates the tables that are absent, and records the format on a
new store. Concurrent calls are serialized. It does not add columns to existing
tables or migrate stored data.
#Redis setup
[features]
persistence-redis = ["ranvier-runtime/persistence-redis"]let store = RedisPersistenceStore::connect(&env::var("REDIS_URL")?).await?;
store.ensure_schema().await?; // checks the store format -- call once at startup#Store format and version 1 data
Version 1 data (Ranvier 0.51.x and earlier) is not supported and is never migrated. Start on a new or emptied store, or use a new table or key prefix.
Each store records its format once, outside the versioned tables and keys: the
PostgreSQL table {prefix}_format (one row) and the Redis key
{prefix}:format. ensure_schema() checks it at startup. Without that call,
each store instance runs the same check before its first operation; PostgreSQL
then requires the marker to exist already. A failed check writes nothing and
returns StoreFormatError inside the anyhow::Error; inspect it with
error.downcast_ref::<StoreFormatError>().
StoreFormatError |
Meaning | Operator action |
|---|---|---|
LegacyData { location } |
Version 1 data at location: rows in the PostgreSQL tables {prefix}_state, {prefix}_events or {prefix}_interventions, or Redis keys {prefix}:{trace_id} outside {prefix}:v2: |
Point the application at a new prefix, or back up and remove the version 1 data, then start again |
UnsupportedVersion { found } |
The marker names another format; a later Ranvier version initialized the store | Run that version, or start this version on a new store. Do not edit the marker |
NotInitialized |
A PostgreSQL store without a marker, and the operation does not create one | Call ensure_schema() at startup |
A store that holds version 2 data but no marker (written by builds before the
marker existed) is accepted: ensure_schema() records the marker.
Downgrades:
- A store initialized with a later format is refused (
UnsupportedVersion). - Ranvier 0.51.x reads neither the marker nor the version 2 tables and keys.
Run against a version 2 store, it neither sees nor changes version 2 traces,
and what it writes is version 1 data. After upgrading back, PostgreSQL
refuses to start (
LegacyData), because the version 1 tables are checked on every start. Redis looks for version 1 keys only while the store has no marker, because the scan walks the whole keyspace; keys written during the downgrade are not detected and stay invisible. Before upgrading back on Redis, list them and remove them after backing them up:redis-cli --scan --pattern 'ranvier:persistence:*' | grep -v -e '^ranvier:persistence:v2:' -e '^ranvier:persistence:format$'(use your prefix). - Do not run different Ranvier versions against one store at the same time. A running store instance does not notice a marker changed by another binary.
Supported servers: PostgreSQL 16 or later and single-node Redis 7.4 or later. The live suites run on PostgreSQL 16.16 and Redis 7.4.12. The runtime does not check the server version. Redis Cluster, Sentinel and other Redis-compatible servers are not claimed.
#Concurrent writers and conflicts
Several processes may run the same trace. Every built-in store write is conditional on the trace's revision (its event count): an append must carry the next event_sequence, a completion needs the terminal event and never replaces a different completion, and an intervention must name the revision it was decided on (Intervention::expected_event_sequence). A losing write leaves the trace unchanged and returns PersistenceConflict inside the anyhow::Error; inspect it with error.downcast_ref::<PersistenceConflict>(). Writes are never retried automatically.
PersistenceConflictKind |
Meaning | Operator action |
|---|---|---|
StaleRevision |
Another writer advanced the trace first | Reload the trace and decide again; do not resend the same write |
ConcurrentUpdate |
Redis compare-and-set lost to another write | Same as StaleRevision |
Terminal, Completed |
The trace already ended | Nothing to resume; investigate why a writer still targeted it |
InterventionExists |
Another intervention is bound to this revision | Review the stored intervention instead of adding a second one |
How executions report a conflict: a conflict before an effect is BlockedBeforeEffect (nothing ran); a writer that finds another writer's open intent is blocked with PendingIntent; a conflict after an effect is Unconfirmed with MayHaveRun and needs reconciliation. Effects are not fenced: the runtime does not undo the effect of a writer that lost after running it.
An intervention applies only while the trace is still at its revision. The run that applies it appends events, so it runs once. An intervention saved and then overtaken by another writer's append stays in the trace but is never applied; issue a new one against the current revision.
The PostgreSQL and single-node Redis adapters provide these guarantees across processes, and InMemoryPersistenceStore within one process. Custom stores must implement the same conditional writes; the runtime does not verify them. Redis Cluster/Sentinel, cross-host ownership, failover and exactly-once execution are not claimed.
#Redis concurrent writes and corrupt records
Redis trace mutations compare the original JSON bytes and replace the value in one atomic Lua operation. A stale snapshot returns concurrent persistence update and preserves the winning value. The adapter does not retry or merge automatically. Reloading alone does not make repeating a business side effect safe; caller retry and required-persistence policy remain release decisions.
A stored trace ID that differs from the requested key is rejected before reads or mutations succeed. Quarantine and investigate the record; do not redirect it into another trace. Transport errors can still leave commit outcome unknown. Atomic replacement does not establish RDB/AOF durability, failover safety, or exactly-once execution.
Local regression evidence is retained in the repository's M427 Redis stale-write evidence packet. It does not replace deployment-specific recovery validation.
#2. Failure Recovery and Reconciliation
#How executions report failures
Axon::execute and execute_cancellable return an ExecutionReport. It says
whether the store confirmed the history, not only what the domain returned.
| Report | Meaning | Action |
|---|---|---|
Recorded, NotRequested |
History confirmed (completion recorded, or not requested) | None |
Unpersisted |
No trace store configured | None; nothing can be reconciled |
BlockedBeforeEffect { operation, effect: NotInvoked } |
A write or check failed before any effect ran | Fix the cause (store outage, invalid history), then run the same trace again |
Unconfirmed { operation, effect: MayHaveRun } |
An effect may have run and its history is not confirmed | Reconcile the trace (below) before anything else |
operation names the step that failed: Load, Intent, Result,
Terminal, Complete, PendingIntent (an earlier effect has no result),
CompensationRead, CompensationWrite, CompensationEvent,
RecoveryPayload, ResumeInput, UnsupportedFormat.
The runtime never retries an unconfirmed write or an effect that may have run.
Once an execution is Unconfirmed it stops: no DLQ delivery, no compensation,
no terminal event and no completion. This includes:
- a
then_with_timeouttimeout while the effect runs (Unconfirmed { Result }); - a lost acknowledgement of any write;
- cancellation while an effect runs (the next run reports
PendingIntent); - a cleanup budget that closes while a compensation handler runs.
The runtime cannot know whether an external effect committed. Exactly-once execution is not provided; an effect that may run twice must be idempotent in the external system.
#Scenario A: Process crash mid-workflow
After the restart, run the same Axon with the same PersistenceTraceId and
the same input. The runtime loads the trace, checks that the input matches the
recorded input, and continues after the last recorded result with the stored
checkpoint. Do not call store.resume() or choose a cursor by hand.
If the process stopped while an effect ran, the trace has an open intent and
the run is blocked with PendingIntent. Reconcile it.
#Scenario B: Store unavailable
A failed write before the effect is BlockedBeforeEffect: nothing ran. Run the
same trace again when the store is back. A failed write after the effect is
Unconfirmed: reconcile it. The adapters do not export failure counters; count
the reports and alert on Unconfirmed.
#Scenario C: Ambiguous write (lost acknowledgement)
A write that timed out may have committed. Never resend it and never treat a duplicate-sequence error as success. Load the trace and classify it.
#Scenario D: Verified outage and process recovery
From the ranvier/ checkout, run the opt-in Podman harness:
.\scripts\dependency_failure_smoke_podman.ps1The M419-RQ8 fixture actually stops and restarts PostgreSQL 16 and Redis 7. It proves that one existing PostgreSQL store/pool and one existing Redis store/ connection manager recover within a bounded retry window. A separate process loads a committed PostgreSQL checkpoint and compensation-idempotency marker, derives the next cursor, and confirms that a completed trace rejects ordinary resume.
The fixture does not prove Redis durability. It also does not make the external compensation side effect and the local idempotency marker atomic; handlers remain at-least-once around that crash window and must be idempotent.
#Reconciling an unconfirmed execution
Load the trace and classify it:
let trace = store.load(trace_id).await?.expect("trace exists"); match trace.reconciliation() { TraceReconciliation::PendingIntent { step, node_id, .. } => { /* check the effect */ } other => { /* see the table */ } }Act on the state:
TraceReconciliationProcedure OpenNothing is pending. Run the same trace again PendingIntenton a business nodeCheck in the external system whether the effect ran, then procedure 1, 2 or 3 PendingIntentonexternal-compensationCheck whether the compensation ran, then procedure 5 TerminalWithoutCompletionProcedure 4 Completed(_)Nothing to do; a completed trace never runs again CompletedWithoutTerminal,InvalidNot repairable by appending events. Keep the record for investigation and start a new trace
Operator writes use the next event sequence of the trace you loaded:
fn operator_event(
trace: &PersistedTrace,
event_type: PersistenceEventType,
step: u64,
node_id: Option<String>,
outcome_kind: &str,
payload: Option<serde_json::Value>,
) -> PersistenceEnvelope {
let first = &trace.events[0];
PersistenceEnvelope {
trace_id: trace.trace_id.clone(),
circuit: first.circuit.clone(),
schematic_version: first.schematic_version.clone(),
event_sequence: trace.events.len() as u64,
event_type,
step,
node_id,
outcome_kind: outcome_kind.to_string(),
timestamp_ms: now_ms(),
payload_hash: None,
payload,
}
}Procedure 1, the effect ran. Record its result, then run the same trace again. The execution continues after the effect without repeating it.
let result = serde_json::to_value(Outcome::<Charged, MyError>::Next(charged))?;
store.append(operator_event(&trace, PersistenceEventType::Result, step,
node_id.clone(), "Next", Some(result))).await?;Procedure 2, the effect did not run and must run. Close the intent with a
Fault result, then save a jump bound to the new revision. The next run of the
same trace runs the node again with payload_override as its input. Address
the node by its label: stored node_id values are generated per Axon instance
and do not survive a restart, while step is the node's index in the schematic.
let closed = serde_json::to_value(Outcome::<Charged, MyError>::Fault(reason))?;
store.append(operator_event(&trace, PersistenceEventType::Result, step,
node_id.clone(), "Fault", Some(closed))).await?;
let trace = store.load(trace_id).await?.expect("trace exists");
store.save_intervention(trace_id, Intervention {
target_node: axon.schematic.nodes[step as usize].label.clone(),
payload_override: Some(node_input),
timestamp_ms: now_ms(),
expected_event_sequence: trace.events.len() as u64,
}).await?;Procedure 3, give the execution up. Close the intent with a Fault
result, write a terminal event and complete the trace as Fault.
store.append(operator_event(&trace, PersistenceEventType::Result, step,
node_id, "Fault", Some(fault.clone()))).await?;
let trace = store.load(trace_id).await?.expect("trace exists");
store.append(operator_event(&trace, PersistenceEventType::Terminal, step + 1,
None, "Fault", Some(fault))).await?;
store.complete(trace_id, CompletionState::Fault).await?;Procedure 4, completion unknown. The terminal event is recorded. Call
complete with the state that matches it: terminal kind Next is Success,
Fault is Fault (or Compensated when a Compensated event precedes it),
Cancelled is Cancelled (or Compensated after compensation).
Procedure 5, compensation result unknown. Check the external system. If
the compensation did not run, run it yourself. Then record it, write the
terminal event with the original fault payload, and complete the trace as
Compensated:
store.append(operator_event(&trace, PersistenceEventType::Compensation, step,
Some("external-compensation".into()), "Compensated",
Some(serde_json::json!({"outcome": "completed"})))).await?;
let trace = store.load(trace_id).await?.expect("trace exists");
store.append(operator_event(&trace, PersistenceEventType::Terminal, step + 1,
None, "Fault", fault_payload)).await?;
store.complete(trace_id, CompletionState::Compensated).await?;Every operator write is conditional on the revision you loaded. If another
writer or operator changed the trace first, the write fails with
PersistenceConflict and changes nothing: reload and decide again.
These procedures run as tests on InMemory, PostgreSQL and Redis
(runtime/tests/reconciliation.rs).
#Cleanup budget, timeouts and shutdown
- Insert
CleanupBudget(duration)into the Bus to bound Saga rollback, external compensation and cancellation cleanup of one execution, retries and backoff included. When it closes, the running handler is dropped (SagaRollbackOutcome::InProgress), the compensation intent stays open and the execution isUnconfirmed. Without it cleanup is unbounded. The budget does not cancel the external effect. then_with_timeoutbounds one transition. A timeout before the effect's intent is acknowledged blocks before the effect; a timeout while the effect runs isUnconfirmed { Result }.- HTTP:
run_managedcancels in-flight executions withOperatorShutdownso their cleanup runs, then aborts what is left atgraceful_shutdown_timeout. KeepCleanupBudgetshorter than that timeout. The compatibilityrundrops in-flight executions at the timeout without cleanup.
#SSE streams held for recovery review
An SSE stream whose Saga compensation did not finish, or whose stream end
record was not acknowledged, is held by the HTTP ingress instead of being
released. It keeps one custody slot (managed_task_capacity); when the slots
are full, new streams get 503 with stream_recovery_capacity_exhausted
before any callback runs.
- Register
HttpIngress::on_stream_retainedto receive each held stream (RetainedStream: method, path and a recovery handle). Without it, held streams are logged at warn level ("SSE stream retained for recovery review"). - Check
report.assessment()andreport.stream_end_durability(). An unconfirmed end record is reconciled in the trace store (see "Reconciling an unconfirmed execution"); it never becomes releasable in memory. - Run
report.reconcile_next_local_compensation_untiluntil it returnsRecoveryBlocked. Each call runs at most one compensation, in LIFO order, including compensation retained by an owned nested child. A failed compensation stays failed: reconcile its effect outside Ranvier. - Call
report.release_settled_until. It succeeds only when every row was settled; the custody slot is then free.
Shutdown reports streams_retained (finished, still held) and
streams_unsettled (not finished by the deadline) in HttpTaskDrainReport.
Held streams are in memory only. After a restart, the stream's trace
(StreamCompleted, StreamCancelled, StreamAbandoned, ... or an open
Intent) is the record to reconcile.
#Retries
DlqPolicy::RetryThenDlqruns every attempt under one intent and records only the final result; intermediate faults are not journaled.then_with_retryrecords each attempt as its own intent and result.- Neither retries after an unconfirmed write.
CompensationRetryPolicyretries the hook with the same idempotency key. A hook that succeeded is not retried when its marker write fails. The cleanup budget covers all attempts.- A retry budget is an attempt count and backoff. To bound total time, wrap the
transition in
then_with_timeout.
#3. Checkpoint Retention Policies
#PostgreSQL -- TTL-based purge
The adapter does not expose general trace TTL or a completed_at column.
Delete child rows before state rows and derive age from the latest persisted
event. Review this example against your table prefix, backup policy, and query
plan before scheduling it:
BEGIN;
CREATE TEMP TABLE expired_ranvier_traces ON COMMIT DROP AS
SELECT state.trace_id
FROM ranvier_persistence_v2_state AS state
JOIN (
SELECT trace_id, MAX(timestamp_ms) AS latest_event_ms
FROM ranvier_persistence_v2_events
GROUP BY trace_id
) AS event_age USING (trace_id)
WHERE state.completion IS NOT NULL
AND event_age.latest_event_ms <
EXTRACT(EPOCH FROM (NOW() - INTERVAL '30 days')) * 1000;
DELETE FROM ranvier_persistence_v2_interventions
WHERE trace_id IN (SELECT trace_id FROM expired_ranvier_traces);
DELETE FROM ranvier_persistence_v2_events
WHERE trace_id IN (SELECT trace_id FROM expired_ranvier_traces);
DELETE FROM ranvier_persistence_v2_state
WHERE trace_id IN (SELECT trace_id FROM expired_ranvier_traces);
COMMIT;Alternatively, use the built-in purge method for compensation idempotency:
let cutoff_ms = (Utc::now() - Duration::days(30)).timestamp_millis();
let purged = idempotency_store.purge_older_than_ms(cutoff_ms).await?;
tracing::info!(purged_rows = purged, "idempotency cleanup complete");#Redis checkpoint retention
RedisPersistenceStore does not currently expose a checkpoint TTL builder.
with_prefix_and_ttl belongs to the compensation-idempotency store, not the
trace store. If checkpoint expiry is mandatory, apply and test a separate
Redis lifecycle policy or use PostgreSQL until a typed trace-retention API is
available. Never infer trace durability or retention from the idempotency-key
TTL.
#Recommended retention windows
| Environment | Retention | Rationale |
|---|---|---|
| dev / staging | 7 days | Debugging window |
| prod (standard) | 30 days | Audit + replay window |
| prod (regulated) | Policy-defined | Legal/compliance review; no universal framework default |
#4. Scaling Considerations
#High-concurrency checkpointing (PostgreSQL)
Pool sizing:
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(20) // match your DB max_connections / expected concurrency
.min_connections(5) // keep warm connections ready
.acquire_timeout(Duration::from_secs(3))
.connect(&database_url).await?;Partitioning (very high throughput):
For services with >10,000 checkpoints/second, partition the ranvier_persistence_v2_events table by trace_id hash:
-- Partition events table into 16 buckets
CREATE TABLE ranvier_persistence_v2_events (
trace_id TEXT NOT NULL,
...
) PARTITION BY HASH (trace_id);
CREATE TABLE ranvier_persistence_v2_events_0
PARTITION OF ranvier_persistence_v2_events
FOR VALUES WITH (MODULUS 16, REMAINDER 0);
-- ... repeat for 1..15#Redis topology
The built-in adapter uses redis::aio::ConnectionManager with a single Redis
client URL. M419-RQ8 verifies reconnect to a restarted single-node fixture; it
does not certify Redis Cluster, Sentinel failover, replica consistency, or
cross-region recovery. Validate those topologies with a dedicated adapter and
failure plan before production use.
#5. Backup and Restore
#Durability settings and recovery point
A store call that returned Ok (append, complete, save_intervention) is an
acknowledged write. Whether it survives a failure depends on the server
configuration, which Ranvier does not check:
| Situation | Required server settings | Acknowledged writes lost |
|---|---|---|
| PostgreSQL restart or server process crash | fsync = on, full_page_writes = on, synchronous_commit not off (the defaults) |
None |
| Redis restart or server process crash | appendonly yes, appendfsync always |
None |
Redis with appendfsync everysec (the Redis default) |
-- | Up to about the last second on a server crash or power loss |
| Redis with RDB snapshots only | -- | Everything since the last snapshot |
| Restore from a backup | -- | Everything written after the backup; Ranvier does not provide point-in-time recovery |
| Host power loss, storage failure or corruption | -- | Not claimed |
The first two rows are verified by restart, server-kill and restore tests on PostgreSQL 16 and Redis 7.4. Recovery time depends on your data size and tooling; Ranvier does not claim a recovery-time objective.
#PostgreSQL
Backup:
# Full dump (for small databases)
pg_dump -U postgres -d mydb -t 'ranvier_persistence_*' \
--format=custom -f ranvier_persistence_$(date +%Y%m%d).dump
# Continuous WAL archiving (for production)
# Configure postgresql.conf:
# wal_level = replica
# archive_mode = on
# archive_command = 'cp %p /mnt/backup/wal/%f'Restore:
# Restore from dump
pg_restore -U postgres -d mydb ranvier_persistence_20260226.dump
# Verify row counts after restore
psql -U postgres -d mydb -c \
"SELECT COUNT(*) FROM ranvier_persistence_v2_state WHERE completion IS NOT NULL;"#Redis
Backup (RDB snapshot):
# Trigger immediate save
redis-cli BGSAVE
# Copy the dump file
cp /var/lib/redis/dump.rdb /mnt/backup/redis_$(date +%Y%m%d).rdbRestore:
# Stop Redis, replace dump.rdb, restart
systemctl stop redis
cp /mnt/backup/redis_20260226.rdb /var/lib/redis/dump.rdb
systemctl start redisKey health check after restore:
# Verify persistence keys exist
redis-cli --scan --pattern "ranvier:persistence:*" | wc -l#After restoring a backup
A backup includes the store format marker ({prefix}_format,
{prefix}:format); the first ensure_schema() checks it like any other start.
A backup that holds version 1 data is refused with StoreFormatError::LegacyData
(see "Store format and version 1 data").
Restoring rolls every trace back to its state at backup time. Effects that ran after the backup left no record in the restored store, so resuming such a trace can run those effects again. Before resuming executions from a restored store:
- List the traces without a completion: PostgreSQL
SELECT trace_id FROM {prefix}_v2_state WHERE completion IS NULL; Redisredis-cli --scan --pattern '{prefix}:v2:*'and check each trace. - Classify each one with
PersistedTrace::reconciliation(). - For traces that are
Open,PendingIntentorTerminalWithoutCompletion, check the external systems and apply the reconciliation procedures in section 2 (record the result, jump past the effect, or abandon).
There is no trace listing API; use the queries above or the trace ids your application records.
#6. See Also
- `docs/manual/04_PERSISTENCE.md` -- concept guide and adapter selection
- `ranvier/runtime/src/persistence.rs` -- API reference
- `ranvier/examples/persistence-production-demo/` -- demo scenarios