Table of Contents

Turn-safe batching protocol

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 turn-safe-batching-protocol.md, and llms.txt lists every page.

Part of Write-Ahead Log.

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 path) run the same cutover protocol. Each call accumulates into an in-memory pending batch held on the grain instance; up to WalMaxPendingBatches flushes can be in motion against IWalStorageProvider.AppendEncodedBatchAsync simultaneously, each independently completing per-caller TaskCompletionSource<long> instances when the provider acknowledges durability. Offset assignment is serialised under the WAL partition's internal state gate, so each in-flight flush owns a strictly-increasing, non-overlapping offset window by construction even while batch appends interleave.

append(entry)
    |  encodes the record once into a pooled buffer
    |  while adding it would overflow the pending batch:
    |      in-flight flushes <  cap -> start a flush of the pending batch
    |      in-flight flushes >= cap -> await the oldest in-flight flush
    |  assigns offset = next offset, then advances the counter
    |  appends the encoded entry to the pending batch and parks an ack
    |  in-flight flushes < cap -> start a flush
    v
returns the ack          <-- completes once the provider acks the batch

The batching limits and flush bounds:

Option Default Trigger
WalMaxBatchEntries 100 Adding the new entry would push the pending count above the cap; the current batch is flushed first, then the new entry starts the next batch.
WalMaxBatchBytes 4 MB Adding the new entry's exact serialised size would exceed the byte budget; same cutover. The grain encodes every captured WalRecord once through the registered IWalRecordEncoder (default: OrleansBinaryWalRecordEncoder, the canonical Orleans-binary codec) into a pooled buffer; the encoded length feeds the byte budget, and the same bytes are handed to the provider's AppendEncodedBatchAsync on flush without a second encode. The budget is an exact ceiling for any batch of more than one entry (a single entry larger than the whole budget is flushed alone rather than refused), suitable for sizing against backends with hard transactional limits (e.g. the Azure Table Storage 4 MB batch cap). It bounds the batch, not each entry: on the Azure Table provider the Table service also limits each entry's stored payload to 64 KiB (see WAL storage providers).
WalMaxPendingBatches 16 Maximum number of in-flight + just-started flushes the grain holds against the provider concurrently. The pre-6.1.0 default was 1, which reproduced the original single-in-flight protocol bit-for-bit; the v6.1.0-v6.2.x default of 8 raised pipeline depth so writer-side bursts coalesced against higher-latency durable providers (e.g. Azure Tables). The post-v6.2 default of 16 was measured on Standard_D4as_v5 + Azure Tables Standard at 4,000 keys/s offered load to give a +57% increase in steady-state silo throughput at the 4k:5 rung with no reliability regression; see WAL tuning for the storage-account-throughput envelope above which the dual-knob fan-out collapses to 429 throttling. The cap is the only synchronisation point new appends see, so cap values above the steady-state burst depth do not buy further throughput. Set explicitly to 1 to opt back into the legacy strict-serial-per-partition shape.
WalFlushTimeout 15 s Upper bound on how long a single flush may take before the grain abandons the wait, faults the flush, resynchronises the dense-offset tail from the provider, and drains the chain so callers retry. Set to Timeout.InfiniteTimeSpan to restore the historical unbounded await. See Flush deadline.
WalFlushPreflightTimeout 5 s Upper bound on a flush's preflight - the setup and initial scheduler yield before the provider call is issued - so a flush whose continuation never resumes faults as a TimeoutException and its slot drains. See Flush deadline.
WalAppendCoalescingInFlightThreshold 4 In-flight depth at or above which a batch append's final entry stops kicking a flush of its own and coalesces into the pending batch, drained by the follow-on flush that fires when an in-flight flush settles. Self-disabling below the threshold; 0 restores the unconditional final-entry kick. See WAL tuning.

Cutovers below the in-flight cap start a fresh flush immediately; cutovers at the cap await the oldest in-flight flush before starting another, which provides natural back-pressure under sustained burst load.

Flush deadline

The number of in-flight flushes is bounded by WalMaxPendingBatches; the cap is the only synchronisation point new appends see. If one flush never settles, its slot never leaves the in-flight chain, the chain saturates at the cap, and every subsequent append back-pressures behind a flush that can never complete - a steady-state stall with no fault and no activation recycle. A provider call can fail to settle for reasons outside the grain's control: a partition left half-activated by a placement/reshard race, an SDK retry loop that never gives up, or a backend that simply stops responding.

WalFlushTimeout (default 15 s) bounds the flush so that hang becomes a recoverable TimeoutException routed through the normal append-failure path: the tail is resynchronised from the provider and the chain drains, so callers that retry observe a healthy grain.

The bound is enforced in two places, deliberately:

  1. The deadline's cancellation token is passed to the provider call, so a co-operative provider stops its own work promptly when the deadline trips.
  2. The grain also bounds its own await on the provider task with Task.WaitAsync(deadline). A provider whose hang does not observe the token - a non-cancellable SDK wait, a retry loop that swallows cancellation, or a genuinely wedged half-activated partition - would otherwise leave the grain awaiting forever even though the deadline has fired. Bounding the grain's own wait abandons the un-cancellable provider task (its slot is removed and its eventual completion is harmlessly unobserved) so the chain drains regardless of whether the provider honours cancellation.

Bounding only the call (passing the token) is not sufficient on its own; bounding the wait is what makes the deadline wedge-proof against uncooperative providers.

WalFlushTimeout arms only once the provider call is issued. The flush's preflight - the setup and initial scheduler yield that precede the call - has its own bound, WalFlushPreflightTimeout (default 5 s): a flush whose post-yield continuation never resumes (an activation parked by a reshard or membership change, a scheduler hogged by non-cooperative work, or a teardown mid-flush) faults as a TimeoutException through the same failure path, so its slot drains instead of saturating the chain, and the orleans.lattice.wal.flush.preflight.timeouts counter attributes each trip to the (tree, shard).

Abandoned flushes, holes and the trim watermark

A flush abandoned at its deadline is still in motion and may land later (issue #4621). Until its provider call settles, nothing at or above its window is exposed to a reader - by a page read, a shipping read, or the readable head that readers resume from - so a late landing is never below a reader's position. The record of such windows is process-wide, keyed by provider and shard, so a reactivation of the shard in the same process is held too, and a WAL move's quiesce does not report the shard's tail stable while any window in it is unsettled (issue #4699). Exposure is also never past the highest offset the shard knows is stored, plus one: a recovering allocator resumes there, so a trailing hole stays unexposed until something lands above it, and a reissued offset can never land below a reader. The post-failure resync normally rewinds the allocator to that point itself; the bound matters when the resync fails and the activation keeps serving reads until it is deactivated. Once the call settles, its window is final: the entries landed, and are read in order, or the slot is a permanent hole, because the allocator is already past it. Offsets are therefore not dense.

A provider call that fails before the deadline is not proof that nothing landed either (issue #6116): a request the storage client abandoned on a per-attempt network timeout, or one answered by a transient fault, can still commit on the service afterwards. A provider can mark such a fault as an unknown outcome, with a settle signal of its own, and the shard then fences the window exactly like a flush abandoned at its deadline. The Azure Table provider does this for a phase-1 fault after any attempt that may still commit; its signal completes once the batch's first entry row is present, or 60 seconds after the fault with the row absent, and the batch's rows, which have no manifest row, are reclaimed at the next reconciliation.

A hole directly above a trim point looks exactly like a trim to a reader that judges by the lowest stored offset. Every provider therefore keeps a trim watermark (IWalStorageProvider.GetTrimWatermarkAsync): the highest offset any trim has trimmed through, persisted before the trim deletes anything, never returned by a read. An offset at or below it was trimmed; a missing offset above it is a hole. The in-memory provider raises it under the same lock as the delete, the file provider records it as its trim marker, and the Azure Table provider in a per-shard row of the manifest partition. The tail every reader judges fall-off by - the leaf's prefix-loss check, the WAL subscriber, the fall-off detector, and the replication shipper's forced-gap check - is one past the watermark.

A reader trusts the watermark only when every silo in the cluster manifest hosts the build that maintains it: a silo that predates it trims without moving it, and its trims would read as holes. Until then, and for a third-party provider that keeps no watermark, readers treat every jump in offsets as a trim, which can trigger a needless rebuild or re-seed during a rolling upgrade but never skips a trim.

A watermark is only ever inferred from what was committed. Up to 10.2.0 the Azure Table provider inferred an empty shard's watermark from its highest offset, which counts batches accepted but not yet committed; a probe during a shard's first batch, or its first after a full trim, cached that batch as trimmed and every later read on the silo skipped it: a view stalled on it, and once a later entry landed the shipper, the views and leaf replay could read past the skipped range and lose it (issue #6036). The provider now infers from the committed tail, and IWalStorageProvider.RefreshTrimWatermarkAsync re-derives the watermark from storage, replacing a cached value. Two backstops use it:

  • A dense reader that sees a jump which is not a trim - the WAL subscriber and the replication shipper - refreshes the partition's watermark and re-reads once from the same position. What reappears is surfaced or shipped, and only what is still missing, a genuine hole, is read past. Both outcomes are metered (orleans.lattice.wal.subscriber.holes_skipped and orleans.lattice.replication.ship.holes_skipped, tagged outcome = recovered or hole) and logged at Warning.
  • The WAL subscriber meters a partition that keeps reading empty while its readable head says entries are waiting (orleans.lattice.wal.subscriber.empty_backlog_reads) and, once that has lasted 30 seconds across at least three drains, logs at Warning and refreshes the watermark. The 30 seconds sit above twice the Azure Table provider's default 12-second phase-2 commit timeout; with a longer configured timeout the backstop can refresh during legitimate lag, which is harmless because a refresh only re-reads the stored watermark.

Leaf replay has no such backstop. Its filtered reads skip excluded entries by design, so a range a stale watermark clamped away is indistinguishable from entries the filter dropped, and detecting it would cost a storage read per replay slice on the cold-restart path. Leaf replay therefore relies on the provider's watermark being exact. See Hidden committed entries for the releases affected and the remediation after upgrading.

Batched leaf write path

Bulk-write entry points on the leaf collapse their per-key WAL grain hops into a single batched dispatch through the batched commit-log append, which the default WAL commit-log writer implementation groups by WAL partition and forwards to the WAL partition batch append. The leaf entry points that flow through this path are:

Entry point Caller
the leaf batch-write path Foreground ILattice.SetManyAsync / TypedLatticeExtensions.SetManyAsync.
The leaf's conditional batch write Foreground ILattice.SetManyWherePredicateAsync, and the predicate overloads of TypedLatticeExtensions.SetManyAsync that call it.
The leaf's batched CRDT delta apply Foreground ILattice.ApplyCrdtDeltaManyAsync, and helpers built on it such as CrdtLatticeExtensions.EnableManyAsync.
the leaf entry merge path Leaf split completion (the right half moving into the new sibling), and the bulk-load topology assembly behind ILattice.BulkLoadAsync and ILattice.BulkAppendChunkAsync, and the raw shard bulk load that tree snapshots and backup restore use.
the leaf batch merge path Every shard-level merge: replication apply, snapshot copy and restore, backup restore, tree merge, and cross-shard migration on shard split, online reshard and shard consolidation (including writes shadow-forwarded during a split).

For an N-key batch routed to a single WAL partition the grain-hop count drops from O(N) to one. Multi-partition batches fan out one batch append per touched partition and the writer reassembles the dense per-input offsets in input order. The whole batch coalesces into a single provider flush when it fits inside the WalMaxBatchEntries / WalMaxBatchBytes window; larger batches cut over across multiple flushes using the same in-flight cap as single-entry append. A partition group of exactly one entry still takes the WAL grain's interleaving batch append rather than its exclusive-turn single append (WalBatchedSingleEntryAppends, default true), so a wide fan-out of one-entry slices does not serialise on the partition. The same option routes every point append - the leaf's point sets and deletes and their conditional forms, CRDT merge apply, pending-transaction staging and inline saga terminal records - through the batch append as a one-entry batch, so WalMaxPendingBatches pipelining and WalAppendCoalescingInFlightThreshold coalescing engage for them too instead of each point append holding the partition for a whole provider round trip. Setting it to false restores the exclusive-turn dispatch for both shapes.

The orleans.lattice.leaf.write.duration histogram records one sample per batched dispatch on the merge channel (kind=merge) rather than one sample per entry, so percentile reads of the merge channel are not biased by batch size.

Activation recovery

On activation the WAL grain calls IWalStorageProvider.ReconcileAsync, then IWalStorageProvider.GetHighestOffsetAsync, and resumes assigning offsets at highest + 1 - or, when a flush this silo abandoned is still in motion, past the end of that flush's window, so a reissued offset can never collide with a late landing (issue #5799; the post-failure resync below applies the same rule). The persisted log is the single source of truth for the next-offset counter - the grain's only grain state is its wal-floor row, which holds the clock floor and the partition's incarnation, not an offset.

Deactivation drain

On deactivation the grain awaits every in-flight flush in chronological order and then triggers (and awaits) a final flush of any remaining pending entries, so a graceful deactivation never leaves a caller observing a hung TCS regardless of the configured WalMaxPendingBatches.

The drain is bounded by WalDrainBudget (default 75 seconds = 5 * WalFlushTimeout). At drain entry the per-activation drain CancellationTokenSource is signalled - every in-flight flush has already linked its per-flush deadline into this source at construction time, so a co-operative provider's AppendEncodedBatchAsync cancellation token cancels in one shot and the flush surfaces a TimeoutException routed through the normal failure handler. The chain is then awaited to settle naturally for up to the budget; any slot that has not unlinked when the budget expires is force-faulted with a typed TimeoutException faulted onto every parked ack TCS so callers are released rather than parking through the rest of host shutdown. The orleans.lattice.wal.shard.drain.budget.expirations counter and orleans.lattice.wal.shard.drain.budget.force_faulted_slots histogram (both tagged tree and shard, where shard carries the WAL partition index) attribute every budget-driven force-fault per partition.

This bound defends against the saturating-storage-account wedge: when the provider call's await is parked behind an SDK retry loop in pre-attempt back-off, the per-flush WalFlushTimeout may not fire promptly (the SDK observes cancellation only between attempts, not during back-off), so without the drain budget a chain with N in-flight slots could hold the deactivation indefinitely. With the budget the chain settles within bounded time of the SIGTERM regardless of whether the underlying provider is healthy. Set WalDrainBudget to InfiniteTimeSpan to disable the ceiling and restore the historical unbounded-drain behaviour.

Writer-side drain at host shutdown

The shard-grain deactivation drain above bounds the shard-side shutdown surface: it releases callers parked inside the WAL partition flush waiting on a provider call. A symmetric writer-side drain surface exists for callers parked one layer up, inside the writer partition admission wait waiting on the per-(tree, partition) admission semaphore.

The library handles this automatically: the WAL commit-log writer exposes a per-silo drain entry that the host's StopAsync lifecycle stage invokes via a registered IHostedService. The drain signals every caller parked on that admission wait on the owning silo's writer; each parked caller surfaces a typed LatticeShuttingDownException (a sealed InvalidOperationException subclass whose message names WalDrainBudget for grep-attribution and whose InnerException preserves the legacy TimeoutException(WalDrainBudget) shape so existing diagnostic tooling continues to work), and a counter sample lands on orleans.lattice.wal.writer.append.drain.releases tagged with (tree, partition). Post-drain single and batched appends on the draining silo fail fast with the same LatticeShuttingDownException rather than blocking on a drained admission gate. See API Reference - Shutdown back-pressure for the caller contract.

The drain is per-silo, local-only. Each silo process in a multi-silo cluster has its own WAL commit-log writer singleton with its own drain state; a drain on silo A does not touch silo B's admission semaphore and does not interrupt any in-flight WAL partition seam activation that silo B is dispatching to. Rolling restarts settle cleanly because each silo drains its own writer independently when its turn arrives. The writer-side drain complements the shard-side WalDrainBudget force-fault path: together they bound the silo shutdown end-to-end so a saturated silo terminates inside its bounded deactivation drain instead of needing SIGKILL (the wedge phenotype documented in benchmark/azure-throughput/throughput.md section 32.6).

Append-failure semantics

A flush failure is fail-fast for every affected caller:

  1. A sticky-failure latch is set the moment any flush in the chain throws. New appends (and the cutover loop's in-progress waiters) short-circuit with that exception until the post-failure resync clears the latch, so a fault that already faulted later windows is never masked by a fresh successful append. The fault that sets the latch is logged once, at Warning, with the failed window, whether its outcome is unknown and the shard's abandoned windows still in motion; the appends it refuses while latched are not.
  2. Every TCS in the failed window is faulted with the underlying storage exception.
  3. Every TCS in every later in-flight window is faulted with the same exception. Their provider calls may still be in motion - the chain waits for them to settle - but their result-setting is short-circuited so they never produce a success that contradicts the failure latch.
  4. Every TCS in the currently-accumulating pending batch is faulted - those entries had been assigned offsets above the failed window, so their offsets are logically orphaned.
  5. Once the chain drains, the grain calls IWalStorageProvider.ReconcileAsync and then re-reads IWalStorageProvider.GetHighestOffsetAsync to recover the provider's real tail. Concurrent later flushes may have already committed against now-orphaned offset windows; the resync restores the dense- offset invariant against the provider rather than against the failed window's start. The sticky-failure latch is then cleared and new appends resume.
  6. If the resync itself fails (or exceeds WalFlushTimeout), the latch stays set and the grain requests its own deactivation, so the next activation re-runs the activation-time reconcile instead of the shard refusing every append until the silo restarts.

The faults of steps 2-4 are delivered only after the resync of step 5 has run, so a caller that retries immediately observes a resynchronised grain.

This contract makes WAL-append failures observable inline at the originating writer rather than being silently coalesced into a later batch.

Contributor note - synchronously-completing providers. The flush body starts by yielding to the scheduler, so the task it returns is observably incomplete by the time the flush is stored on its in-flight slot. Without that yield, an IWalStorageProvider whose AppendEncodedBatchAsync returns a synchronously-completed task (the in-memory provider's does, through the default implementation that delegates to its synchronous AppendBatchAsync) would run the entire flush body inline before the slot is fully initialised, including the slot's removal from the in-flight chain on exit - and the chain invariant ("every in-flight slot carries a task that completes when its provider call settles") would be violated. Any future refactor of the flush loop must preserve this yield, which WalFlushPreflightTimeout bounds.