Run a worker

Run a worker

Take a queue's messages with a worker or one call at a time, then ack, nack, or extend each claim.

There are two ways to take a queue's messages. A worker, Work / createWorker(…).run(), keeps a session with each node that delivers the queue and runs your handler on each message; use it by default for a long-running process. A one-shot claim, ClaimOnce / claimOnce, takes messages in one call; use it over HTTP, through the Gateway, in a serverless function, or at a low rate. Each message comes with a claim, which you settle with an ack when the work is done or a nack when it failed. Delivery and claims explains what each outcome does. The API has the claim routes. Consuming needs the read permission.

Run a worker

A worker takes messages as fast as your handler finishes them, from every node that delivers the queue, and settles each message by how its handler ends.

queue := c.Queue(client.Address{Bucket: "demo", Key: "emails"})

err := queue.Work(ctx, func(_ context.Context, claim *client.Claim) error {
	if len(claim.Message.Body) == 0 {
		// An empty message can never succeed: dead-letter it now.
		return &client.NackError{Err: errors.New("empty message"), Terminal: true}
	}

	fmt.Printf("%s, attempt %d\n", claim.Message.Body, claim.Attempt)

	return nil // nil acknowledges the message
}, client.WorkOptions{
	Concurrency: 8,   // handle up to eight messages at once
	ExtendAt:    0.5, // extend a claim once half its time has passed
})
if err != nil {
	return err
}
Output
welcome, attempt 1
receipt, attempt 1
The handlerThe message
Returns nil / resolvesIs acknowledged
Returns an error / throwsFails this attempt, and is delivered again after the queue's backoff
Returns or throws a NackErrorFails this attempt, and waits the error's retry-after time, or goes to the dead-letter stream at once when it is terminal
Calls Ack or Nack itselfIs settled by that call. What the handler returns is ignored

A claim carries the message as it was sent, its routing key, its attempt number (1 the first time), its deadline, and its range and position. Worker calls need gRPC: over HTTP, a worker fails at once with ErrWireOnly / WireOnlyError.

ConcurrencyDefault1
How many messages the worker handles at once
ClaimTTLDefaultThe queue's claim_ttl_ms, 30 seconds
How long each claim lasts before its message is delivered again; at most 12 hours
ExtendAtDefault0, never
Once this fraction of a claim's time has passed and the handler is still running, extend the claim by its TTL again
GraceDefault0
How long running handlers may go on after you stop the worker
SettleFailedDefaultNone
Called when an ack, nack, or extend did not take; it must not block
WorkerIDDefaultThe host name and process id
Your worker's name in the nodes' logs

Keep a long job's claim

A claim's deadline is its delivery time plus the claim TTL. If the deadline passes before the handler returns, the message is delivered again, maybe to another worker while the first is still running. For work whose length varies, set ExtendAt / extendAt, as above: with 0.5 and a one-minute TTL, the worker extends the claim by another minute every 30 seconds while the handler runs.

No claim lasts more than 12 hours after its delivery, its max deadline: claim.MaxDeadline() in Go, claim.maxDeadline in TypeScript. The worker stops extending 5 seconds before it, and a claim still running then fails its attempt. Split work longer than 12 hours into steps.

The handler's context ends, or its signal aborts, when the queue takes the claim back or when you stop the worker and its grace period runs out. A claim taken back is not settled; its message is delivered again.

Stop a worker

Cancel the context, or abort the signal, you passed to the worker. It then asks for no more messages and hands back unstarted any that still arrive, without spending their attempts. It lets running handlers finish within the grace period, settles what they returned, and returns.

ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()

err := queue.Work(ctx, handle, client.WorkOptions{
	Concurrency: 16,
	Grace:       20 * time.Second, // running handlers get this long to finish
	SettleFailed: func(claim *client.Claim, err error) {
		log.Printf("message %s was not settled: %v", claim.Message.ID, err)
	},
})
if err != nil {
	return err
}

Set the grace period long enough for normal work to finish. A handler cut off by it fails its attempt. Inside a worker, an ack or a nack returns once it is queued, so a refusal reaches the settle-failed callback instead of your handler.

Claim one call at a time

A one-shot claim takes up to a number of messages and waits a while for the first. Any node can answer for the whole queue, and so can the Gateway, so it works over HTTP and in browsers.

queue := c.Queue(client.Address{Bucket: "demo", Key: "emails"})

// Up to 10 messages, waiting up to 20 seconds for the first.
claims, err := queue.ClaimOnce(ctx, 10, 20*time.Second, client.ClaimOptions{})
if err != nil {
	return err
}

for _, claim := range claims {
	fmt.Printf("%s, attempt %d\n", claim.Message.Body, claim.Attempt)

	if err := claim.Ack(ctx); err != nil {
		return err
	}
}
Output
welcome, attempt 1
receipt, attempt 1

The call returns once it has the number asked for, once the node it takes from has nothing more after at least one, or when the wait runs out, with an empty list. Call it in a loop with a wait of 20 to 30 seconds, and settle each claim before you take more.

limitMessagesDefault1 over HTTP
The most messages to take; at most 256
waitWaitDefault0
How long to wait for the first message; at most 30 seconds
ClaimOptions.ClaimTTLDefaultThe queue's
How long the claims last; at most 12 hours
ClaimOptions.WorkerIDDefaultNone
Your worker's name in the nodes' logs

Always use a wait. A node starts reading a queue's range only when someone first asks for its messages. So on a queue nobody has consumed since its node started, a claim with no wait returns nothing, and retries and delays wait too. The SDKs give up an attempt 10 seconds after its wait and try again within the retry budget. Over HTTP, set your client's timeout above the wait plus 5 seconds.

Ack, nack, and extend

A claim from a one-shot call is settled by a call of its own, through any node: the connection that took it does not matter.

// Long work: move the deadline to five minutes from now, then finish.
if err := work.Extend(ctx, 5*time.Minute); err != nil {
	return err
}

if err := work.Ack(ctx); err != nil {
	return err
}

// A message that can never succeed: send it to the dead-letter stream now.
if err := corrupt.Nack(ctx, client.NackOptions{Terminal: true}); err != nil {
	return err
}

fmt.Printf("acked %s, gave up %s\n", work.Message.Body, corrupt.Message.Body)
Output
acked transcode, gave up corrupt
CallEffect
AckThe work is done. The message is never delivered again
NackThe attempt failed. The message is delivered again after a wait, or goes to the dead-letter stream; the nack options choose
ExtendThe deadline moves to the given time from now, earlier or later, but never past the max deadline. Zero uses the TTL the claim was delivered with

When a claim is refused

An ack, nack, or extend is refused when the claim is no longer yours to settle, for example because its deadline passed and the message went to another worker. A refused call did nothing.

if err := claim.Ack(ctx); err != nil {
	var refused *client.ClaimRefusedError
	if !errors.As(err, &refused) {
		return err // no answer within the retry budget: acking again is safe
	}

	// The claim is no longer this worker's. Do not settle it again.
	fmt.Println("ack refused:", refused.Refusal)
}
Output, for a claim whose deadline had passed
ack refused: not_held

The error is a *client.ClaimRefusedError and matches client.ErrClaimRefused. Its Refusal is one of ClaimNotHeld, ClaimSeatMoved, ClaimGone, ClaimMalformed, and ClaimPastMaxDeadline.

RefusalWhat to do
not_held, seat_moved, claim_goneDrop the claim. Another worker may hold the message now. Do not settle it again
malformedFix the call: the claim stands as it was
past_max_deadlineExtend by less, or let the claim expire

Delivery and claims explains when each refusal happens and what became of the message. Other errors, such as no answer within the retry budget, leave the claim as it was, so settling it again is safe.

When a worker stops with an error

A worker returns an error only when it cannot go on:

Error: Go, TypeScriptCause
ErrUnavailable, UnavailableErrorNo node that delivers the queue answered within the retry budget, 30 seconds by default
ErrStreamNotFound, StreamNotFoundErrorThe queue was deleted, or never existed
ErrUnauthenticated, UnauthenticatedErrorThe credential was refused
ErrMessage, MessageErrorA node refused the worker's options, such as a worker id over 256 bytes
ErrWireOnly, WireOnlyErrorThe client uses HTTP. Use one-shot claims

Get more throughput

To deliver moreDo thisUp to
Per workerRaise its concurrencyWhat your process can handle at once
Per one-shot callAsk for more messages256 per call
Across workersRun more workersThe node limits in node limits
Across nodesCreate the queue with more initial_ranges; ranges also split as they get busy256 ranges per queue
Per keyRaise key_concurrency, or leave it unboundedOne per key on a key-ordered queue

Acknowledge promptly. A node reads ahead a bounded amount per range, and messages that wait for their ack fill it. The fairness page explains the per-key and queue-wide limits.

See also

On this page