Seat lifecycle and crash safety
Queues

Seat lifecycle and crash safety

How a queue seat opens, idles, and ends, how its due keys fire, and how every queue sequence survives a crash.

A seat's progress is one state row per range, and only the seat with the row's current epoch may write it. A failed message is written as a due key before its position is settled, and every other multi-step queue sequence is ordered the same way: the durable record of what remains comes first. So a crash at any step delivers a message again, and never loses one.

Where it lives

File in internal/queueWhat it holds
seats.go, seatbound.go, idle.go, release.go, leave.goOpening, idling, closing, and ending seats
saving.go, frontier.goThe ack frontier and its saves
retry.go, expiry.goDue keys, the fire, retries, delays, dead letters, expiry
purge.go, internal/transport/grpc/queue/upkeep.goPurges and purge points
keyedsends.go, dedup.goIdempotent sends under durable and memory dedup
internal/metadata/queuedispatch.go, queuekeyed.goThe rows and their compare-and-set

The data

RowKeyHolds
Range statequeue/{queue}/r/{range}/stateAck frontier, a bitmap of positions settled above it, epoch, holder, released, drained, and the noisy-key fields
Due keyqueue/{queue}/r/{range}/due/{readyAtMs}~{id}~{attempt}Position, attempt, routing key, and whether it is a dead letter. The id is the message id, or @ and the position.
Purge pointqueue/{queue}/r/{range}/purgedThe position a purge emptied the range to. It only moves forward.
Keyed sendqueue/{queue}/keyed/{span}~{hash}Range, position, and send time of the copy an idempotency key names
Replay leasequeue/{queue}/replayThe one replay running on the queue, held up to 2 minutes

The seat saves its frontier with a compare-and-set every 250 ms, after 1,024 settled positions, and once more as it closes. One save is in flight at a time, with 3 seconds to finish. A failed save gives back what it carried, and the next one retries.

internal/queue/saving.go
func (s *Seat) rewrite(ctx context.Context, sv *saving) (metadata.RowVersion, error) {
	st, version, err := s.rows.RangeState(ctx, s.r.Stream, s.r.Range)
	if err != nil {
		return 0, fmt.Errorf("queue: seat of range %v: read the state row after a save met another version: %w", s.r.Range, err)
	}

	if st.Epoch != sv.st.Epoch {
		return 0, metadata.ErrStateVersion
	}

	return s.rows.CASRangeState(ctx, s.r.Stream, s.r.Range, version, sv.st)
}

A save that meets another version reads the row. Its own epoch means its earlier save was stored and the answer was lost, so it saves again on that version. Any other epoch means a newer seat replaced it.

Idle and closing

When its last worker leaves, a seat is idle. It drops its read-ahead, reads no further, and starts its idle time, SeatIdle (60 seconds). A worker that comes back inside it, by a reconnect or a one-shot poller's next call, finds the seat as it was, with no takeover and no new read.

Once the idle time passes, the seat closes in order unless something holds it open:

internal/queue/idle.go
func (s *Seat) holdsOpen(now time.Time) bool {
	s.keyed.expire(now)

	rows := s.rw.flying || s.rw.owed > 0 || len(s.rw.records)+len(s.rw.settles)+len(s.rw.again) > 0 || len(s.ended) > 0

	return len(s.held.claims) > 0 || len(s.waitingOn) > 0 || rows || s.sv.flying || len(s.unarmed) > 0 || len(s.keyed.order) > 0 ||
		s.sending()
}

That is: claims in either claims mode, claims held past their deadline for a call on its way, claim rows to write, a save in flight, delays whose due keys are not written, idempotent ids still in their 5 minute window, and records being sent. A seat held open past its idle time gives back its ready entries, and reads them again when a worker returns.

A seat that closes saves its frontier and marks its range released, so the next seat, here or on another node, takes over at once. When the closed seat was its queue's last, no session is open, and no range is paused after a failure, the queue stops being attended.

MaxSeats (8,192) bounds the seats open on the node, idle ones included. A range that needs a seat at the bound waits, and the seat idle longest that holds nothing open is asked to close for it.

A seat that fails is paused for one pass, 5 seconds. A need during the pause opens nothing, and the pause's own timer reopens the seat if a session is still open. The paused range keeps its queue attended, so a one-shot poller cannot reopen a failing seat at its own rate.

When a seat ends

CauseWhat the seat does
The node stops or drains, or loses the shardEnds in order: saves the frontier and marks the range released. With memory claims, revokes the claims it holds.
Idle past SeatIdle, or asked to close at MaxSeatsEnds in order, as above
A read errorEnds in order, then pauses 5 seconds
A save finds a newer epochFails, with no save beyond the one already out, and pauses 5 seconds. It does not release. Memory claims are refused SEAT_MOVED. Persisted claims stand for the next seat.
A claim row write finds a row a later seat wrote, or the row goneEnds at once. It hands over nothing of that write, and gives back its claims with their credits.
Its sealed range is drained: dealt to its end, no claim out, no due key standingSaves Drained, removes the range from the dispatch index, and ends. The state row stays, so child ranges can read Drained.
A purge passed its frontierSaves its frontier at the purge point and is seated again at once
The quiet pass of an isolating split is overSaves and is seated again at once for the noisy pass
Its range is gone from the mapOnce the range is out of the dispatch index, finishes its row writes and its save, removes the range's dispatch rows, and ends. While still filed, it waits and deals nothing.

A seat that ends is removed from every session of its queue in the same step.

Before a drained seat leaves, it scans its range's due keys once and wakes its fire for any that another seat left. The fire reports a pass that found none together with the number of key writes the seat had begun when the pass started. The seat accepts the report only if it has begun none since. Without this, the retry of a sealed range's last message could be lost with its seat.

Due keys

A due key is a timer: a row under the range whose first field is when it is ripe. Three events write one:

CauseRipeWhen it fires
A failed attempt, standard queueAfter the backoff, or the nack's retry_after_msThe message is appended again with nova-attempt one higher
A delayed message read by the seatAt its not_before timeThe message is appended again without its delay, as the same attempt
A message given upAt onceThe message is appended to the dead-letter stream

The seat writes the due key, then settles the position. A crash between the two delivers the message again and loses nothing. Settling lets the frontier move past a waiting message.

internal/queue/retry.go
	for i, err := range s.rows.ArmDues(ctx, s.r.Stream, s.r.Range, due) {
		if err != nil {
			failed, why = failed+1, err

			continue
		}

		c := put[i].c
		armed[i] = true

		s.held.release(c.msg.seq)
		s.settleClaim(c)
		s.win.release(c.msg, time.Time{}, time.Time{})

On a queue with persisted claims, the claim's row is written first, then the due key, then the position, and last the row is settled as carried on. A key-ordered queue retries in place instead: a failed message stays at its key's head in the window, which keeps the order. Only a dead letter uses a due key there. A due key that cannot be written leaves its message retried in place.

The fire runs beside the seat while it reads. It sleeps until the earliest key is ripe, and wakes when any key is written. It reads ripe keys a page at a time (DueScanLimit, 256), carries a page's messages on, up to 16 at once, then resolves their keys together. On a key-ordered queue, one key's dead letters go one after another. A carry that fails fails the pass, which tries again a second later; keys already carried are still resolved.

Claim, attempt 1 Nack Write the due key Settle the position Fire: the key is ripe Read the record back Append it as attempt 2 Resolve the due key Claim, attempt 2 Worker Seat Dispatch keyspace Range
A retry on a standard queue. The due key is written before the position is settled.

Every message is carried before its key is resolved. A fire that dies between the two appends a message twice, and the window's (message id, attempt) filter drops the second copy if the first is still held. A record that retention removed before the fire reads it is expired, counted under record_gone, and its key resolved.

Retention and purge

A read that starts below the range's trim point returns the trim point instead of a batch. The seat counts the unsettled positions in between as expired, logs them once, and moves its frontier to the trim point.

A purge is separate. The node that receives it carries each range's purge one hop, to the node that deals the range, 8 ranges at a time. There, per range:

  1. The seat saves its frontier first, so the count leaves out acks answered since the last save.
  2. The purge reads the range's tail and counts what is unsettled below it.
  3. It writes the purge point, the position the range is emptied to.
  4. It trims the range to the purge point.
  5. It deletes the range's due keys in one range delete, and leaves news. Its node tells its own seats at once.

The purge never writes the state row. The receiving node carries the purge to every node that deals a range, even after one fails, and purges its own ranges. If any node failed, the call returns the first failure with a PurgeResponse detail counting what each node removed before it failed.

Last, when the purge named no ranges and nothing failed, the receiving node deletes the queue's idempotent send rows. It does so only when it deals at least one of the queue's ranges itself.

A seat reads the purge point at takeover, on news of its range, and when its read reports records gone, before it counts them as expired. That order keeps a purge from being reported as expiry.

Durable dedup

On a queue with dedup: durable, each idempotency key has a row naming the copy that is the key's message: its range, position, and send time. Rows are filed by 5 minute span, so a check is two point reads issued together: the key's span and the one before.

  • Send reads the rows first. A send within 5 minutes of a row returns that message marked deduplicated, and nothing is stored. Otherwise the message is appended, then the row is created with a compare-and-set on its absence. The append comes first, so a row never names a copy that was not stored.
  • A seat checks every keyed copy it reads against the rows, up to 64 at once, off its dealing goroutine. The copy a row names is the message. A copy within 5 minutes of another copy's row is a repeat, settled and not dealt. A copy no row names gets its row written and is dealt. That is how an SDK's idempotent append, which never calls Send, is recognized.
  • A seat that cannot read the rows deals none of the batch. It ends with its frontier saved and reopens after its pause.

The first row a node writes for a queue in a span also deletes the queue's spans before the previous one, in one range delete. Deleting the queue removes the rows too.

Crash safety

SequenceOrderA crash leavesTest
SaveCAS the state rowBefore it: the next seat resumes at the old frontier and deals again what was out, plus acks since the save. After it, answer lost: the next save finds its own epoch and saves again.TestACrashedSeatsSuccessorRedeliversWhatWasNotSaved, TestASaveWhoseAnswerIsLostDoesNotEndTheSeat
Fail a messageDue key, then settle the positionThe message delivered againTestASuccessorFiresWhatItsPredecessorLeftDue
Fire a due keyAppend, then resolve the keyThe message appended twice, the second copy dropped if the first is heldTestAMessageSentTwiceIsDealtOnce
Persisted ackSettle the claim row, then the positionA settled row the next seat readsTestAnAckOnItsWayWhenItsSeatIsLost
Durable idempotent sendAppend, then create the key's rowA copy no row names. The next send or the seat records it, or settles it as a repeat.TestAKeyedSendWhoseSenderDiedIsDeliveredOnce
PurgePer range: save, purge point, trim, delete due keys, newsA range already emptied is marked and trimmed again at its tailTestAPurgeThatStopsConvergesWhenRunAgain
Replay dead lettersTake the lease, send each letter, then trim the dead-letter stream past themLetters sent twice, none lost. The lease lapses after 2 minutes.TestAReplayThatStopsLosesNothing
An isolating split's passesQuiet pass, then frontier back and QuietDrained, then noisy passThe next seat resumes the pass it finds savedTestASeatLostInAPassResumesIt
Create a queueCheck the address, then internal streams, configuration row, index rows, then the stream rowNothing at the address until the last write. The range-intent job removes the pieces.TestRangeIntentDutyReapsADeadQueueCreation
Split a queue's rangeSeal, create children, file them, change the mapIndex rows the map does not name, which dispatchers skipTestRangeSplitDutyOnAQueueConvergesAfterDyingBetweenTheIndexAndTheMap
Prune a range retention emptiedDelete its stream, remove its dispatch rows, drop it from the mapA map entry whose stream is gone, which the next pass finishesTestScalableRetentionPrunesASealedRange

What a node cleans up

EventWhat the node does
A range closed by a split or merge is dealt to its endOnce no claim and no retry or delay of it is pending, its seat closes and the range leaves the dispatch index. A closed range that is not finished stays, and a worker's next open seats it again.
Retention empties a closed rangeRemoves the range's stream, index entry, state, claims, and due keys, then drops the range from the map. Due keys removed this way are logged as expired.
A queue is deletedRemoves its ranges, dead-letter stream, and every row it kept, in the background

A closed range that nobody consumes is not finished. It stays until a worker consumes the queue or retention removes it.

Concurrency

Only the seat writes its state row and its due keys' settles, and the epoch in the row stops a replaced seat at its next save. The fire runs on its own goroutine but begins nothing once its seat is ending, or has found a later seat on its range. A purge runs beside the seat: it saves through the seat first and never writes the state row, so the seat learns of it by reading the purge point.

Bounds and signals

Metrics:

  • nova.queue.takeovers, by how the range was found, and nova.queue.takeover.wait
  • nova.queue.messages.expired, by cause, and nova.queue.messages.purged
  • nova.queue.due_keys.unwritten and nova.queue.due.lag
  • nova.queue.keyed_sends.repeats and nova.queue.keyed_ids.shed

Log lines:

  • queue: seat opened, queue: seat closed
  • queue: seat failed; a need opens it again after a pause
  • queue: seat took its range over
  • queue: range drained: it is sealed and dealt to its end
  • queue: due messages carried on, queue: message dead-lettered
  • queue: a range was purged past its seat's frontier; the seat starts over from there
  • queue: retention trimmed a range past its ack frontier; the messages between expired undelivered

Tests

  • Lifecycle: TestAnIdleSeatClosesAndReleasesItsRange, TestATakerInsideSeatIdleFindsTheSeatAsItWas, TestAFailedSeatIsReopenedNoSoonerThanAPause, TestALostShardEndsItsSeatsInOrder, TestClaimsKeepAnIdleSeatOpen in lazy_test.go.
  • Leaving: TestADrainedRangeWithADueKeyStandingStaysSeated, TestADrainedRangeLooksForADueKeyAnotherSeatLeftBeforeItLeaves in leave_test.go; TestASeatThatEndsInOrderReleasesItsRange in release_test.go.
  • Fire: TestAKeyOrderedQueueRetriesInPlace, TestAFireThatFindsItsRecordGoneCountsAnExpiry in retry_test.go.
  • Rows: TestRangeStateIsACompareAndSet, TestAPurgePointOnlyMovesForward in internal/metadata/queues_test.go.

Go deeper

Why delivery is at least once: Queues on streams.

On this page