Work sessions

Work sessions

The gRPC stream a queue worker holds with each node, frame by frame, for writing a worker without an SDK.

A work session is a long-lived gRPC stream between a worker and one node. The worker grants credit, and the node delivers one message per credit, never more. The Go and TypeScript workers speak this protocol for you. Read this page to write a worker in another language. There is no HTTP work session: over HTTP a worker uses one-shot claims.

Open a session on a node at 127.0.0.1:8501 and grant one credit
grpcurl -plaintext -keepalive-time 10 -import-path proto -proto nova/v1/queue.proto -d @ \
  127.0.0.1:8501 nova.v1.QueueService/WorkSession
{"open": {"bucket": "apps", "key": "emails", "worker_id": "worker-1"}}
{"credit": {"n": 1, "generation": 0}}

With two messages sent to apps/emails under the routing key user-42, and the queue purged while the claim was out, the node sent:

What the node sends back, one frame per line
{"opened": {"ranges": ["01a204ae-30b5-7480-acd8-0bbc4509570d"]}}
{"dispatchers": {"ringVersion": "1683677576203226383", "dispatchers": ["127.0.0.1:8501"]}}
{"ready": {}}
{"claim": {"claim": "AaIErjC1dICs2Au8RQlXDQAAAAAAAAAAAAAAAQAAAAAAAAABAAABogSu4BY=", "message": {"body": "d2VsY29tZQ==", "messageId": "01a204ae-315c-70d2-a5e0-167f6cd28669"}, "attempt": 1, "deadlineMs": "1795374899222", "range": "01a204ae-30b5-7480-acd8-0bbc4509570d", "routingKey": "user-42", "maxDeadlineMs": "1795418069222"}}
{"ready": {"quiet": true}}
{"revoked": {"claim": "AaIErjC1dICs2Au8RQlXDQAAAAAAAAAAAAAAAQAAAAAAAAABAAABogSu4BY=", "reason": "the claim's message was purged: it is not dealt again, and nothing is owed", "refusal": "WORK_REFUSAL_CLAIM_GONE"}}
{"ready": {"generation": "1"}}

grpcurl reads one JSON frame per line and ends the session when its input closes. Nova serves no gRPC reflection, so grpcurl reads the service from proto/nova/v1/queue.proto in the Nova repository. In gRPC JSON, bytes fields such as body and claim are base64, and fields at their zero value are left out: seq is 0 here.

Where it lives

FileWhat it holds
proto/nova/v1/queue.protoQueueService.WorkSession and every frame
internal/transport/grpc/queue/work.goThe server side: open, frames, refusals, dispatchers refresh
internal/queue/session.go, calls.goA session's credit, generation, deliveries, and calls to seats
client/queue_work.go, queue_dealer.goThe Go worker
sdk/ts/packages/nova/src/worker.ts, dealer.tsThe TypeScript worker

The session

open: bucket, key, worker_id opened: ranges dispatchers: every node that deals the queue ready: quiet, generation 0 credit: n = 3, generation 0 claim, claim, claim ack: two claims extend: the third extended: its new deadline ready: nothing waits, generation 1 Unspent credit at this node is now zero Close the stream OK, after the calls already read Worker Node
A session with one node. A ready frame with a new generation cancels the worker's unspent credit.

Where to connect

A queue's ranges are dealt by one or more nodes, its dispatchers. A worker holds one session with each. GetQueue lists them as dispatchers, and each range's dispatcher, as node gRPC addresses.

The node answers the open withMeaningWhat to do
An opened frameThe session is openWait for ready
FAILED_PRECONDITION with NotOwner{holder_addr}This node deals none of the queue's ranges. holder_addr names one that does.Open the session there
UNAVAILABLE, with an empty NotOwner or noneThe node is assigned the queue but not dealing it yet, or could not read its directoryRetry
RESOURCE_EXHAUSTED with QueueLimit{limit: "max_work_sessions"}The node holds its 512 work sessions, the defaultRetry later
NOT_FOUNDNo queue at the addressStop

After opened, the node sends a dispatchers frame naming every node that deals the queue, when it can read its directory. A split or merge sends a new frame at once. A change of the ring is noticed by a 5 second refresh of a directory reading cached for up to 2 seconds, so up to about 7 seconds later. The node sends a frame only when the set of addresses changes. Open a session with each node you do not have one with. ring_version is the ring assignment's version: two frames with one version name the same nodes for the same ranges, but the same nodes can come with another version.

Keepalive pings

A node can freeze without closing its connections: a stopped process, a paused VM, a long runtime pause. Its TCP connection stays open, so a session with it neither delivers nor fails. Dial each node with HTTP/2 keepalive pings, so the connection closes when a ping goes unanswered. The session then ends UNAVAILABLE, and the worker follows the other nodes' dispatchers frames.

SettingValueWhy
Keepalive time10 sPing after 10 seconds without a frame. The SDK workers use this.
Keepalive timeout5 sClose the connection when a ping is not answered within 5 seconds
The node's minimum interval5 sA client that pings more often is closed with GOAWAY (too_many_pings). Pings are allowed while no call is open.

With these values a worker notices a frozen node about 15 seconds after its last frame. In grpc-go, dial with keepalive.ClientParameters{Time: 10 * time.Second, Timeout: 5 * time.Second}. In grpc-js, set grpc.keepalive_time_ms to 10000 and grpc.keepalive_timeout_ms to 5000. The node also pings an idle connection itself every 30 seconds.

Frames

proto/nova/v1/queue.proto
message WorkSessionRequest {
  oneof frame {
    WorkOpen open = 1;
    WorkCredit credit = 2;
    WorkAck ack = 3;
    WorkNack nack = 4;
    WorkExtend extend = 5;
  }
}
message WorkSessionResponse {
  oneof frame {
    WorkOpened opened = 1;
    WorkDispatchers dispatchers = 2;
    Delivery claim = 3;
    WorkRevoked revoked = 4;
    WorkRefused refused = 5;
    WorkReady ready = 6;
    WorkExtended extended = 7;
  }
}

A successful ack or nack gets no reply. A frame refused as malformed leaves the session open. When the worker closes its side, the node still carries out the acks, nacks, and extends it already read, waiting up to 5 seconds, then ends the session with OK. Deliveries not yet written go back as unattempted. Claims already delivered stand until their deadlines.

Work session frames

FrameDirectionFields
WorkOpen (open)Worker to nodebucket, key, worker_id (at most 256 bytes), claim_ttl_ms (0: the queue's; at most 12 hours)
WorkCredit (credit)Worker to noden (quiet credit), leftover, generation
WorkAck (ack)Worker to nodeclaims[]
WorkNack (nack)Worker to nodeclaim, retry_after_ms (0: the queue's backoff; at most 14 days), terminal, unattempted
WorkExtend (extend)Worker to nodeclaim, ttl_ms (0: the TTL the claim was dealt with)
WorkOpened (opened)Node to workerranges[]: the ranges this node dealt at the open, which can leave out seats still opening. Not updated.
WorkDispatchers (dispatchers)Node to workerring_version, dispatchers[]
WorkReady (ready)Node to workerquiet, leftover, generation
Delivery (claim)Node to workerclaim, message, attempt, deadline_ms, range, seq, routing_key, max_deadline_ms
WorkExtended (extended)Node to workerclaim, deadline_ms
WorkRefused (refused)Node to workerclaim, reason, refusal
WorkRevoked (revoked)Node to workerclaim, reason, refusal (WORK_REFUSAL_SEAT_MOVED or WORK_REFUSAL_CLAIM_GONE)

A claim token is 44 bytes: range id (16), position (8), attempt (4), the dealing seat's epoch (8), and its deadline in Unix milliseconds (8), big endian. A worker treats it as opaque. Any other length is refused malformed:

An ack of a token that is not a claim
{"refused": {"claim": "AAEC", "reason": "queue: not a claim", "refusal": "WORK_REFUSAL_MALFORMED"}}
WorkRefusalHTTP and TypeScriptGoMeaning
WORK_REFUSAL_NOT_HELDnot_heldClaimNotHeldThe node dealt the claim and no longer holds it
WORK_REFUSAL_SEAT_MOVEDseat_movedClaimSeatMovedAnother node deals the range now, or dealing restarted, or the range is not seated in this session. The message is dealt again.
WORK_REFUSAL_MALFORMEDmalformedClaimMalformedNot a claim, a time out of bounds, or a nack with unattempted beside a wait or terminal. Nothing was done.
WORK_REFUSAL_CLAIM_GONEclaim_goneClaimGoneThe claim no longer stands and nothing is owed: purged, or with persisted claims settled, retried, or taken over
WORK_REFUSAL_PAST_MAX_DEADLINEpast_max_deadlineClaimPastMaxDeadlineAn extend would pass max_deadline_ms. The claim keeps its deadline.

A session ends INVALID_ARGUMENT when the worker breaks the protocol: a first frame that is not open, a second open, or an empty frame. An open with a worker_id over 256 bytes, or a claim_ttl_ms that is negative or over 12 hours, ends it the same way.

Credits and the two classes of work

The node delivers a message only against a credit. A session has two pools of credit, one per class of work:

Classready fieldcredit fieldWhat it is
QuietquietnMessages in any ordinary range
LeftoverleftoverleftoverThe backlog of an isolated range, given to one flooding key

A credit is spent only on its own class. ready says which classes have messages waiting on this node. Grant a class's credit only while that class is true: the node accepts credit at the current generation either way, but a grant before the first ready buys nothing the node said it has.

The classes let a worker put a flooding key last. For each free slot, grant quiet credit to a node that reports quiet work. Grant leftover credit only when no node reports quiet work. To keep the flooding key moving, give about one grant in ten to leftover work first, as the SDK workers do.

A worker that only ever grants n never receives an isolated range's backlog. Grant leftover credit when ready reports leftover work.

A session holds at most 1,024 credits by default across both classes, counting deliveries not yet written to the connection. A grant past that ends the session RESOURCE_EXHAUSTED with QueueLimit{limit: "max_credits"}. The SDK workers grant at most 512 to one node.

Generations

When a class turns from true to false, the node cancels the session's unspent credit in both classes and raises the session's generation, as the last frame of the example shows. Every credit frame carries the generation of the last ready the worker saw. The node drops, silently, any grant whose generation is not the current one, because the worker sent it before it learned its credit was gone.

The worker's rule: on a ready with a new generation, set its unspent credit at that node to zero in both classes. Then grant again, under the new generation, for each class the frame reports true. A class turning true changes no generation and cancels nothing.

The node writes frames in this order: deliveries queued, then revocations, then a change of dispatchers, then ready. So a message delivered against a generation's credit always arrives before the ready that ends that generation. A cancellation also waits while credit already spent is on its way.

Revoked claims

On a queue with memory claims, a node revokes a session's claims in a range when the seat dealing the range ends. That happens when the range moves, the node drains, the seat's read breaks, or a newer seat replaced it. A purge restarts the seat on the same node. The node sends one revoked frame per claim:

refusalThe message
WORK_REFUSAL_SEAT_MOVEDIs dealt again by the seat that has the range now
WORK_REFUSAL_CLAIM_GONEWas purged and is not dealt again, as in the example

Stop working on that message if you can. An ack of a revoked claim is refused. A queue with persisted claims revokes nothing, because its claims survive a move: its workers' settles after a purge are refused claim_gone instead.

Closing a session settles nothing. Its claims stay out until their deadlines. The worker can settle them through another session with the same node while that node still seats the range. It can also send a unary Ack, Nack, or Extend, which the node routes to the seat that dealt the claim. A session with another node refuses them seat_moved.

Work session calls

A session's reader hands each ack, nack, and extend to the seats. A quick call, on a queue with memory claims and no earlier call waiting at its seat, runs on the reader itself. Any other call takes a goroutine and one of 64 places in the session's window, and the 65th waits. Answers wait in a backlog of 64, and when it is full the reader stops reading. Calls reach each seat in the order they were read, so an extend never overtakes the nack of its claim.

Crash points

EventWhat the worker seesWhat happens to its claims
The node crashes or freezesThe stream ends UNAVAILABLE, at once or after the keepalive timeoutMemory claims are dealt again by the next seat, after the node's metadata session expires. Persisted claims stand to their deadlines.
A range moves to another noderevoked frames with seat_moved, then a dispatchers frameThe new seat deals the messages again
The worker crashesNothing: the node sees the stream endClaims stand until their deadlines, then are dealt again
A frame is lost with the connectionThe stream endsAn ack never read is not applied; the claim runs to its deadline

Bounds and signals

BoundDefault
Work sessions per node512
Credit per session1,024
Calls in flight per session, and answers queued64 each
Dispatchers refresh5 seconds
Settle after the worker closes5 seconds
Claim TTL30 seconds, at most 12 hours
A claim's max deadline12 hours after its delivery
Nack retry_after_msAt most 14 days
Streams per client connection1,024

The per-node bounds are fields of the node's Dispatch configuration. Log lines:

  • queue: work session opened and queue: work session closed, at Debug
  • queue: work sessions refused at the bound; no more is said until one closes
  • queue: credit refused at the bound

Tests

  • The server: TestWorkSessionDealsAMessagePerCredit, TestWorkSessionDealsLeftoverWorkAgainstLeftoverCredit, TestWorkSessionNamesAClaimWhoseSeatMoved, TestWorkSessionFollowsTheStars, TestWorkSessionSaysAPurgedClaimIsGone in internal/transport/grpc/queue/work_test.go; TestAWorkSessionRefusesAFrameOutOfBoundsAndGoesOn in bounds_test.go.
  • The session: TestARangeRunningDryCancelsUnspentCredit, TestCreditPastTheBoundIsRefused, TestASeatThatEndsRevokesItsClaims, TestASessionsCallsReachASeatInTheirOrder, TestClosingASessionWaitsForItsAcks in internal/queue/session_test.go.
  • The Go worker: TestOneDisputedGrantInTenGoesToLeftoverWorkFirst, TestAReadyWithAnUnseenGenerationCancelsUnspentCredit in client/queue_dealer_internal_test.go; TestAWorkerFollowsItsQueueAcrossStars in client/queue_fleet_test.go.
  • TypeScript: sdk/ts/packages/transport-grpc/src/queue.test.ts and sdk/ts/packages/nova/src/worker.test.ts.

Go deeper

On this page