Retries and dead letters

Retries and dead letters

Set how a queue retries a failed message, fail one message your way, and read or replay dead letters.

A message fails an attempt when its worker nacks it or lets its claim's deadline pass. Nova delivers it again after a wait. After the last attempt, Nova moves it to the queue's dead-letter stream, where you can read it and send it back. Set how a queue retries in its retry policy; to treat one message differently, nack it with options. Delivery and claims explains every way a claim ends. The examples use a queue demo/payments whose worker charges cards.

Set the retry policy

A queue's retry policy says how many attempts a message gets and how long it waits between them. Set it when you create the queue, or update it later.

payments := client.Address{Bucket: "demo", Key: "payments"}

info, err := c.CreateQueue(ctx, payments, client.QueueConfig{
	Kind: client.QueueStandard,
	Retry: client.QueueRetry{
		MaxAttempts: 8,                      // dead-letter after the eighth attempt
		MinBackoff:  500 * time.Millisecond, // the wait after the first failure
		MaxBackoff:  30 * time.Second,       // the longest wait
		Factor:      2,                      // each wait is twice the one before
	},
})
if err != nil {
	return err
}

r := info.Config.Retry
fmt.Printf("%d attempts, waits from %d to %d ms\n",
	r.MaxAttempts, r.MinBackoff.Milliseconds(), r.MaxBackoff.Milliseconds())
Output
8 attempts, waits from 500 to 30000 ms
MaxAttemptsAttemptsDefault5
Deliveries before the message goes to the dead-letter stream
MinBackoffFirst waitDefault1 second
The wait after the first failed attempt
FactorDefault2
How much each wait grows; a value above 0 and up to 1 keeps it constant
MaxBackoffLongest waitDefault60 seconds
The cap on any wait; at least the first wait

The wait after attempt n fails is the first wait times the factor to the power n − 1, up to the longest wait. A setting left at zero takes its default, so the default policy delivers a message five times, waiting 1, 2, 4, and 8 seconds between attempts. Nova refuses a negative value, and a longest wait below the first, with 400. A change applies to the next failed attempt, within about 5 seconds.

Set the claim TTL above your usual processing time. Too short, and slow work is done twice; too long, and a crashed worker's message waits that long for its retry.

Fail one message your way

A nack can override the policy for one message. Use a retry-after time when you know when to try again, such as from a rate limit. Make the nack terminal when the message can never succeed, such as one that fails validation.

func Handle(ctx context.Context, claim *client.Claim) error {
	err := charge(ctx, claim.Message.Body)

	var limited *RateLimitError

	switch {
	case errors.As(err, &limited):
		// Try again when the provider says, instead of after the backoff.
		return &client.NackError{Err: err, RetryAfter: limited.RetryAfter}
	case errors.Is(err, ErrCardDeclined):
		// Retrying cannot help: dead-letter the message now.
		return &client.NackError{Err: err, Terminal: true}
	}

	return err // nil acknowledges; another error retries after the backoff
}

A *client.NackError returned from a worker's handler sets the options. Outside a worker, call claim.Nack(ctx, client.NackOptions{…}).

RetryAfterDefaultThe policy's wait
Wait this long before the next attempt; at most 14 days
TerminalDefaultfalse
Send the message to the dead-letter stream now, whatever attempts remain
UnattemptedDefaultfalse
The worker never started the message: deliver it again at once, without spending the attempt. Use it alone

An unattempted hand-back is free only three times a minute, and only within 15 minutes of the message's first hand-back. After that it spends the attempt like any nack, so a worker that hands everything back still reaches the last attempt. The SDK workers hand back unattempted the messages that arrive while they stop.

What counts as a failed attempt

EventFailed attempt
The worker nacks, or the claim's deadline passesYes
The worker nacks with unattempted, within its limitNo
The worker disconnectsNot yet: the claim fails at its deadline
A one-shot claim's caller has gone when the answer is readyNo: the messages are handed back unworked
The node delivering the range stops, with memory claimsNo: the message comes back with the same attempt
A delay endsNo

How a retry is delivered

On a standard queue, Nova stores a new copy of the message when its wait ends: the same id, body, and headers, with an attempt one higher. It goes to the back of its range, with a new seq. On a key-ordered queue, the message stays at the head of its key, and the key's later messages wait behind it.

Read dead letters

A message goes to the dead-letter stream when it fails its last attempt or is nacked as terminal. Read the stream to see what failed and why.

var from client.SeqNum

for {
	letters, err := queue.DeadLetters(ctx, from, 100)
	if err != nil {
		return err
	}

	if len(letters) == 0 {
		break // read them all
	}

	for _, r := range letters {
		for _, h := range r.Headers {
			if string(h.Name) == client.AttemptHeader {
				fmt.Printf("dead letter %s, given up on attempt %s\n", r.Body, h.Value)
			}
		}
	}

	from = client.SeqNum(letters[len(letters)-1].SeqNum + 1)
}
Output
dead letter declined, given up on attempt 1

Reading goes oldest first and removes nothing. Each record is the message as it was last delivered, with the queue's nova- headers beside yours: the message id, the attempt it was given up on, and its routing key. Nova keeps a dead letter for the queue's dead_letter_ttl_ms, 14 days by default, counted from when it was dead-lettered. Dead letters are never delivered to workers, and a purge leaves them.

Replay dead letters

A replay sends the queue's oldest dead letters back to the queue and removes them from the dead-letter stream. Use it once you have fixed what made them fail.

for {
	replayed, more, err := queue.ReplayDeadLetters(ctx, 1000)
	if err != nil {
		return err
	}

	fmt.Println("replayed", replayed)

	if !more {
		break
	}
}
Output
replayed 1

One call replays up to its limit, 100 by default and at most 1,000, and more says whether dead letters remain. A replayed message keeps its id, body, headers, and routing key, and starts again at attempt 1 with a full TTL. A delay it already served is not applied again. From a shell, use nova queue replay-dead-letters. Replaying needs the append permission.

A replay can need the admin permission

When the dead letters are stored on a different node from the one that delivers the queue, a replay sends them and then fails with PermissionDenied, even with the append permission. The letters it sent stay in the dead-letter stream, so replaying again sends them a second time. Replay with a token that holds nova:admin. nova queue has the same limit.

Only one replay of a queue runs at a time. A second one fails with ABORTED, 503 over HTTP: Go returns it, and TypeScript retries within its budget and then throws UnavailableError. A replay sends for at most 90 seconds. If its node stops part way, the next replay is refused until 2 minutes after the first began. Nova sends each letter before it removes it, so a replay that stops between the two can send a letter twice, but never loses one.

Message expiry

Nova drops a message older than its TTL instead of delivering it: the message's own TTL, or the queue's message_ttl_ms. Age counts from the first send, and neither a retry nor a delay resets it. An expired message does not go to the dead-letter stream. message_ttl_ms is also the queue's retention: Nova removes stored messages older than it, settled or not. Operators can count expired messages; see the metrics catalogue.

See also

On this page