Dispatch and windows
Queues

Dispatch and windows

How a node's dispatcher deals a queue's ranges to seats, and how seats share the node's queue memory.

A seat is the part of a node that delivers one range of a queue: it reads the range, keeps its unsettled messages, and deals them, handing each to a worker under a claim. Each range has at most one seat at a time, and the epoch in the range's state row proves which one. A node keeps state for a queue only while a worker reaches the queue there. Every seat's memory is bounded by its window and by the node's window budget, so no queue can take the node's memory.

Where it lives

File in internal/queueWhat it holds
dispatcher.go, attend.go, dealt.goThe dispatcher: ring seat, passes, news, attended queues, dealt ranges
seat.go, seats.go, release.goOne seat per range, its takeover, and the node's set of seats
window.go, holding.go, class.go, budget.goThe ready window, entry charges, classes of work, the dispatch budget
share.go, giveback.go, pages.goThe window budget: shares, borrowing, give-back, cold pages
isolation.go, passes.goNoisy-key isolation and the two passes of a sealed range
internal/transport/grpc/queue/claim.goOne-shot claims

The data

RecordWhereWritten by
Dispatch index1,024 shards; each range filed under the shard its id hashes toCreate, split, merge, prune
News rowOne per changed range, in 16 groupsWhoever files, removes, moves, or reconfigures a range
Range state rowqueue/{queue}/r/{range}/state: ack frontier, bitmap, epoch, holder, released, drained, noisyOnly the range's seat. See Seat lifecycle.
Dispatcher seatA membership record tied to the node's metadata store sessionThe dispatcher

Passes and news rows

The dispatcher's ring gives each of the 1,024 dispatch shards to the live node with the highest rendezvous score. Every 5 seconds, and at once when a node joins or leaves, a dispatcher runs a pass. A pass reads the ring and the news, and nothing else, so an idle pass costs the same however many queues exist.

Hold the ring seat, read the ring Owned shards by rendezvous score Lost shards: end their seats in order Save the frontier, mark the range released Gained shards: read attended queues' maps, 16 at a time Read the index rows of their ranges Deal the ranges, open seats for open sessions Take over: wait for the release, then CAS the epoch Read the 16 news groups Act on each range's news Delete each news row at the version read Dispatcher Metadata store Seats
One dispatcher pass. Lost shards end their seats in order before gained shards are dealt.
internal/queue/dispatcher.go
func (d *Dispatcher) pass(ctx context.Context) {
	owned, ok := d.owned(ctx)
	if !ok {
		return
	}

	shards := make([]int, 0, len(owned))
	for shard := range owned {
		shards = append(shards, shard)
	}

	d.seats.Own(ctx, shards)
	d.follow(ctx, owned)
}

A news row, named after a range, says the range changed. A writer leaves one when it files the range in the index or removes it, changes its place in the queue's map, or changes its queue's settings. A range that changes twice has one row. For each range under a shard the node owns, the dispatcher reads the range's index row and acts:

The rangeWhat the node doesThe news row
Dealt here and still filedIts seat, if open, reads the queue's settings and its map entry once. The queue's work sessions read its dispatchers again and send a dispatchers frame if the set changed.Deleted
Dealt here and no longer filedThe range leaves the dealt ranges, and its seat ends in orderDeleted
Not dealt here and not filedNothingDeleted
Not dealt here, filed, and named by its queue's mapWhen the queue is attended here, the range is dealt and seated for its open sessionsDeleted
Not dealt here, filed, and not yet named by its queue's mapNothingLeft for the next pass

The dispatcher deletes a news row at the version it read, so a later change keeps its row. News of another node's range is left for that node. A split or merge files its new ranges before the queue's map names them, and a create files its ranges before its stream row exists, which is why the last row's news is kept. Every filing is a step of a sequence that is retried to its end, and each run writes the news again. Nothing reads the index on a timer.

Attended queues

A node keeps state for a queue only while the queue is attended there. That starts with the first work session or one-shot claim of the queue on the node. It lasts until the last session has closed, the last seat has ended, and no range is waiting out a failure pause. An unattended queue costs the node no range, goroutine, timer, or read.

A work session's open reads the queue's stream row, settings, map, and dead-letter stream, in four point reads. The open hands the map to the seats, which deal the ranges under the node's shards. An open range is dealt at once. A closed range is dealt only while it is still filed, which one point read of its index row tells. The open that makes a queue attended reads its map once more after its session holds the queue, to catch a split whose news the node acted on while nobody attended it. Later opens read no map, unless the queue is stale: the node gained shards while no session of the queue was open.

While a queue is attended, the node keeps its address, its dealt ranges, the ranges known to have left dispatch, and its seats. A dealt range costs about 160 bytes. An open that finds no range of its queue under the node's shards is refused with the node that delivers the queue, or UNAVAILABLE while the directory names only this node.

A seat

One goroutine owns a seat's state. Sessions and the transport send it commands. A seat opens when its range is needed: a work session or one-shot claim of its queue opens here, or the node deals a range of a queue with a session already open.

The seat then takes over the range. If another live node's seat holds the range unreleased, it waits for the release, up to 2 seconds. It then increments the epoch in the state row with a compare-and-set, sets itself as holder, and starts reading from the ack frontier. Every claim carries the epoch it was dealt under:

A claim on the wire: 44 bytes, big endian
range id (16) | position (8) | attempt (4) | epoch (8) | deadline, unix ms (8)

Only the seat writes its state row, one save at a time. Routine saves run off the seat's goroutine. Saves that decide what happens next, at a purge, an isolation, or the seat's end, run on it. A save that finds an unexpected version reads the row. A row of the seat's own epoch is its own earlier save whose answer was lost, so it saves again. A row of another epoch means a newer seat replaced this one, and this seat ends. So a seat with nothing to save can keep dealing under an old epoch until its dispatcher closes it at the next pass.

The ready window

The ready window holds an entry for each message the seat has read and not settled, ready and claimed. An entry is the message's position and the fields the seat deals by: size, routing key and its hash, message id, attempt, times, and its claim row. It never holds the record. From the moment it is read, an entry is charged what it costs once claimed, 512 bytes plus its key and id, so dealing it needs no new room.

Ready messages are grouped by routing key, and the seat deals by deficit round robin. Each key earns a 64 KiB quantum per round and deals while its balance covers its next message:

internal/queue/window.go
	for {
		q := w.round[0]
		head := q.msgs[0]

		if q.deficit < head.size {
			q.deficit += w.quantum
			w.round = append(w.round[1:], q)

			continue
		}

		q.deficit -= head.size

A key at its key_concurrency leaves the round until one of its claims ends. A key-ordered queue uses a cap of one, and also holds the key while a failed message waits. A message is dealt only once its record is held. A key whose next message has no record sits out the round and keeps its balance. The seat still tells its sessions that messages wait, so workers grant the credit that makes it fetch.

The window also filters repeats. It keeps the (message id, attempt) of every message it holds and skips a second copy. A repeated send or a fire that ran twice can append one. With the memory dedup policy, the seat remembers the ids of idempotent sends for 5 minutes, under a node-wide budget of 1,048,576 ids. A durable queue checks them against rows instead, as durable dedup describes.

The window budget

A node's window budget, WindowBudgetBytes (512 MiB), bounds the memory all its seats hold, counted as heap. That covers entries, read-ahead, records on their way to workers, fetches out, the rest of a read's batch, and room reserved for cold pages. Part of it, the fetch pool, is kept for the fetches of seats with nothing they can deal: 64 reads × 1 MiB, at most an eighth of the budget. The seats share the rest.

How seats share the budget

A seat is active while it has a worker or holds anything. Each active seat is owed an equal share of the shared part. A seat that asks for room gets it by these rules:

internal/queue/share.go
	if held+n > s.limit(share) {
		s.served()

		return false
	}

	if total := b.used(); total+n <= b.max-b.headroom || held+n <= share/2 && total+n <= b.max {
		s.served()

		return true
	}

	if held < share {
		s.want()
	}

	return false
  1. Until the node holds seven eighths of the shared part, any seat may grow to its WindowBytes. Holding more than its share is borrowing.
  2. The last eighth is kept for seats holding under half their share. Each may take up to half its share there, so a seat that has just become active always finds room.
  3. A seat refused while it holds under its share is wanting. While any seat wants, every seat's limit is its share. At its next save, a seat above its share gives back read-ahead, the latest in deal order first. If it still holds more than its share by over an eighth of it, it gives back ready entries from its highest position down, at most once a second, and reads them again later. While it is at its limit, it deals a new claim only if it holds none.
  4. A seat with nothing it can deal, whose fetch the rules refuse, fetches into the pool. A seat holds less than one fetch's worth (1 MiB) plus one record of the pool, counting records not yet sent and claims waiting for their rows. So the pool serves at least half as many seats as the node has fetch reads, and about as many with small records. Before a fetch is fitted to what is left, the seat lets go of the pool's records for keys at their cap.
  5. A seat stops wanting when its want is met, when it has no worker, or when its read is waiting or paced with no fetch due. A seat at its own limit is full, not wanting.
At the defaultsValue
The fetch pool64 MiB
Shared by the seats448 MiB
Where borrowing stops: seven eighths392 MiB
Where cold pages are sized down: three quarters336 MiB
One seat alone on the nodeIts whole 8 MiB window
The share of each of N active seats448 MiB ÷ N
The smallest share, at 8,192 active seats56 KiB, about 100 messages

A seat gives back only read-ahead and ready entries it read and never dealt. Claims, records on their way, and messages handed back stay: a handed-back message's attempt is known only to the seat. It reads what it gave back again in reads sized to its room, while its subscription waits where it stood. A seat that gave back entries then holds to its share until the node has gone 10 seconds with no seat wanting, so it never borrows back at once what it gave. An idle seat held open past its idle time gives back its ready entries too.

The node can hold a little past the budget: a read's batch is charged whole when its first piece is taken, and a cold page can arrive larger than its reservation.

Credit, classes, and readiness

A range's work has a class. An isolated range, one whose span is a single routing hash, turns leftover when its window is full, and stays leftover until the window has nothing left to deal. A window is full when it holds its limit less its read-ahead room, or when its read has stood held for HoldFull (10 seconds). Every other range is quiet. The hold keeps the class from changing with every message read, since each change cancels credit.

A session keeps unspent credit per class. A seat takes credit of its own range's class only, and only when it has a message to deal. Each seat tells its sessions when it has messages no credit has bought, and in which class. When a class stops being ready, the session cancels its unspent credit in both classes and raises its generation. Work sessions gives the worker's side.

Within one node, a queue's leftover seats are held back while its quiet seats have messages waiting. A leftover seat makes one claim for every nine the quiet seats make (LeftoverShare, one in ten), and can bank at most 8 claims it earned. With no quiet seat waiting, a leftover seat deals against every leftover credit it is granted. Across nodes, the worker chooses through the credit it grants.

The dispatch budget

With ClaimsPerSecond set, a node's seats share one budget of claims, checked before a seat takes a credit, with a floor per seat. Node bounds gives its rules.

One-shot claims

A one-shot Claim is a short work session with every node that deals the queue:

Claim max 10, wait 5 s Take a claim-wait slot, read the dispatchers Open a one-shot session on its own seats Open a WorkSession as the caller ready: quiet work waits credit: n = 10 claim frames The claims gathered Caller Receiving node Other dispatcher
A one-shot claim. Credit goes to one node at a time, so the nodes together never deal more than the claim asked for.

The receiving node opens one session on its own seats, in process, and one WorkSession with each other node, as the caller. It grants credit only to a node that reports waiting messages, one node at a time, quiet credit first. It grants leftover credit only once every node has reported and none has quiet work. The records a claim gathers in process count against their seats until its answer is handed back.

A claim with a wait, on a queue no node deals yet, looks again every 250 ms while its wait lasts. If the caller has gone by the time the answer is ready, the claim nacks every message as unattempted, and each is dealt again at once with the attempt it had. A caller that hangs up while gRPC writes the answer goes unseen, and its claims run to their deadlines.

Ack, Nack, and Extend are settled at the seat of the claim's range. When that seat is on another node, the call goes one hop, as the caller, to the node the ring names, marked so that node answers from its own seats.

Isolating a noisy key

The seat counts its window's bytes per routing hash, and judges at each save:

internal/queue/isolation.go
func (s *Seat) noisyHash() (uint32, bool) {
	switch {
	case s.holdsLimit() || (s.inHand == 0 && !s.starRoom(entryCharge)):
		return mostOf(s.byHash, s.sizes, s.opts.NoisyShare)
	case s.heldLong() && s.lately.total >= s.aheadTarget():
		return s.lately.most(s.opts.NoisyShare)
	default:
		return 0, false
	}
}

A window at its limit, or a node with no room for one more entry, is judged on its bytes per hash. A read held for HoldFull that has dealt at least its read-ahead target meanwhile is judged on a sample of the 16 hashes it dealt most. Either way, a hash holding more than half is noisy. A range whose span is already one hash is never judged.

one hash holds over half split refused the split seals the range end of range, QuietDrained saved end of range Open Noisy QuietPass NoisyPass Drained
  1. The seat writes Noisy {hash} to its state row, then asks the range duties for a split at [hash, hash + 1). It asks again every 30 seconds until the map shows the split. A refusal (one_hash, outside_span, map_cap, or max_isolated) is logged and counted, and the key stays in its range.
  2. The split seals the range and opens its children, one of which spans only that hash.
  3. In the quiet pass, the sealed range's seat writes Started and QuietFrom, its frontier at that moment, and drops the noisy hash's ready entries. It reads to the end of the range and deals every message except the noisy hash's.
  4. At the end, it saves QuietDrained and moves the frontier back to QuietFrom in one write. The seat ends and is seated again at once.
  5. In the noisy pass, the new seat reads from QuietFrom and deals only the noisy hash's messages. At the end it saves Drained.

Both passes share one frontier. Moving it back to QuietFrom drops what the row knew of the noisy hash's acks above that point, so a noisy message acknowledged before the noisy pass can be dealt again in it. A range sealed by any other change is dealt whole, and its Noisy mark is cleared.

Crash points

Crash afterState left behindWhat the re-run does
A pass acts on news, before deleting the rowA news row for done workThe next pass acts again, which converges, and deletes it at the version it reads
A shard moves, before the old seat releasesA state row held, not releasedThe new seat waits up to 2 seconds, then takes over by epoch. The old seat finds the new epoch at its next save and ends.
Noisy is written, before the split requestA marked range with no splitThe seat asks again at its next save, every 30 seconds
The quiet pass ends, before the frontier moves backQuietDrained not yet savedThe pass is saved in one write with the frontier, so the seat repeats the quiet pass from its frontier

Concurrency

While the ring changes, two nodes can both believe they own a shard, and both may deal the same range for a moment. The epoch settles it: every save and every persisted claim row names the seat's epoch, and the seat with the older epoch ends at its next write. Memory claims of the older seat are refused SEAT_MOVED and dealt again.

Bounds and signals

Node bounds lists every limit. Metrics:

  • nova.queue.window.held, by part, and nova.queue.window.share
  • nova.queue.ranges.isolated and nova.queue.ranges.leftover
  • nova.queue.isolations.refused, by reason
  • nova.queue.maps.read, by reason, and nova.queue.deals

Log lines:

  • queue: dispatcher joined the ring
  • queue: the star's dispatch shards changed
  • queue: a seat below its share was refused; seats above their share give memory back
  • queue: isolating a noisy key into a range of its own
  • queue: a noisy key is not isolated; it stays in its range
  • queue: a range sealed to isolate a noisy key is dealt in passes

Tests

  • Dispatch: TestDispatchShardsMoveWithMembership, TestADispatcherFollowsTheNews, TestNewsOfAnotherStarsRangeIsLeftForIt in dispatcher_test.go; TestAGainedShardSeatsTheSessionsOpenOnIt in attend_test.go.
  • Sharing: TestActiveSeatsShareTheBudgetEqually, TestTheLastEighthIsKeptForASeatThatHoldsLittle, TestASeatRefusedBelowItsShareHasBorrowersGiveBack, TestTheFetchPoolKeepsSeatsDealing in share_test.go; TestSlowQueuesDoNotStarveAHealthyOne in windowbudget_test.go; TestGivingBackDoesNotThrashUnderSteadyContention in giveback_test.go.
  • Classes: TestLeftoverWorkIsDealtItsShareBehindQuietWork, TestAClassTurningFalseCancelsCreditOfBoth in class_test.go.
  • Isolation: isolation_test.go, TestASealedNoisyRangeIsDealtInTwoPasses in passes_test.go, TestAReadHeldAtItsTargetJudgesANoisyKey in paced_test.go.
  • One-shot claims: TestAOneShotClaimOpensSeatsAsASessionDoes in lazy_test.go.

Go deeper

Why queues are built this way: Queues on streams.

On this page