WAL, slots and ledgers
How a node commits flights to object storage as numbered slots and acknowledges them in order.
A node's WAL is its write-ahead log in object storage, one per storage class. The WAL acknowledges a flight only when its slot holds W copies and every earlier slot of the same ledger has been acknowledged. Each slot is written at most once in each bucket, so the acknowledged slots of a ledger run from slot 0 with no gaps.
A flight is a group of batches from many streams, written as one object. A slot is one flight's numbered position in the WAL. A ledger is a run of slots written by one writer under one number, its epoch. A WAL is a sequence of ledgers. Each slot is written to the K buckets of its class's bucket set: one standard bucket, or one express bucket per availability zone. The slot is committed once W of them, the copy quorum, hold the flight. W is 1 on Standard and 2 by default on Express. The glossary has every term.
Where it lives
| Package | What it owns |
|---|---|
internal/storage/durability | The write core of one class: the pool, the flusher that cuts flights, the flight index, and the live indexer loop |
internal/storage/wal | WAL: the mint, Publish, the backlog budget, the in-place roll, the open gate, and the release flush |
internal/storage/loglet | Sequencer (slot numbers, the fan-out to K buckets, in-order release) and the static half: Fence, Walk, Trim, ProbeGarbage. It never touches the metadata store. |
internal/storage/indexer | Absorber, which turns committed slots into span rows, and ledger recovery |
internal/metadata (ledgers.go) | Ledgers: the mint counter and the ledger records, all changed by CAS |
internal/objectkey | WALSlot, which derives a slot's key |
The write core builds one WAL per class. Standard and Express run the same code over a different bucket set. See Storage classes inside.
The data
Slot keys
Every slot key is derived from the ledger record, so no reader lists a bucket to find a slot. The ledger records its slot layout when it is minted, and every reader derives keys from that record:
| Layout | Key | Used by |
|---|---|---|
hashed | wal/<h>/<star>/<epoch>/<seq> | New Standard ledgers (the default of --wal-key-layout) |
star | wal/<star>/<epoch>/<seq> | Express ledgers, and Standard with --wal-key-layout=star |
<seq> is zero-padded to 20 digits, so key order is slot order. <h> is four hex characters folded from an FNV-1a hash of the star and epoch. It gives each ledger its own place in the key space, so S3 can split partitions between ledgers. Storage layout has the whole key scheme.
The slot envelope
Every slot starts with a 60-byte envelope. One small read at offset 0 tells a reader what the slot holds, proves that it sits at the key it claims, and locates the bundle's footer:
func (e envelope) encode() []byte {
buf := make([]byte, envelopeLen)
binary.BigEndian.PutUint32(buf[0:], envelopeMagic) // "CHNE"
buf[4] = envelopeVersion
buf[5] = byte(e.kind) // 1 flight, 2 poison
binary.BigEndian.PutUint64(buf[8:], uint64(e.epoch))
binary.BigEndian.PutUint64(buf[16:], e.seq)
binary.BigEndian.PutUint64(buf[24:], e.nonce)
binary.BigEndian.PutUint64(buf[32:], uint64(e.size))
binary.BigEndian.PutUint64(buf[40:], uint64(e.footerOff))
binary.BigEndian.PutUint64(buf[48:], uint64(e.footerLen))
binary.BigEndian.PutUint32(buf[56:], crc32.Checksum(buf[:56], crcTable))
return buf
}Bytes 6 and 7 are reserved. The checksum is CRC-32C over the first 56 bytes. A flight's bundle starts at byte 60, and every offset a reference stores counts from the start of the object. A poison slot is the envelope alone: the marker a fencer writes so that a slot can never commit. The nonce identifies the writer. A Sequencer draws a random one when it opens, and a fencer draws its own.
Slot lifetime
Every write to a slot is a create that fails when the key exists, so a slot is written at most once in each bucket. A slot ends in one of two states, and neither can change:
| State | Holds in its K buckets | Then |
|---|---|---|
| Committed | W or more flight copies | Kept until the indexer has absorbed it and denorm has copied every stream out of it. The auditor's trim-check then deletes it from every bucket and moves the ledger's trimmed cursor past it. |
| Dead | K−W+1 or more poison envelopes | Kept until the star is decommissioned |
The two states cannot overlap: W flight copies and K−W+1 poison envelopes do not fit in K buckets. Epochs and fencing shows how a fence drives a slot to one of them.
The ledger record
A ledger has one record at ledgers/<star>/<epoch> in the streams keyspace. Its constants are fixed when the ledger is minted. A WAL that needs other settings rolls to a new ledger instead of changing one.
message Ledger {
LedgerState state = 1; // OPEN, FENCED, INDEXED
uint64 checkpoint = 2; // first slot the indexer has not absorbed
uint64 trimmed = 5; // slots below it are deleted
uint64 rewritten = 8; // slots below it hold no live refs
uint32 storage_class = 9;
uint32 quorum = 10; // W
repeated string bucket_zones = 11; // the bucket set, in fixed order; K = len
uint32 window = 13; // the pipeline bound
optional uint64 cut = 14; // present once fenced
uint64 absorbed_bytes = 15;
uint32 slot_layout = 16;
}The three cursors only move forward, each by CAS. Neither rewritten nor trimmed may pass the checkpoint, and the trim-check deletes slots only below rewritten. The star's mint counter sits at ledgers/<star>. It holds the last epoch, the head epoch of each class, and a writer record per class. Epochs and fencing explains the mint.
Committing a flight
- The first use mints.
WAL.initmints the ledger by CAS on the mint counter, then fences every unindexed ledger of the same class that an earlier process left. The daemon calls it throughPrimebefore the node registers, so a crashed ledger is already superseded when the node first looks alive. - The flusher cuts a flight from the pool once 8 MiB has gathered (
--s3-bundle-size-mib), or once the oldest byte has waited 200 ms on Standard (--s3-bundle-batch-interval) or 25 ms on Express. One flusher per class hands flights toPublishone at a time, so slot order is the order of arrival. Publishtakes a backlog token. The token is held until the indexer absorbs the flight. When none is free,Publishcounts a stall and waits until the flight's deadline.Sequencer.Nextassigns the slot. It takes a window permit (128 by default,--s3-parallel-uploads), gives the flight the next sequence number, and starts its upload with a 30-second budget.- The slot fans out. The upload sends one
PutIfAbsentper bucket, in parallel, each body a fresh reader over the same bytes. - The quorum decides. W confirms commit the slot. Once more than K−W buckets have refused, the slot fails and the ledger halts.
- Acknowledgements release in slot order. A finished slot waits until every earlier slot has released.
- The indexer absorbs. It writes metadata for the acknowledged flights and moves the checkpoint, which frees their backlog tokens. See Indexing.
The quorum loop counts each bucket's answer as it arrives:
for range k {
out := <-results
switch out.kind {
case attemptConfirmed:
confirms++
if confirms >= a.cfg.Quorum {
return nil
}
case attemptForeign:
denied++
foreign = out.err
case attemptFailed:
denied++
failure = out.err
}
if denied > k-a.cfg.Quorum { /* the quorum is out of reach */ }
}The release is a cursor that only moves over finished slots:
func (a *Sequencer) advanceLocked() {
for {
if a.halted && a.released >= a.haltSeq {
return
}
next, ok := a.pending[a.released]
if !ok || !next.finished {
return
}
next.done <- next.result
<-a.window
delete(a.pending, a.released)
a.released++
}
}When a create's answer is lost
An answer can go missing after the object has landed. On any failed create, send reads the slot's envelope back and decides what happened:
| What the envelope read finds | Verdict |
|---|---|
| A flight with this writer's nonce | Confirmed: the create landed and only the answer was lost |
| Any other envelope | Foreign: a fencer or another writer holds the slot, and the ledger halts |
| Nothing, and the create was not a conflict | Failed: nothing landed in this bucket |
| Anything else | Unresolved: counts against the quorum |
A throttled create is sent again when the bucket's throttle gate admits it, until the slot's 30-second budget runs out. A slow partition costs latency and leaves the ledger open. A bucket whose upload permits are all in use is skipped for this slot and counted as failed. Only real confirms count toward W, so skipping a slow minority is safe.
When a ledger halts
A slot that cannot reach its quorum halts its ledger. The first failure latches the halt: that slot and every later one resolve with ErrEpochHalted, and no acknowledgement at or after it is ever released. Slots below it can still finish. A halted ledger never resumes. The WAL rolls to a new ledger in place:
The roll runs in three phases:
- Quiesce. It aborts and closes the halted sequencer, then waits until every in-flight publish has resolved or parked. The set of parked flights is then final.
- Settle. It fences its own ledger from the checkpoint and publishes the cut by CAS. A parked flight below the cut is committed, and its acknowledgement is only late. A flight at or above the cut was never committed in this ledger, so it is republished.
- Turn over. It takes a token from the roll pacer, mints the next ledger with
MintNext, installs a new sequencer, and republishes the parked flights in order.
for _, pf := range *remaining {
if pf.epoch == from && pf.seq < cut {
pf.resolve(t.resolutionAt(nil, from, pf))
continue
}
republish = append(republish, pf)
}Fencing before minting keeps the roll free of duplicates. Each flight lands in exactly one ledger's coverage, so no sequence number is committed twice. Producers usually see a pause and no error. A parked flight whose deadline passes before the new ledger is minted fails with ErrPublishDeadline, and so does every flight parked after it. None of them was published, so sending them again cannot duplicate a record. While the roll runs, Publish waits at the WAL's gate, and the stall is counted as rolling, or as roll_pacer while the roll waits for a token.
MintNext refuses the roll when its class's head epoch has moved, or when recovery has revoked the head. Either means a successor owns this star's writing, so the WAL is deposed: it becomes terminal and fails its parked flights. Any other failure retries the phase. Each attempt has 60 seconds, and attempts are spaced 0.5 to 1.5 seconds apart, so stars that roll through one outage do not retry their fences together.
The halt's cause labels the roll: foreign_occupant, throttled, probe_unresolved, put_failed, or unknown when the halt recorded no cause.
Indexing acknowledged records
The indexer turns committed slots into per-stream metadata. Its one operation, absorb, takes a dense run of a ledger's slots that starts at the checkpoint. For each stream in the run, it writes one span ref: a row keyed by the stream's first sequence number in the run. The row lists, for each slot, the slot number, the first sequence number, the footer range, and the bytes. It also holds the epoch, the slot layout, the time bounds, and the stream's running byte total. Absorb then advances the checkpoint by CAS. It writes metadata only and never reads object storage.
spanCommits, objects := buildSpans(slots, dead, b, c.cfg.Class, status)
outcomes, err := c.commitBatch(ctx, b.Epoch, spanCommits, objects)
if err != nil {
return 0, fmt.Errorf("indexer: ledger %d: %w", b.Epoch, err)
}
adv := metadata.CheckpointAdvance{From: checkpoint, To: slots[len(slots)-1].Seq + 1, Bytes: slotsBytes(slots)}
if err := c.advance(ctx, b, adv); err != nil {
return 0, fmt.Errorf("indexer: ledger %d: %w", b.Epoch, err)
}commitBatch writes each stream's row with a create-only put, up to --absorb-fanout streams at a time (4,096 by default). The aftermath then arms one denorm batch marker for the run and the streams' retention checks. A span for a stream that was deleted meanwhile is dropped, and the batch goes on. See Stream objects and denorm for the marker.
The live indexer runs on the leader. The release path wakes it each time a flight joins the flight index. One round takes at most 512 slots, and one pass has 60 seconds. --absorb-pass-interval sets a minimum gap between passes, so more slots share each row. A publish that finds the backlog full skips that gap. Ledger recovery runs the same Absorber over a stopped ledger, 32 slots at a time.
| Crash after | State left behind | What the re-run does |
|---|---|---|
| Some span rows commit | Rows for part of the run; checkpoint unmoved | Commits the run again; each existing row is found and counted as covered |
| All span rows commit | Every row; no marker; checkpoint unmoved | The same, then arms the marker it finds missing |
| The aftermath | Rows and the marker; checkpoint unmoved | Commits again and re-arms the marker, which converges on the same key |
| The checkpoint advances | Nothing left to do | denseFrom drops every slot below the checkpoint and returns |
Crash points
A WAL lives in one process. When the process stops, the next start of the same node, or another node's recovery, finishes the work:
| Crash after | State left behind | What the next start does |
|---|---|---|
| The mint counter CAS | A head epoch with its record reserved in the counter, not yet created | Any reader of the counter creates the reserved record (materializeHeads) before it mints or recovers |
| Some slots commit, before their acknowledgement | Committed slots past the checkpoint | The new process fences the old ledger, so those slots stay below its cut and are absorbed. The producer's retry may append them twice. |
A roll's fence, before PublishCut | Poison at the cut; no cut recorded | Any fencer reaches the same cut, and the first publish wins |
A roll's PublishCut, before MintNext | A fenced ledger, still the class head | The restart mints past it and recovers it like any fenced prior |
MintNext, before republishing | An empty new ledger | The restart fences it at cut 0; a prior whose cut equals its checkpoint is reaped and marked Indexed at once |
A restart fences its own priors in init. A prior with nothing left to absorb, where the cut equals the checkpoint, has its garbage window deleted and is marked Indexed on the spot. Any other prior waits for ledger recovery.
Concurrency
- One writer per ledger. Only the process that minted a ledger writes its flights. The sequencer's mutex guards the slot counter, the pending set, and the halt latch.
- Slot order comes from one flusher. Each class has one flusher, and it calls
Publishin arrival order. Uploads run in parallel, and the release cursor puts them back in order. - Per-bucket upload permits. Each bucket allows
Windowuploads at once, quorum stragglers included, so a slow bucket cannot build up readers. - Stale writers. A writer that only seems dead keeps writing until it meets a poison marker. Its next create in that slot fails, it reads a foreign envelope, and its ledger halts. Recovery revoked its head before fencing, so its roll is deposed. See Epochs and fencing.
- The roll gate. While a roll runs, new publishes wait at the gate, and the parked set is settled before any slot is judged.
Bounds and signals
| Bound | Default | At the bound |
|---|---|---|
| Pool | 256 MiB per class (--s3-memory-buffer-mib) | Producers wait |
| Slots uploading at once | 128 per class (--s3-parallel-uploads) | Sequencer.Next waits |
| Backlog: flights acknowledged but not absorbed | 1,024 flights (--s3-wal-backlog-flights) and 4 GiB (fixed) | Publish waits; the stall is counted by cause |
| One slot's upload | 30 s | The slot fails and the ledger halts |
| One roll attempt | 60 s | Retried after 0.5 to 1.5 s |
| Rolls | A burst of 3, then 1 every 200 s | The roll waits for a token; publishes wait at the gate |
The Express WAL uses the same values, fixed in code. The --s3-express-parallel-uploads, --s3-express-memory-buffer-mib, and --s3-express-publish-deadline flags configure only the Express fan-out store; the Express WAL ignores them.
The backlog reports itself as pressed at three quarters of either bound. The metrics are in the metrics catalogue:
| Signal | What it shows |
|---|---|
nova.wal.backlog.age | Age of the oldest flight awaiting absorb. Alert on this. |
nova.wal.backlog.stall | Publishes that waited, by cause: absorb_lag, metastore_slow, rolling, roll_pacer |
nova.wal.slot.duration, nova.wal.boarding.duration | One slot's upload, and the wait between token and slot |
nova.wal.roll.count, nova.wal.roll.waiting | Rolls by outcome and reason; a roll waiting for a token |
nova.indexer.pass.duration, nova.indexer.phase.duration | One absorb pass, and its liveness, commit, aftermath, and checkpoint phases |
The log lines are wal: ledger minted (with priors_fenced), wal: epoch halted; rolling (with reason and cause), wal: ledger rolled in place, wal: roll attempt failed; retrying, and wal: roll failed; the WAL is terminal. A slot or a backlog wait longer than 5 seconds logs wal: slot resolved slow or wal: publish waited on the backlog budget. The stall cause metastore_slow means the last ref commit took longer than one second.
Tests
internal/storage/loglet:TestAppendAssignsDenseSeqsAndReleasesInOrder,TestReleaseOrderSurvivesOutOfOrderCompletion,TestQuorumAckSurvivesOneBucketDown,TestQuorumMinorityPoisonLosesTheRace,TestGhostPutResolvesByOwnNonce,TestForeignOccupancyHaltsTheEpochPermanently,TestThrottledSlotGivesUpAtItsBudget,TestEnvelopeEncodesTheGoldenLayout.internal/storage/wal:TestFirstPublishMintsAndCommitsInOrder,TestBacklogBlocksUntilRetired,TestRollAcknowledgesLateBelowTheCut,TestRollDeposedShedsTerminally,TestRollPacerBoundsCascades,TestRestartFencesPriors,TestRestartConvergesAcrossAHalfRolledPair,TestClosedS3PartitionCostsAppendsLatencyNotEpochs.internal/storage/indexer:TestAbsorbConvergesFromAnyMidBatchCrash,TestAbsorbRefusesGaps,TestAbsorbCommitsOneSpanPerStream.tlaplus/Ledger.tlamodels the slot quorum, the fence, and acknowledgement order.