Write-Ahead Log
This page is part of the documentation for Orleans.Lattice 10.5.0 (release line 10.5), built 2026-12-05. It is also published as markdown, with every table and list, at wal.md, and llms.txt lists every page.This document describes how Orleans.Lattice uses a write-ahead log (WAL) as the sole foreground-commit durability boundary for every leaf grain mutation. The WAL is the primary on-disk truth: in-memory projections, secondary indexes, and replication consumers are all rebuilt from it on activation or recovery.
If you're looking for a different angle on the WAL:
- For the pluggable storage backend (in-memory, local file, or Azure Table) see
wal-storage-providers.md. - For how the in-memory projection is rebuilt from the WAL on activation see
projection-rebuild.md. - For the replication-side overlay (partitioned sink, producer-side
filters, and the
MutationCategory.Maintenanceskip) see../lattice.replication/wal.md. - For the causal+ entry-schema extension (vector clock + dependency
summary slots on
WalRecord) seewal-causal-plus.md.
Contents
- What the WAL is: The WAL is an append-only log of
LatticeMutationenvelopes, split into WAL partitions. - Why WAL-as-sole-commit-point: Every foreground commit (set / delete / range-delete) appends exactly one WAL record before the in-memory projection sees the write.
- Commit pipeline: Every leaf grain commit follows the same four-step pipeline.
- Durability boundary: The WAL append in step 2 is the foreground durability boundary.
- WAL grain API: Each WAL partition is owned by an internal grain keyed
{treeId}/{partition}wherepartitionis a stable FNV-1a hash of the key reduced modulo the tree's pinnedLatticeOptions.WalPartitions(default8). - Origin cluster id stamping: Every WAL record carries
OriginClusterIdso multi-site receivers can attribute the origin and break replication cycles. - Turn-safe batching protocol: The WAL grain's append path implements a turn-safe batching protocol: the exclusive-turn single append and the interleaving batch append that every single-entry append takes by default (
WalBatchedSingleEntryAppends, see Batched leaf write... - Recovery and rebuild: Formal model.
ReplayPermitschecks permit conservation, observed admission decisions, memory withholding and retained replay prefixes. - Projection checkpoint: To keep tail-replay bounded, the leaf flushes a projection checkpoint durably whenever the elapsed wall-clock time since the last flush reaches
MaterialiserCheckpointInterval(default: 5 seconds) or the count of unflushed advances... - Trim and GC: The WAL grows monotonically and must be trimmed.
- Clock floor (replicated trees): Each WAL partition of a replicated tree keeps a durable clock floor (#4586).
- Append epoch fencing: Orleans promises one activation per grain, but during a membership change a leaf can briefly run twice.
- Hand-off fences: The epoch fence above stops a stale duplicate of a leaf.
- Live checkpoint advance: A leaf whose WAL partition holds no record it has not read, other than its own writes, may advance its projection checkpoint over those writes without replaying them (#5570, #5572, #5593; design note section 1).
- Relationship to replication: Cross-cluster replication is an additional consumer of the same WAL - not a parallel pipeline.
- Configuration: The knobs below shape WAL retention and replay; defaults suit most workloads.
- Observability: The commit pipeline's primary instrument is the per-step latency histogram below.
- Related surfaces: contract and the in-memory, file, and Azure Table providers.
What the WAL is
The WAL is an append-only log of LatticeMutation envelopes, split into WAL
partitions. Each partition owns a monotonically increasing offset space starting
at zero, and an acknowledged offset is never reused or reordered. Offsets are
dense in normal operation. A flush that fails leaves its window unacknowledged
and the partition resumes from the provider's durable tail, so that window is
either reassigned (when nothing above it landed) or left as a permanent gap
(when a later concurrent window had already committed), which readers observe
honestly - see Append-failure semantics.
partition 0: [0]Set k1 [1]Set k2 [2]Delete k1 [3]Set k3 ...
partition 1: [0]Set a [1]DelRange [2]Set b [3]Set c ...
partition 2: [0]Set x [1]Set y [2]Set z [3]Delete y ...
A LatticeMutation carries everything a replay or replication consumer needs to
reconstruct the effect of one foreground operation: the tree id, the operation
kind (Set / Delete / DeleteRange, plus the TxCommit / TxAbort saga
terminals and the Tombstone compaction reap), the key (and optional
end-exclusive key for ranges), the LWW timestamp (an HybridLogicalClock), the
value bytes (or tombstone marker), the optional TTL expiry, the origin cluster
id, the vector clock, the optional transaction id, the maintenance category, the
optional delta payload and the merge mode, together with the atomic-batch
metadata (batch size, index and shard count, and the prepared flag), the merge
and backstop flags, the authoring shard index, the keys a predicate-filtered
range delete matched, the cross-tree operation id and participants, and
whether a prepared write's stamp is its prepare's original stamp (see
A commit applies each value at its prepare stamp;
the field is additive, so a record written before it existed reads as not
original), and whether the stored value is migrated (see
A later write the split imports is not dropped over the saga's value;
also additive, read as not migrated on an older record). The WAL
stores each envelope as its durable twin, WalRecord - the shape that is
encoded onto storage and shipped to replication peers, which also carries the
causal+ dependency summary - and a storage provider or IMutationObserver sees
it projected back to a LatticeMutation.
Why WAL-as-sole-commit-point
Every foreground commit (set / delete / range-delete) appends exactly one WAL record before the in-memory projection sees the write. The WAL append is the moment the operation is durable; everything after that is materialisation.
This is a deliberate trade. The wins:
- Single durability boundary. There is exactly one write-ahead step per commit. The in-memory projection has no independent durability guarantee; it is reconstructed from the WAL on activation.
- Replay-driven recovery. Activation rebuilds the in-memory projection from the leaf's latest durable snapshot plus a replay of the WAL past the offsets that snapshot covers - or of the whole readable WAL when the leaf has no usable snapshot. The WAL entry is the only thing a foreground commit must make durable before it returns; nothing else holds a second copy of the value that has to be kept in step with it.
- Replication coupling. A peer's change feed and the local commit log are the same byte stream. Cross-cluster replication is an additional consumer of the same WAL, not a parallel pipeline.
The cost:
- Cold-activation replay cost is bounded by snapshot coverage and
retention. A cold activation replays the WAL past the offsets the leaf's
latest snapshot covers, or the whole readable window when it has no
snapshot, so the size of a replay depends on how recently the leaf captured
a snapshot (its checkpoint persists drive those captures; see
projection-rebuild.md) and on how much WAL is retained. - The WAL provider must be durable. The default
InMemoryWalStorageProvideris fine for tests and single-process samples but is not crash-safe; production deployments register a durable provider through its package's registration helper -AddAzureTableWalStoragefromOrleans.Lattice.Storage.AzureTableorAddFileWalStoragefromOrleans.Lattice.Storage.File, each of which also wires the cursor registry and WAL garbage collector a durable log needs. Seewal-storage-providers.mdfor what a custom provider registered throughAddWalStorage(...)must add.
Commit pipeline
Every leaf grain commit follows the same four-step pipeline. The order is load-bearing - the WAL append must happen before any in-memory state mutates, and the observer publish must happen after both, inside a commit-log scope.
build --> wal --> apply --> observer
(HLC, (append (merge (publish under
entry, the WAL into the commit-log
WAL record) projection) scope)
record)
in-mem durable in-mem in-mem
build - Tick the local hybrid-logical clock and the version vector, construct the new entry's last-writer-wins value (or the tombstone), and build its
WalRecord. The record captures the ambientLatticeOriginContext,LatticeVectorClockContextandLatticeDeltaContext, plus the ambient transaction id, maintenance category and atomic-batch stamps.wal - Resolve the silo's commit-log writer and append the mutation.
AddLatticealways registers the writer, with the in-memory WAL provider as its baseline, so on a silo wired throughAddLatticethis step always runs; it is skipped only for a leaf that has no tree id yet (one created outsideILattice, for example by a test harness). Failures here propagate to the caller before any in-memory state has been touched. The writer fills an empty origin with the tree's resolved origin (the local cluster id on a replicated tree, an empty string on a single-cluster host), which the shipper and receivers rely on. The leaf row of an own write keeps a null origin, and a row rebuilt from the record later - by the projection, a replay or a snapshot's fold - turns that stamp back into null, so an own row has one representation however it was produced; a peer's origin is kept.apply - LWW-merge the value into the in-memory entry cache. If the leaf's entry count crosses
MaxLeafKeys, or its live state bytes crossMaxLeafBytes, trigger a split. This step is the only place that mutates the per-leaf in-memory state on the foreground path.observer - If any
IMutationObserveris registered, publish the post-commit mutation inside an ambient commit-log context scope. The scope marker lets a replication-aware observer detect that the source of this mutation was the local commit log and short-circuit its loop-prevention logic so it doesn't re-append its own input back into the WAL.
The pipeline is implemented in
the leaf point-write commit path
and the mirror paths for single-key and range deletes, the leaf's entry
merges (single and batched), and tombstone compaction. The wal, apply and
observer steps - plus digest, which hands the write's projection-digest
change to the parent internal node - record their elapsed wall-clock duration
to the orleans.lattice.leaf.commit.duration histogram tagged by step;
build is not timed separately. With the default
DigestCoalescingWindowMs
(5 ms) a write that changes the digest schedules, or joins, a publish the
leaf sends when the window elapses, outside the commit, so the digest step
includes the cross-grain publish itself only when the window is 0. The
orleans.lattice.leaf.write.duration histogram times the leaf's grain-state
persists with no kind tag, and additionally carries
kind-tagged samples that time the WAL appends of merge traffic
(kind=merge), tombstone compaction (kind=compact) and the cross-migration
LWW backstop (kind=backstop). Ordinary set and delete commits carry no kind
tag; size them with the per-step commit histogram.
The leaf's merge paths (single and batched) emit one envelope
per accepted entry with Kind = Set | Delete and IsMerge = true;
tombstone compaction emits one envelope per reaped entry with
Kind = Tombstone and IsMerge = true. The IsMerge flag is a ship-side
metric tag - receivers apply the envelope as an ordinary write regardless of
its value.
Durability boundary
The WAL append in step 2 is the foreground durability boundary. Three invariants follow:
- A successful commit implies a durable WAL append. If
SetAsyncreturns successfully, the mutation is in the WAL and visible to any replay. If the WAL append throws, the in-memory projection is untouched, and the caller sees the exception. - In-memory projection is reconstructable from the WAL and the leaf's snapshot. The projection has no independent durability guarantee. The leaf still persists its grain-state row for the projection-checkpoint flush (below) and for tree-metadata paths (sibling pointer updates, tree-id stamping, split lifecycle, last-compaction-version snapshotting), but those persist metadata, not a fallback copy of the entry values. The grain-state row never stores committed entry values as a backup: apart from the replay ledger that records unresolved saga prepares and undrained deferred terminals verbatim (see Resumable cold replay), entry values live in the WAL until they reach a durable snapshot, after which the WAL GC may trim the snapshot-covered prefix. The ledger is empty in the steady state, but a backlog of sagas whose terminals never land grows it without limit (see Tree Storage).
- Replication consumers see exactly the foreground commit ordering. A peer
replicating from this WAL partition sees the same
LatticeMutationenvelopes in the same order that the local projection saw them. The WAL is the linearization point.
Origin cluster id stamping
Every WAL record carries OriginClusterId so multi-site receivers can
attribute the origin and break replication cycles. The stamp comes from
two sources, applied in priority order when the silo's commit-log
writer routes the record to its WAL partition:
mutation.OriginClusterIdwins when present. A remote replay path stamps the upstream cluster id onto the mutation before it reaches the WAL writer; the writer preserves that value verbatim.- Fallback to the resolver-supplied local cluster id. When the
mutation arrives with no
OriginClusterId(null or empty) - the foreground commit path on a host where the replication observer has not yet stamped - the writer asksILatticeOriginClusterIdResolver.Resolve(treeId)for the local id.
ILatticeOriginClusterIdResolver is a public seam in the Orleans.Lattice
namespace. The core ships a
default resolver that returns string.Empty, so a
single-cluster host gets an empty stamp and downstream consumers ignore
it. Hosts that register Orleans.Lattice.Replication get a
configured resolver swapped in via the same
remove-then-TryAdd pattern that the replication package uses for
ILatticeMergeModeResolver. The configured resolver reads
LatticeReplicationOptions.ClusterId and caches the per-tree result with
IOptionsMonitor<T>.OnChange invalidation, so the commit-time hot path is
a single dictionary lookup. The writer asks for the id of the logical tree,
so a physical copy the tree has been moved onto (by a resize, a restore, a
bootstrap hold or a schema remediation or migration) stamps its writes with the logical tree's per-tree
ClusterId, the id the tree's shipper selects on.
The same resolver is consulted on the read-back path
(the WAL partition page read) so the change feed projects the same origin
the producer recorded - required for the replication-side loop-prevention
filter that drops batches whose OriginClusterId matches the local
cluster.
A user who needs to source the local cluster id from somewhere other
than LatticeReplicationOptions (e.g. a control plane, environment
variable, or per-tree feature flag) registers a custom
ILatticeOriginClusterIdResolver before calling AddLattice /
AddLatticeReplication; the package registrations use TryAddSingleton
and the swap loop only removes the default registration, so a
user-supplied resolver is preserved.
Projection checkpoint
To keep tail-replay bounded, the leaf flushes a projection checkpoint
durably whenever the elapsed wall-clock time since the last flush reaches
MaterialiserCheckpointInterval (default: 5 seconds) or the count of
unflushed advances reaches MaterialiserCheckpointEntries (default: 5 000),
whichever happens first. The checkpoint is a single grain-state write of the
leaf's persisted row, which records for each WAL partition the highest offset
the leaf has worked through - replay advances it past other leaves' records as
well as its own - together with the leaf's hybrid-logical clock and
version vector. It does not capture entry values: the persisted leaf row
has carried no per-key entries since the leaf-state collapse, and its former
entries slot is reserved; the only mutations it can carry are the unresolved
saga prepares and deferred terminals of the replay ledger (see
Resumable cold replay). On the
next activation the leaf rehydrates its entries from its latest durable
snapshot and replays the WAL only past the offsets that snapshot covers - the
checkpoint a capture stamps - rather than from zero; a partition no snapshot
covers is replayed from the start of its readable window.
Both triggers are evaluated as each advance is recorded. An advance that
arrives inside the interval and below the entry count - typically the last
partition an activation replay reconciled - would otherwise stay pending on
a resident, write-idle leaf, because no later advance re-asks the question.
The leaf's periodic coverage-lag check (every
LeafSnapshotMaxCoverageLagSeconds,
300 seconds by default) re-evaluates the same triggers and commits such an
advance once the interval has elapsed, so a pending advance becomes durable
within the later of the interval and the next check (issue #3608).
The checkpoint is not an additional durability boundary - it's a replay-cost optimization. If a checkpoint flush fails, the leaf rolls the advance back and keeps it pending for its next flush, and the durable pin it publishes for the WAL GC never runs ahead of the checkpoint that actually reached storage, so the GC cannot trim the range the failed write would have covered and the next activation simply replays more WAL entries; correctness is unaffected. The checkpoint is also flushed opportunistically at deactivation so a graceful shutdown doesn't lose an already-pending advance.
Clock floor (replicated trees)
Each WAL partition of a replicated tree keeps a durable clock floor (#4586).
How it moves. A replication shipper reads the partition through the partition's bytes-shaped shipping read. Each time it reads, the partition checks its floor against now - ReplicationClockFloorLag. Once the floor has fallen half a lag behind that target:
- The partition raises the floor to the target.
- It persists the new floor in its own grain state (
wal-floor). - Only then does it return the floor to the shipper, paired with its next offset.
That keeps the floor between one and one and a half lags behind the wall clock, at the cost of at most two storage writes per lag per partition while it is being shipped.
What it refuses. From then on, the partition refuses any freshly authored local write stamped below the floor, with a below-floor WAL stamp fault (counted on orleans.lattice.wal.append.floor_refusals). The check runs under the same state gate that assigns the offset, so a refused write is never assigned one.
Why. The floor-and-offset pair is a promise: every fresh local write at or above that offset carries a stamp at or above the floor. So once a peer has acknowledged everything below the offset, it holds every write of this cluster, in that partition, that is stamped below the floor. That is a low watermark that is downward-closed, which the max-HLC high-water mark is not (#1060). The replication package's causal low watermark is built on this promise.
Which writes the floor governs
The floor governs a stamp minted on this cluster for the write being appended. A carried stamp is exempt, because the identity it names was first appended fresh, at a lower offset. The carried stamps are:
- a replicated write of another origin;
- a merge or backstop copy;
- a migrated row, including a saga prepare carried at its original stamp from another shard;
- a record stamped under an HLC override, such as a shadow-forward or a prepared-bucket sweep (
WalRecord.IsCarriedStamp); - a tombstone-reap envelope;
- a record with a zero stamp.
Two overrides are minted for the operation itself, so the floor governs them: a range delete's issue stamp, and a caller-supplied idempotency key.
What a writer sees when its stamp is refused
| Write | On a refusal |
|---|---|
Single-key SetAsync or DeleteAsync |
The leaf merges its clock past the floor and re-stamps, then commits once in the same grain turn. The caller sees nothing. |
| Typed CRDT delta, or a multi-key batch | Not re-run in the turn, because the fold or another partition may already hold part of it. The leaf merges its clock past the floor, and the caller sees a transient error whose retry is admitted. |
DeleteRangeAsync |
The call re-issues a fresh dominating stamp for the remainder of the range. The keys already tombstoned keep theirs, so the delete lands as one HLC per uninterrupted run. A nested range delete keeps its owner's stamp and the refusal propagates to the owner. |
A write under a LatticeIdempotencyKey |
Fails with LatticeIdempotencyKeyExpiredException. The key's stamp cannot be renewed without breaking its contract (see Retry Policy). |
Rolling upgrades and trees that are not replicated
A partition advances its floor only while every active silo's grain manifest advertises provider clock-floor capability. That marker is the capability of a build that both enforces the floor and re-stamps a refused write. So during a rolling upgrade, no floor moves until the last older silo has left; the gate opens by itself, and there is no option to forget to enable.
A floor already published stays enforced, because it is durable. If the gate closes again, the floor only stops moving. Downgrading to a build without the marker after a floor was published is unsupported.
A tree that is not replicated is never read by a shipper. Its floor stays zero, and it never refuses a write.
Relationship to replication
Cross-cluster replication is an additional consumer of the same WAL - not
a parallel pipeline. The replication change feed reads LatticeMutation
envelopes from the WAL, applies them on the peer cluster through
IReplicationApplier, which writes them into the peer tree through its
per-tree apply path, and acknowledges its progress through the same cursor
registry that GC consults.
The single-cluster and multi-cluster code paths are identical up to the point where replication transports an envelope across a network boundary. There is no "replication mode" that changes how a foreground commit durabilizes - the commit always appends to the local WAL, and replication is purely additive.
See ../lattice.replication/replication-drivers.md
for the driver-grain scheduling model that consumes the WAL on each peer.
Configuration
The knobs below shape WAL retention and replay; defaults suit most workloads. They are a subset: the full WAL option set - batching and pipeline depth, admission and saturation, GC cadence, and the materialiser pin store - is in the Options Reference.
| Option | Default | Purpose |
|---|---|---|
MaterialiserCheckpointInterval |
5 seconds | Time-driven flush of any pending projection-checkpoint advance. Set to Timeout.InfiniteTimeSpan to disable the time trigger and rely solely on the entry-count trigger. |
MaterialiserCheckpointEntries |
5_000 |
Entry-count trigger: forces a checkpoint flush once this many advances are pending, regardless of MaterialiserCheckpointInterval. Bounds the worst-case replay cost when the steady-state apply rate is high. |
MaxLeafReplayEntries |
10_000 |
Per-leaf replay size above which a cold activation logs a warning and increments orleans.lattice.leaf.activation_replays_over_budget. It counts the entries the leaf actually applies after its ownership filter, and it is a cost signal only: the leaf still tail-replays in full, and exceeding it never routes to ProjectionRebuildPolicy (issue #1738). |
LeafProjectionRetention |
7 days | Age beyond which a persisted checkpoint is flagged as a cost signal only - the leaf still tail-replays and never falls off-log on age alone. The activation path currently supplies a zero age, so the trigger does not fire from activation today. Set to Timeout.InfiniteTimeSpan to disable the age-based trigger. |
ProjectionRebuildPolicy |
SnapshotThenWal |
Recovery strategy consulted only on genuine loss (the WAL trimmed past the checkpoint with no covering snapshot); today every policy refuses the leaf with LeafProjectionStaleException. See projection-rebuild.md. |
WalRetention |
null (disabled) |
Wall-clock hard ceiling on retention: entries older than now - WalRetention fall off the log even if a consumer still pins them. The only knob that trims past a stuck consumer - set it where unbounded growth is unacceptable. See How the retention bounds interact. |
WalMaxRetainedBytes |
null (disabled) |
Advisory per-tree byte ceiling that schedules byte-pressure trim work, but only within the safe consumer frontier. See Tree Storage. |
WalBytePressureReclaimTarget |
0.8 |
Low-water hysteresis fraction of WalMaxRetainedBytes that disarms the byte-pressure policy after a trim. Inert unless WalMaxRetainedBytes is set. |
ReplicationClockFloorLag |
60 seconds | How far a replicated tree's clock floor trails the wall clock. It is also the shortest time an idempotency key stays usable on a replicated tree. Must be between one second and one day. |
The WAL provider itself is registered separately - through a storage package's
helper such as AddAzureTableWalStorage or AddFileWalStorage, or siloBuilder.AddWalStorage(...)
for a custom provider (a replicated host can also supply a per-tree resolver
through LatticeReplicationOptions.WalStorageProvider). See
wal-storage-providers.md for the provider seam
and the in-memory, file, and Azure Table providers.
Observability
The commit pipeline's primary instrument is the per-step latency histogram below. The leaf write-duration histogram described under Commit pipeline, and the WAL writer and shard instruments catalogued in Metrics, complete the picture.
| Instrument | Type | Tags | Meaning |
|---|---|---|---|
orleans.lattice.wal.append.floor_refusals |
counter ({entry}) |
tree, shard, tenant |
Fresh local writes a replicated tree's partition refused below its clock floor. A sustained rate points at silo clock skew or a write pipeline stalled for longer than ReplicationClockFloorLag. |
orleans.lattice.leaf.commit.duration |
histogram (ms) | tree, step (one of wal, apply, digest, observer) |
Per-step latency of the foreground commit pipeline. The wal step is the durability cost; apply is the in-memory merge plus any relocation or split it triggers; digest hands the write's projection-digest change to the parent internal node - with the default DigestCoalescingWindowMs it schedules, or joins, a publish sent when the window elapses, so it includes the cross-grain publish itself only when the window is 0; observer is the publish under the commit-log scope. |
The bundled Grafana dashboards consume these instruments directly; see
../lattice.dashboards/README.md.
Related surfaces
wal-storage-providers.md- pluggable backend contract and the in-memory, file, and Azure Table providers.projection-rebuild.md- drift detection and the fall-off-log rebuild path.tombstone-compaction.md- how reaped tombstones interact with WAL retention.configuration.md- the fullLatticeOptionssurface.wal-causal-plus.md- causal+ entry-schema extension (vector clock + dependency summary slots onWalRecord).../lattice.replication/wal.md- the replication-side overlay: partitioned sink, producer-side filters, and theMutationCategory.Maintenanceskip.