Atomic Multi-Key Writes
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 atomic-writes.md, and llms.txt lists every page.ILattice.SetManyAtomicAsync(entries) commits a batch of key-value pairs with
all-or-nothing semantics: either every entry in the batch is durably written,
or - on any failure - none of them is, and every key keeps its pre-saga value.
The feature is implemented as a saga coordinator that stages the whole batch
through the tree's batched write path as prepared writes readers cannot see,
then makes it visible - or discards it - with a single commit or abort
decision recorded in the tree's transaction registry. An abort issues no
per-key rollback writes.
The non-atomic SetManyAsync remains available for throughput-oriented use
cases where partial application on failure is acceptable.
If you need to commit a tree write all-or-nothing together with a non-tree
effect - a payment, an email, a call to another grain - reach for the
Atomic Action coordinator instead. It generalizes this
key-only atomic write to an ordered plan of arbitrary caller-defined
forward/compensate steps, and ships a built-in tree-write step that delegates
back to this machinery, so a SetManyAtomicAsync-equivalent mutation can be one
step of a larger saga without giving up the atomicity guarantees described here.
Contents
- Atomicity Guarantees: This section describes the atomicity contract of the saga.
- Usage
- Mixed upsert + delete batches:
SetManyAtomicAsync(upserts, deletes, operationId)commits a batch that mixes upserts and deletes in a single all-or-nothing visibility flip. - Guarded atomic writes:
SetManyAtomicAsync<T>(entries, predicate)adds an all-or-nothing precondition: the batch commits only if every targeted key's pre-saga value satisfies the predicate. - How It Works: Each call to
SetManyAtomicAsyncis routed by the tree to a saga coordinator grain keyed by{treeId}/{operationId}, whereoperationIdis a GUID generated per call (or the caller-supplied idempotency key - see Caller-supplied... - Crash-Recovery Timeline
- Performance Notes: with its size N: the prepare phase reads every key's pre-saga value with one batched read per touched shard (issued in parallel), and the execute phase dispatches the whole unwritten remainder as one
SetManyAsyncfan-out whose per-leaf... - Shutdown back-pressure: A saga that is dispatched while the silo is shutting down (the host has received SIGTERM and the WAL writer is draining) cannot reach the storage layer - the writer-side drain refuses new appends with the typed...
- Silo restarts: A silo restart is where the shutdown fast path above meets live readers.
- Batches whose caller was answered: A caller can be answered with a failure while its saga is still working.
- Caller-supplied idempotency keys: The default
SetManyAtomicAsync(entries)overload generates a freshGuidper call as the saga'soperationId. - Ambient context capture-once: A caller that wraps
SetManyAtomicAsyncinLatticeVectorClockContext.With(...)has the ambient frontier captured once, on the saga's first prepare, and re-established before every dispatch the saga issues, so every prepared write... - Atomic-batch metadata on emitted mutations: In addition to the saga-wide
VectorClock, every per-keyLatticeMutationthe saga emits also carriesAtomicBatchSize(the total entry count of the enclosing transaction) andAtomicBatchIndex(the zero-based position of the key within... - Cross-cluster atomic visibility: Cross-cluster atomic visibility ships universally through the same per-tree transaction-registry linearization point used locally.
- Cross-tree (multi-tree) atomic writes:
SetManyAtomicAsyncis bound to a single tree. - Related: extensions.
Usage
var tree = grainFactory.GetGrain<ILattice>("orders");
// Byte-array surface
var batch = new List<KeyValuePair<string, byte[]>>
{
new("order:42/status", Encoding.UTF8.GetBytes("shipped")),
new("order:42/tracking", Encoding.UTF8.GetBytes("1Z999")),
new("customer:alice/last-order", Encoding.UTF8.GetBytes("42")),
};
await tree.SetManyAtomicAsync(batch);
// Typed extension (System.Text.Json by default)
var typedBatch = new List<KeyValuePair<string, Order>>
{
new("order:42", new Order("42", 99.95m)),
new("order:43", new Order("43", 12.50m)),
};
await tree.SetManyAtomicAsync(typedBatch);
Mixed upsert + delete batches
SetManyAtomicAsync(upserts, deletes, operationId) commits a batch that mixes
upserts and deletes in a single all-or-nothing visibility flip. Every key
in upserts is written and every key in deletes is tombstoned as one atomic
unit: a reader observes either the whole batch applied or none of it, never a
partial state where some upserts are visible but the deletes are not (or vice
versa). Each delete becomes visible on commit and is dropped on abort, riding
the same saga terminal as the upserts.
This is the primitive behind atomic re-key retraction: when a logical row moves
from key A to key B, the upsert at B and the delete at A flip together,
so a reader never sees both keys at once or neither. The materialised-view
maintainer uses it to flush a completed atomic batch's upserts and retraction
deletes inside one mixed op (see Materialised views).
A stable operationId is required for this overload so a client retry
re-attaches to the original saga. The delete-key channel is optional on the
wire: a batch with no deletes is byte-identical to the value-only overload.
var tree = grainFactory.GetGrain<ILattice>("orders");
// Move order:42's row from the "pending" index key to the "shipped" index key
// atomically: the new key appears and the old key disappears in one flip.
var upserts = new List<KeyValuePair<string, byte[]>>
{
new("index/shipped/order:42", Encoding.UTF8.GetBytes("42")),
};
var deletes = new List<string> { "index/pending/order:42" };
await tree.SetManyAtomicAsync(upserts, deletes, "rekey:order-42");
On the cross-tree fluent builder, stage a retraction with .Delete(key)
alongside .Set(...) calls under the same ForTree(...); the deletes ride the
cross-tree saga and flip jointly with the upserts (see
Cross-tree atomic writes).
Guarded atomic writes
SetManyAtomicAsync<T>(entries, predicate) adds an all-or-nothing
precondition: the batch commits only if every targeted key's pre-saga
value satisfies the predicate. The predicate is compiled to the serializable
predicate IR and evaluated once, server-side, against each key's captured
pre-saga document during the saga's prepare phase - a key with no live
pre-saga value counts as a non-match. When any key fails the saga aborts
before any write and the call returns AtomicWriteOutcome.PreconditionFailed
with nothing committed; when all match it returns
AtomicWriteOutcome.Committed. A precondition miss is reported as a value,
not an exception, so a guarded conflict is ordinary control flow. Genuine
write failures still throw and compensate exactly as the unguarded overload.
The idempotency-key overload re-attaches to the original saga and returns its memoized outcome without re-evaluating the (pure) predicate against possibly-moved data.
var tree = grainFactory.GetGrain<ILattice>("orders");
var guardedBatch = new List<KeyValuePair<string, Order>>
{
new("order:42", new Order("42", 99.95m)),
new("order:43", new Order("43", 12.50m)),
};
// Only commit the whole batch if every order's current Total is below 1000.
AtomicWriteOutcome outcome =
await tree.SetManyAtomicAsync<Order>(guardedBatch, o => o.Total < 1000m);
if (outcome == AtomicWriteOutcome.PreconditionFailed)
{
// At least one order's pre-saga value failed the guard; nothing was written.
}
Crash-Recovery Timeline
| Crash point | State on reactivation | Recovery path |
|---|---|---|
| Before the prepare checkpoint persists | Not started - nothing persisted | Reminder tick unregisters itself and deactivates. Client's pending call returns a transport error; the client retries (the same caller-supplied operationId starts the saga afresh; the auto-generated overload mints a new one). |
| During execute, before the whole batch is staged | Execute phase, staging checkpoint not yet written | A re-issue of the same operationId resumes the saga forwards: it re-dispatches the whole unwritten remainder (re-staging a write already staged for the transaction is idempotent) and drives to completion. A keepalive-driven resume normally runs past the caller's decide-by deadline (the reminder first fires a minute after the saga started), so it instead records an abort, broadcasts the abort terminals, and completes (see Batches whose caller was answered). |
| After the whole batch is staged, before completion persists | Execute phase, every entry staged | If the commit decision was already recorded, the resumed saga re-records it (a same-outcome repeat is a no-op), re-broadcasts the commit terminals (idempotent at the leaf), then completes. If it was not, a keepalive-driven resume rolls the saga back exactly as in the previous row. |
| During compensate | Compensate phase | Reminder tick re-drives the abort decision and the abort-terminal broadcast (both idempotent), then completes. |
| Parked as a cross-tree participant | Prepared (paused) | The keepalive tick is a deliberate no-op; the cross-tree coordinator's own reminder re-drives its finalize call, which records this tree's decision, broadcasts the terminals, and completes. |
| After completion persists | Completed (or precondition-failed) | Reminder tick re-runs the terminal cleanup idempotently - it unregisters itself, arms the retention reminder and, for a completed saga, forgets the registry decision - then deactivates. Completion metrics and the completed event are not re-emitted. |
Performance Notes
- A saga's Orleans traffic scales with the shards it touches rather than
with its size N: the prepare phase reads every key's pre-saga value
with one batched read per touched shard (issued in parallel), and the
execute phase dispatches the whole unwritten remainder as one
SetManyAsyncfan-out whose per-leaf slices collapse into batched WAL dispatches. Around that sit the saga's own state writes, a handful of registry calls (an admission check before prepare, a best-effort bulk participant registration after prepare, the single decision write, a post-broadcast participant re-fetch that catches a shard a concurrent split added, and one cleanup call that tombstones the decision), a routing refresh, a split-forward probe per touched shard, and one terminal RPC per touched shard, whose terminal WAL records are then appended as one batched write per WAL partition. For large batches where atomicity is not required, prefer the parallelSetManyAsync. - The saga's persisted state is stored under the Lattice storage provider
(
LatticeOptions.StorageProviderName,"lattice") with theatomic-writestate name. The saga grain deactivates on completion, so the storage row is typically read exactly once (on activation) and written three times on the happy path: the prepare checkpoint (which records the pre-saga snapshot and flips the phase to execute), the post-staging checkpoint, and the terminal completed write. A retried dispatch and a pivot to compensate each add one write, and the terminal broadcast adds one only when it has to grow the persisted touched-shard set (a routing change, a concurrent split, or a late participant). The final (completed) write also releases the staged batch payload, so a completed saga's persisted footprint is bounded to its lightweight outcome fields for the retention window rather than the full batch value payload - which matters most for high-cardinality bulk workloads that produce one saga per touched key. - Reads pay for visibility in registry calls, never in locks. A direct single-key read that finds a pending key resolves it with one call to the saga's registry shard, and a leaf resolving several pending keys without an ambient snapshot batches them into one call per owning shard. Multi-key reads, scans and cursors instead capture one tree-wide registry snapshot at entry on every call, whether or not a saga is in flight, and stamp it onto an ambient context so every leaf in the read reuses it; a multi-key read or count also re-reads the registry revision after its fan-out to confirm the snapshot held. On an unsharded tree the snapshot is one registry call; once sagas are minted across shards it is one call per registry shard up to the tree's shard high-water mark plus the legacy registry. Either way it reads the mark alongside, and a silo's concurrent reads of a tree share one round (see Sharded decision registry). The coordinator does not block, lock, or serialise reads - these registry calls are the entire visibility cost.
- Multi-page enumerations (streaming
ScanKeysAsync/ScanEntriesAsyncand point-in-time durable cursors opened withpointInTime: true) take the same tree-wide registry snapshot once and reuse it across every page, so the per-page registry cost is zero after the initial capture. Point-in-time durable cursors additionally pin the captured decision set on the registry so a saga that completes mid-enumeration still has its verdict resolvable for the cursor's lifetime; see Durable Cursors - Point-in-time cursors.
Silo restarts
A silo restart is where the shutdown fast path above meets live readers. The saga in flight on the departing silo is parked with its prepared writes staged, and the leaves that held them reactivate elsewhere and rebuild their pending saga state from the write-ahead log, so the parked saga's prepares come back still undecided. They stay undecided until the saga resumes, which may be long after the restart, and every later batch over the same keys prepares beside them.
Atomic visibility does not wait for that resumption: it holds at every instant, with any number of parked sagas.
- A key covered by several sagas' prepares resolves against the one saga whose outcome actually decides it, on every read path alike: a committed saga whose commit has not yet reached the leaf (the newest one, if several have committed) surfaces its value; a saga whose outcome is indeterminate hides the key; in-flight and aborted sagas are invisible whatever their age; and a prepare a newer row has already superseded never decides, because its commit would not overwrite that row. A parked saga therefore never shadows a later batch that has committed, and a later in-flight batch never shadows an older one that has.
- A key covered by one saga's prepare that a newer row supersedes resolves to the row, whatever that saga's outcome. A restart can record a saga's commit and lose its commit on the way to one leaf (an online resize's copy, whose shard could not log it while its silo shut down), leaving that saga's older value pending there while every later batch commits beside it; the leaf serves the later batches, as its siblings do.
- A leaf rebuilt by activation replay drains each replayed commit with a stamp derived from the rows it writes and that saga's own prepares, never from a clock that has already absorbed a later saga's prepares. A batch that commits after the reactivation therefore lands on that leaf like on every other.
Neither depends on the parked saga's keepalive reminder firing: the reminder resumes the saga, but readers are atomic before it does.
Batches whose caller was answered
A caller can be answered with a failure while its saga is still working.
Its call times out; or the routing tier behind ILattice re-issues the
saga after a transient fault - a silo leaving the cluster, say - by which
time the caller has timed out and may already have written the same keys
again. A saga that then committed would make its batch visible after
those newer writes, so a later batch would read back at this one's older
values.
- A saga commits only while its caller can still be waiting. Every
SetManyAtomicAsyncandSetManyAtomicWhereAsynccall carries a decide-by deadline: the silo'sSiloMessagingOptions.ResponseTimeout, less a tenth of it (at least one second, at most half) for the time the request spent reaching the silo. The saga persists the deadline and checks it before it starts work and again immediately before its commit decision. A saga past the deadline that has not recorded its commit records an abort instead and rolls the batch back - its prepared writes were never visible - and fails withInvalidOperationException("... failed and was rolled back"). A saga that already recorded its commit is unaffected: the decision made the batch visible, and the saga only finishes delivering it. - A late resume rolls back. The keepalive reminder first fires a
minute after the saga started, past any deadline, so a reminder-driven
resume of a saga that never recorded its commit rolls it back. A caller
that re-issues its
operationIdwaits afresh: the re-issue carries its own deadline and resumes the saga forwards. - A terminal delivered again does not overwrite newer writes. A committed saga's terminal can reach a leaf more than once - a saga resumed after its decision re-runs its broadcast. A repeat no longer re-applies the batch over a key written on that leaf after the terminal first landed there.
The deadline is derived from the silo's response timeout because the
caller's own is not observable. A client configured with a shorter
ClientMessagingOptions.ResponseTimeout than the silo's can still time out
before the deadline; configure the two alike.
Caller-supplied idempotency keys
The default SetManyAtomicAsync(entries) overload generates a fresh
Guid per call as the saga's operationId. On a transport-level failure
(silo restart mid-call, client-side timeout, transient network error) the
client has no way to re-attach to the in-flight saga and must treat the
call as failed - the original saga may still commit server-side.
The SetManyAtomicAsync(entries, operationId) overload takes a stable
caller-supplied idempotency key, which maps directly to the saga grain
identity ({treeId}/{operationId}). Re-submitting the same
operationId re-attaches to the original saga:
- If it has already reached a terminal state, the second call returns immediately (or rethrows the original terminal failure) - the client observes the original outcome.
- If it is still in flight, the second call awaits the saga's terminal state.
The re-submission is checked on entry exactly like a first call (see Atomicity Guarantees), so a check that refuses it - an enforcing cap the tree has reached since, for example - surfaces before the call can re-attach.
This turns a transport-level failure into a recoverable client-side retry
- the caller simply calls again with the same
operationId.
string orderId = "42";
string customerId = "7";
// Stable per-business-operation idempotency key.
var operationId = $"order-{orderId}";
var entries = new List<KeyValuePair<string, byte[]>>
{
new($"order:{orderId}:state", Encoding.UTF8.GetBytes("paid")),
new($"customer:{customerId}:last-order", Encoding.UTF8.GetBytes(orderId)),
};
// Safe to retry on timeout: the saga is bound to operationId, not to
// this RPC attempt.
await tree.SetManyAtomicAsync(entries, operationId, cancellationToken);
Key-set stability
An operationId is bound to the exact set of keys submitted on its
first call. The saga persists a SHA-256 fingerprint of the sorted key
set during the prepare phase; a subsequent call reusing the same operationId
with a different key set (added, removed, or renamed keys) throws
LatticeIdempotencyKeyMismatchException (a subclass of
InvalidOperationException). Reordering keys or changing their values
is allowed - the fingerprint hashes the sorted key list only, so the
same logical retry with a slightly-different serialized payload is
accepted as idempotent.
Validation
operationIdmust be non-null, non-empty, and non-whitespace.operationIdmust not contain'/'- reserved as the grain-key separator between tree ID and operation ID.
Both constraints throw ArgumentException at submission time.
Retention window
Completed saga state is retained for
LatticeOptions.AtomicWriteRetention (default 48 hours) so delayed
retries within the window still observe the original outcome. Only the
lightweight outcome fields are retained; the staged batch payload is
released on the terminal checkpoint (see Phase 4 - Complete),
so the retained footprint per completed saga is bounded to its outcome and
does not scale with the batch's value size. After
the window, the saga grain's state is cleared and its activation
deactivates - the same operationId then becomes eligible for a fresh
saga. Set the option to Timeout.InfiniteTimeSpan to disable
retention cleanup (completed saga state then lives forever, at the
cost of unbounded growth in the number of retained outcome rows).
Ambient context capture-once
A caller that wraps SetManyAtomicAsync in
LatticeVectorClockContext.With(...) has the ambient frontier captured
once, on the saga's first prepare, and re-established before every
dispatch the saga issues, so every prepared write in the batch carries the
identical VectorClock - closing per-key drift a remote replication
consumer would otherwise see as a partial-set state where the writer's
frontier said all N keys should be visible together.
The captured frontier is durable: a silo crash mid-saga resumes from
persisted state and re-stamps the persisted frontier on the resumed
dispatch, so observers see the same VC across the original emits and the
post-recovery emits. The origin-cluster stamp is not captured the same
way: a LatticeOriginContext.With(...) scope around the call rides only
the originating request, so it reaches the writes the first attempt
dispatches but is absent from a reminder-driven resume.
var vc = new Orleans.Lattice.VersionVector();
vc.Tick("origin-peer");
using (LatticeVectorClockContext.With(vc))
{
await tree.SetManyAtomicAsync(new List<KeyValuePair<string, byte[]>>
{
new("k1", Encoding.UTF8.GetBytes("v1")),
new("k2", Encoding.UTF8.GetBytes("v2")),
new("k3", Encoding.UTF8.GetBytes("v3")),
});
}
// Every per-key mutation observed downstream carries the identical
// VectorClock, regardless of how the saga's writes were interleaved.
Atomic-batch metadata on emitted mutations
In addition to the saga-wide VectorClock, every per-key
LatticeMutation the saga emits also carries AtomicBatchSize (the total
entry count of the enclosing transaction) and AtomicBatchIndex (the
zero-based position of the key within the batch). The size is captured
once, on the first prepare, from the submitted entry count and persisted
with the saga; the saga then re-stamps it onto the ambient
LatticeAtomicBatchContext around its batched dispatch, together with a
key-to-index map, so every staged write carries its batch-global index no
matter which shard or leaf it routes to. Single-key writes outside a saga
emit 0 / 0 (the "not-in-a-saga" sentinel).
These two slots are metadata about the saga's shape - they let a downstream observer (a change-feed consumer, a mutation-observer pipeline, an audit log) recognise that several mutations belong to the same enclosing batch and reason about batch-level invariants without coordinating with the producer. They are not the atomicity primitive: tree-wide atomic visibility is delivered by the per-tree transaction registry plus the per-leaf pending-tx mechanism described above. They are consumed, though: a replication receiver lets a prepared write with a non-zero batch size bypass its snapshot-floor dedup (the pending-bucket merge and the terminal mark deduplicate it instead) and its causal-dependency park (which could otherwise deadlock sibling prepares behind one another), and rejects a range delete that carries batch metadata; the replication anti-entropy leaf re-replay ships an atomic batch as one whole unit; and the materialised-view maintainer flushes a staged batch only once its prepares satisfy the declared size. See Consistency: Atomic visibility.
Related
- API Reference - full
SetManyAtomicAsyncsignature and typed extensions. - State Primitives - HLC and LWW semantics the saga's per-key writes resolve under.
- Chaos Tests - atomic-write workload exercised under concurrent splits and fault injection.
- Atomic Action - the generic saga / TCC coordinator that layers arbitrary forward/compensate steps over this atomic-write machinery.