Skip to content

Retry, Backoff & Delayed Delivery ​

“The solution isn’t to remove backoff. It’s to add jitter.” — Marc Brooker, AWS Architecture Blog

Summary: Retry repeats a safe operation after a recoverable failure; backoff controls when, and a budget controls when to stop. Focus: Failure classification, attempt and time limits, jitter, durable scheduling, and the actual RabbitMQ, Kafka, Redis Streams and Laravel mechanisms. Learning goal: Design a retry path that survives a worker crash without losing work, multiplying load without limit, or pretending that ordering and exactly-once effects come for free.

This chapter owns retry policy and delayed delivery. Dead-letter queues own quarantine and redrive; ordering owns sequence guarantees; idempotent consumers own duplicate suppression. Read those contracts alongside the schedule, because a correct timer alone cannot make a retry safe.

Page map ​

If you need…Go to
A compact policy checklistOne minute
Which failures deserve another attemptClassification
Attempt counting, deadlines and cancellationBudgets
Exact jitter formulasBackoff and jitter
Preventing a retry stormAmplification
Deciding where waiting happensDelay placement
RabbitMQ versions, Kafka topics, Redis LuaBroker differences
Laravel backoff, retryUntil, releaseLaravel
A review and failure-injection exerciseLab

Everything in one minute ​

QuestionPolicy decisionExample
Can repeating succeed?Classify the failureTemporary 503 versus invalid invoice
Can repeating cause damage?Require an idempotency contractSame billing operation key on every POST
How much work is allowed?Total attempts, including the first6 attempts means at most 5 retries
How long is it useful?Absolute deadline plus per-attempt timeoutStop the operation after 30 minutes
When is another call allowed?Backoff, jitter, server hintsmax(local_delay, Retry-After)
Where does the wait live?Memory, broker, or persistent scheduler100ms locally; minutes in durable storage
What protects the dependency?A shared retry budgetRetry tokens separate from original traffic
What happens at exhaustion?An explicit terminal policyFail, park, reconcile, or escalate
MechanismWhat it providesWhat it does not provide
Exponential backoffIncreasing delay envelopeRandom spreading or a finite lifetime
JitterLess synchronization across workersLess total work unless a budget also exists
Delayed deliveryA not-before timeAn exact execution time or reserved worker capacity
Publisher confirmationBroker acceptance of a publicationConsumer business success
Retry topicA separate Kafka failure pathOrdering with the original topic
Redis sorted setDue-time indexingA Streams scheduling feature by itself
Laravel retryUntil()Time-based job admission limitA second independent tries limit

Where it comes from ​

Backoff appears wherever independent participants contend for a resource. For application retries, Brooker's 2015 AWS article compares capped exponential backoff with Full, Equal and Decorrelated Jitter using an optimistic-concurrency simulation. The result is evidence about synchronization and contention, not a universal benchmark for every queue workload.

Amazon's Builders' Library explains why retries at several service layers multiply load and describes limiting retries with a token bucket. Google's SRE book distinguishes a per-request limit from a per-client retry budget. Broker products then supply different storage and delivery primitives; the application must connect those primitives to a business deadline and error classifier.

Why it exists ​

A payment provider can be briefly unavailable while the invoice remains valid. Immediately failing every invoice loses useful work; repeatedly hitting the provider at full speed can prevent recovery. The useful middle ground is a finite number of safe attempts spread over a useful time window.

Prefer recoveryProtect the system
Retry a short network interruptionDo not retry bad credentials indefinitely
Wait through a deploymentDo not occupy every worker while waiting
Preserve pending work across crashesBound scheduled storage and message age
Continue unrelated ordersAccept or explicitly prevent overtaking
Honor the server's recovery hintStop if the hint exceeds the business deadline

Three misunderstandings should disappear immediately: a timeout does not prove the server did nothing; a larger delay does not limit the number of attempts; and successfully publishing a replacement does not prove the original was safely acknowledged.

What it is really about ​

A retry policy is a state machine over one logical operation: classify the result, check permission to repeat, consume a budget, compute the earliest next attempt, persist that decision if necessary, and settle the current delivery only after the handoff succeeds. Its state includes message_id, attempt count, first-attempt time, deadline, next-attempt time, and the last failure category.

The message identifier stays stable while delivery identifiers can change. A republished RabbitMQ delivery, a new Kafka offset and a new Redis stream entry may all represent another attempt at the same invoice. The business idempotency key must survive those transport changes.

Failure observedOutcome may be unknownSafe to repeat?Transient allowlistAttempts + deadlineShared retry tokensCompute due timeBackoff + jitterPermanent / unsafeStop and resolveBudget exhaustedParking policyDurable scheduleWait, then try

An everyday picture ​

A courier arrives at a closed shop. Calling again a few minutes later may help; ringing the bell continuously will not. The courier has a finite number of visits, a closing-time deadline, and an address that must be valid. If every courier returns at exactly noon, the shop gets another crowd. Choosing different return times spreads the load. Writing the appointment in a durable diary also means another courier can take over after a shift ends.

The concept catalogue ​

Failure classification and safe repetition Must-know ​

In plain words: Retry a problem that can change, and only when repeating the action is safe.

Common misunderstanding: “All 4xx are permanent and all 5xx are temporary.” HTTP status is an input to the classifier, not the whole business contract. A 429 is deliberately retry-related; a 409 may require rereading state; a deterministic 500 can be a permanent application bug.

Definition: A transient failure may succeed without changing the operation's intent; a permanent failure requires a payload, permission, configuration or business-state change. An ambiguous outcome means the effect may already have happened even though the caller did not observe success.

text
1 Worker -> Billing: create invoice, operation key invoice-42:send:v1
2 Billing: persists invoice; response connection breaks
3 Worker: sees timeout, not proof of rollback
4 Worker -> Billing: repeats SAME operation key
5 Billing: returns prior result under its idempotency contract

Real scenarios include a payment response lost after commit, temporary rate limiting, an obsolete event schema, and a revoked credential. Classify these differently. For a stale-version conflict, refresh state and recompute the operation; blindly repeating the same stale request is not progress.

FailureDefault decisionRequired condition
Connection reset / timeoutBounded retryRepetition safe; outcome may be ambiguous
HTTP 408, 429, 502, 503, 504Candidate for retryEndpoint contract and remaining budget
HTTP 400 / schema rejectionStopCorrect the input before a new operation
HTTP 401 / 403Stop or one controlled credential refreshNever hide a persistent permission error in retries
HTTP 409Domain-specificRefresh version/state when the API requires it
Unknown exceptionStop by defaultAdd an explicit retryable category after investigation
Cancellation / expired operationStopCaller no longer authorizes more work

SQL should persist the logical attempt budget, Go should use typed errors or an allowlist callback, and Laravel should call fail() for permanent business failures. The implementation below keeps the same billing key; the receiver, not the header itself, supplies deduplication.

Attempt budgets, time budgets and cancellation Must-know ​

In plain words: Count how often you try and how long the result remains useful; those are different limits.

Common misunderstanding: “Three retries means three calls.” Here MaxAttempts = 3 means the first call plus two retries. A library parameter named retries may instead mean three additional calls. Document the unit beside the setting.

Definition: The attempt budget limits starts; the overall deadline limits the operation's useful lifetime; a per-attempt timeout limits one dependency call. Queue waiting, backoff and handler execution all consume wall-clock time before the overall deadline.

text
1 Operation deadline = 10:30:00; max attempts = 6
2 Attempt 1 begins 10:00:00, call timeout = 5 seconds
3 Failure schedules attempt 2 for 10:00:20
4 Worker crashes; replacement reads the SAME deadline and count
5 At 10:30:01 a delivery arrives: reject further execution, do not reset the clock

For an in-process policy with N attempts, per-call timeout T, and delays d[0..N-2], the nominal upper bound is N*T + sum(d). A stricter outer deadline wins. This is only a bound if the operation honors cancellation; a Go context cannot forcibly stop arbitrary code or undo a committed side effect.

LimitPersist or propagateCommon mistake
Total attemptsAcross republishing and worker restartsResetting to zero on every retry topic
Absolute deadlineIn the logical operation envelopeRecomputing “now + 30 minutes” on every execution
Per-call timeoutInto the actual HTTP/DB/client operationTiming only the sleep loop
Maximum message ageFrom business creation timeTreating a fresh delivery as fresh business intent
Shared retry allowanceAcross the callers it protectsGiving every worker a full fleet-sized budget

The PostgreSQL example reserves an additional attempt with one conditional update. It is a budget illustration, not a complete scheduler; outbox owns atomic publication with a database change.

sql
-- PostgreSQL: persist a logical operation's budget across worker restarts.
CREATE TABLE retry_budget (
    message_id text PRIMARY KEY,
    attempts integer NOT NULL CHECK (attempts >= 1),
    max_attempts integer NOT NULL CHECK (max_attempts >= 1),
    deadline_at timestamptz NOT NULL,
    next_attempt_at timestamptz NOT NULL,
    CHECK (attempts <= max_attempts)
);
INSERT INTO retry_budget VALUES
    ('invoice-42:send:v1', 1, 6, now() + interval '30 minutes', now());

-- Bind :id and :delay_seconds; application validates 0 <= delay <= 300.
-- Zero rows means exhausted/expired/not due: do not dispatch another attempt.
UPDATE retry_budget
SET attempts = attempts + 1,
    next_attempt_at = clock_timestamp() + make_interval(secs => :delay_seconds)
WHERE message_id = :id
  AND attempts < max_attempts
  AND next_attempt_at <= clock_timestamp()
  AND clock_timestamp() + make_interval(secs => :delay_seconds) < deadline_at
RETURNING message_id, attempts, next_attempt_at, deadline_at;
-- This reserves budget only. Use the linked outbox pattern if publishing must
-- be atomic with this update; do not assume SQL commits publish broker messages.
sql
-- PostgreSQL: inspect expired or exhausted logical operations.
SELECT message_id, attempts, max_attempts, deadline_at
FROM retry_budget
WHERE attempts >= max_attempts OR deadline_at <= clock_timestamp();

Go's outer context carries the deadline; the wrapper creates a child timeout for each call. Laravel's retryUntil() takes precedence over tries, so the example explicitly guards attempts() when both independent limits are required.

Backoff families and jitter Must-know ​

In plain words: Wait longer after repeated failures, and give different workers different return times.

Common misunderstanding: “Exponential backoff already spreads retries.” Equal starts and equal delays produce synchronized waves, including repeated waves once the cap is reached.

Definition: Let retry index k = 0 denote the first retry after attempt 1; b is base delay and C is the cap. The exponential envelope is B(k) = min(C, b * 2^k). U(a,b) means a uniform draw between the bounds; discrete implementations must document inclusivity.

PolicyDelay formulaConsequence
Immediate0Useful only for carefully bounded local races; otherwise a hot loop
ConstantbSimple but synchronized across callers
Linearmin(C, b * (k+1))Slower growth; RabbitMQ native delayed retry uses delivery count
Exponential without jitterB(k)Reduces frequency but keeps cohorts together
Full JitterU(0, B(k))Mean approximately B(k)/2; zero is allowed
Equal JitterB(k)/2 + U(0, B(k)/2)Minimum half the envelope; mean about 3B(k)/4
Decorrelated Jittermin(C, U(b, 3 * previous_delay))Carries previous-delay state; initialize it to b
text
1 b=1s, C=8s; four workers fail together
2 No jitter: all retry at +1s, then all at +2s after their next failure
3 Full jitter: first waits might be 0.1s, 0.4s, 0.7s, 0.9s
4 Later envelopes grow to 2s, 4s, 8s; the budget still stops the operation

Use Full Jitter as a straightforward default for independent retrying clients. Equal Jitter avoids very short sleeps at the cost of more waiting; Decorrelated Jitter has a different distribution and needs persistent previous-delay state if a worker restart must continue the sequence. Brooker's simulation favors jittered variants over no jitter; choose using your latency and load goals rather than treating one simulation as a universal ranking.

The multiplication must saturate before integer overflow. Even ceiling + 1 can overflow a signed maximum duration when sampling an inclusive range. The Go example guards doubling and uses an unsigned sampling bound. Laravel computes a small bounded array, avoiding an unbounded exponent.

Retry amplification and fleet budgets Must-know ​

In plain words: Each retry consumes capacity needed for both recovery and new work.

Common misunderstanding: “A limit of three at every layer is conservative.” Three total attempts at three independently retrying layers can produce 3 × 3 × 3 = 27 dependency calls. Three retries after the first call would instead mean 4³ = 64.

Definition: Retry amplification is the ratio of physical attempts to original logical operations. A per-operation cap bounds one operation; a shared retry budget bounds extra traffic across many operations over a time window or token balance.

text
1 API allows 3 attempts of the worker request
2 Worker allows 3 attempts of the SDK operation for each API attempt
3 SDK allows 3 dependency calls for each worker attempt
4 Persistent failure -> up to 27 dependency calls for one logical operation
5 Move retry ownership to one layer; make all other layers report failure

At steady arrival rate lambda, if every operation uses A attempts, approximate dependency demand becomes lambda * A. Backoff changes when that work arrives, not the total count. During an outage, the scheduled backlog also grows; after recovery, an uncontrolled drain can create a second outage.

GuardWhat it limitsImportant scope
Per-operation attempt capWork caused by one messagePersist across redeliveries
Token bucket for retriesExtra calls over time with a finite burstPer dependency; coordinate or divide across workers
Retry-to-original ratioRetry traffic relative to new workDefine denominator and window explicitly
Concurrency limitCalls simultaneously in flightInclude retries in the same dependency limit
Circuit breakerAttempts while dependency is unhealthyHalf-open probes also need a budget
Controlled backlog drainRecovery trafficFairness across tenants and fresh work

Google's SRE discussion gives a 10% per-client retry-budget example; that is an example policy, not a default for every service. A token bucket with capacity 20 and refill 2 per second permits a bounded burst and then two extra calls per second. If copied independently to 100 workers, it becomes a very different fleet allowance. Backpressure owns the admission and capacity controls; this chapter requires retries to participate in them.

3 attempts at caller3 attempts at worker3 attempts at SDK3 × 3 × 3 = 27 callsOne owner + shared budgetBound dependency loadNo jitter: workers retry togetherFull jitter: workers spread within the cap

Where the delay lives Important ​

In plain words: A worker waiting in memory is a different system from a message waiting durably.

Common misunderstanding: “Sleeping for five minutes is just delayed delivery.” It occupies a worker, retains in-flight state, can hit consumer liveness limits, and vanishes on process loss unless the input remains safely unacknowledged.

Definition: In-process backoff keeps retry state in the worker. Durable delayed delivery persists a not-before time outside the process and makes work eligible later. Eligibility is not an execution SLA: backlog, scheduler polling, clocks and capacity can make execution late.

text
1 Worker receives message and discovers dependency outage
2 Option A: sleep in worker; input stays in flight, worker capacity unavailable
3 Option B: confirm durable delayed copy, then settle original input
4 Worker dies during wait: A relies on redelivery; B survives in delay storage
5 Due time arrives: scheduled item becomes eligible; available capacity determines start
PlacementBest fitCost / failure boundary
Short cancellable timerSmall transient disturbance within request budgetOccupies an execution slot
RabbitMQ TTL tierA small finite set of delay classesApproximate time; DLX transfer needs its own safety configuration
RabbitMQ quorum native delayPer-message due time on supported versionsVersion and queue-type dependency
Kafka retry topicDecouple failed records from main trafficScheduler/consumer logic; original ordering changes
Redis ZSET schedulerExplicit due-time indexApplication owns payload identity, atomic movement and persistence
Durable workflow timerDays-long business coordinationBroader workflow state; see durable workflows

A first attempt scheduled for tomorrow is not a retry, although it may use the same storage. Message expiration means “no longer useful after”; delayed delivery means “not useful before”. Keep those timestamps separate.

Server hints, clocks and Retry-After Important ​

In plain words: When a server asks you to wait, respect its earliest acceptable return time without extending your own business deadline.

Common misunderstanding: “Cast Retry-After to an integer.” RFC 9110 allows delta seconds or an HTTP date. Casting a date to zero can turn a throttling response into an immediate retry storm.

Definition: Convert a valid server hint into an earliest next-attempt time; combine it with the local policy using the later of the two. Add only nonnegative jitter when the server hint is a minimum. If it exceeds the allowed horizon, stop or hand off to a separately authorized longer-lived policy; never clamp it downward and call early.

InputMeaningAction in the PHP helper
120Wait at least 120 secondsUse 120, then bounded upward jitter
Valid IMF-fixdateWait until the given GMT dateConvert relative to current wall clock
Date in the pastMinimum is already satisfiedZero minimum; local policy may still wait
Invalid or negative textNot a valid deltaUse documented fallback of 30 seconds
Huge numeric valueBeyond the example's 300-second horizonReturn over-limit marker; job fails instead of retrying early
Hint after job deadlineWork would no longer be usefulEnd this operation's retry policy

The helper accepts the canonical IMF-fixdate format emitted by current HTTP servers; obsolete HTTP-date formats fall back rather than being guessed. Across machines, wall-clock skew affects absolute due times. The Redis scheduler uses Redis TIME for both insertion and draining; a Go in-process timer uses durations and the runtime's clock support. Monitor lateness separately from intentional delay.

Durable handoff and identity Must-know ​

In plain words: Keep responsibility for the old delivery until somebody durably accepts responsibility for the next one.

Common misunderstanding: “The publish function returned, so ACK is safe.” Some APIs only accepted bytes into a local socket or buffer. Confirmation, routing, persistence and the original settlement are distinct boundaries.

Definition: A retry handoff copies the logical operation into its next schedule and then settles the current delivery. If those are separate actions, the crash gap normally gives at-least-once delivery; removing the gap requires a supported transactional boundary, not a comment claiming exactly once.

text
1 Publish retry copy with unchanged message_id and business idempotency key
2 Wait for confirmed acceptance; reject unroutable publication
3 Crash before acknowledging original -> both original and retry may be delivered
4 Deduplication at the business boundary makes the duplicate harmless
5 ACK first, then crash before publish -> lost work; never choose this ordering
Broker pathAcceptance before settlementResidual risk
RabbitMQ republishPublisher confirm and mandatory-return checkDuplicate if original ACK is lost; TTL→DLX has separate guarantees
Kafka retry topicSynchronous successful produce before input commitDuplicate on crash before commit; transactions are a separate design
Redis schedulerSuccessful schedule script before original XACKRetry after ambiguous response may reschedule the same ID

Preserve logical identity, trace context, schema version and the business deadline. Replace retry control fields deliberately. Do not blindly preserve old routing headers, per-message expiration or an old delivery-time header into a new RabbitMQ schedule. A fresh transport ID never authorizes a fresh business operation.

Scheduler identity and atomicity Important ​

In plain words: A due-time index must distinguish two different messages even when their payloads are identical.

Common misunderstanding: “Use the JSON payload as the sorted-set member.” Redis ZSET members are unique. Two separate invoices with the same serialized data then overwrite one another's score instead of creating two pending messages.

Definition: Store a stable message ID as the ZSET member, a due timestamp as its score, and the envelope in a separate hash keyed by that ID. The same pending ID intentionally updates its schedule; different IDs remain different operations.

Scheduler propertyExample implementationBoundary
IdentityID in ZSET, envelope in HASHIDs must not collide across business operations
Due clockRedis TIMERedis clock still needs operational discipline
Concurrent drainersOne bounded Lua scriptSerial execution is not rollback
Redis Cluster locality{orders} in every keyClient prefixes must retain the effective hash tag
Bounded workAt most 100 items per tickOne Lua script blocks other commands while running
DeliveryXADD before removing pending IDPersistence/failover and ambiguous responses still require idempotency

The script checks key types and missing payloads before moving a batch. That removes common partial-write causes, but Lua has no general transaction rollback. Resource errors, persistence configuration and failover remain real concerns. Keep source records recoverable and use the Redis durability guidance appropriate to the workload.

Mechanics: exact controls and failure boundaries ​

Control / signalProduct and unitInterpretation
MaxAttempts, PerAttempt, outer contextThis Go example; count / duration / deadlineAll three bounds are independent
x-message-ttlRabbitMQ queue argument; millisecondsMessage lifetime within a queue, used for a fixed delay tier
expirationRabbitMQ message property; decimal millisecond stringPer-message TTL; mixed values create head-of-line effects
x-expiresRabbitMQ queue argument; millisecondsDeletes an unused queue; not a message delay
x-delayRabbitMQ legacy plugin; millisecondsDelay before routing through its custom exchange
x-opt-delivery-timeRabbitMQ quorum 4.4+; Unix millisecondsNative publisher-requested not-before time
x-delayed-retry-min/max/typeRabbitMQ quorum 4.3+; milliseconds / modeNative linear redelivery policy
not-before-ms, attemptApplication Kafka headersKafka itself does not schedule from these names
DisableAutoCommit, BlockRebalanceOnPollfranz-go optionsManual settlement with bounded ownership during processing
ZRANGE ... BYSCORE, LIMITRedisDue selection with an explicit batch bound
backoff(), release($delay)Laravel 13; seconds or supported date formsException schedule versus explicit release
retryUntil(), #[RetryFor]Laravel 13; absolute time / relative windowTime-based attempt policy
retry_after, --timeoutLaravel queue connection / worker; secondsRedelivery visibility versus worker execution time; neither is backoff
Failure signalResponse
AMQP 312 NO_ROUTE / mandatory returnDo not ACK source; fix routing and reconnect with backoff
AMQP 406 PRECONDITION_FAILEDFix mismatched queue declaration; retrying the same declaration cannot help
AMQP negative publisher confirm / connection lossKeep source unsettled; outcome can be ambiguous
Kafka produce or commit failureExit the simple loop; restart with a new client and committed offsets
Malformed not-before-msStop/route to invalid-message policy; never treat as epoch zero
Redis WRONGTYPE / missing payloadRepair scheduler state; repeating unchanged input is not a fix
Redis CROSSSLOTCorrect effective key hash tags; backoff cannot repair key design
Go context.Canceled / DeadlineExceeded on outer contextStop new attempts
Laravel MaxAttemptsExceededExceptionInspect attempts, releases and time policy; follow terminal handling

Solving the recurring problems ​

ProblemSolutionBenefitCost / limit
Brief dependency blipFew cancellable local retriesSmall latency overheadOccupies a worker and consumes request deadline
Minutes-long outagePersist delayed attemptsFrees workersMore storage and handoff paths
Simultaneous recovery surgeJitter plus shared retry tokensBounds burst and ongoing retry loadCoordination/fairness policy
Business deadline passedStop before another callAvoids stale effectsNeeds an explicit terminal outcome
Retry publication failedKeep original unsettledAvoids acknowledge-before-publish lossCan duplicate on ambiguous acceptance
Strict same-key sequence requiredKeep partition/key blocked or use a coordinated gatePrevents overtakingHead-of-line blocking; see ordering chapter
Same payload appears twiceDistinct stable IDs in schedulerBoth messages surviveRequires real operation identity
Count resets after restartDurable envelope or budget rowCap remains meaningfulState lifecycle and retention

A useful implementation order is classifier → budgets → safe handoff → scheduling → fleet controls. Adding more delay tiers before defining a terminal outcome only makes a broken policy take longer to fail. For long-lived reminders and multi-step timeouts, use durable workflows rather than extending this retry loop into a workflow engine.

Go ​

Before ​

The old shape retries forever on a fixed rhythm. It has no classifier, cancellation or deadline and treats a poison input like a temporary outage. It is compilable code, but intentionally poor policy.

go
package before

import (
	"context"
	"time"
)

// Deliver retries forever with a fixed one-second sleep. Every failing
// consumer wakes up on the same beat, and a poison message is retried until
// the process dies.
func Deliver(ctx context.Context, send func(context.Context) error) {
	for {
		if err := send(ctx); err == nil {
			return
		}
		time.Sleep(time.Second)
	}
}

After ​

The wrapper validates its policy, checks cancellation before starting a call, saturates the exponential envelope safely, and gives each call a child context. The caller supplies an allowlist classifier; an unknown error should normally stop. Its MaxAttempts includes the first call.

go
package after

import (
	"context"
	"errors"
	"fmt"
	"math/rand/v2"
	"time"
)

var ErrBudget = errors.New("retry attempt budget exhausted")

// MaxAttempts includes the initial call. The caller supplies an overall context
// deadline; PerAttempt limits each call. fn must honor its context.
type Policy struct {
	MaxAttempts int
	Base, Cap   time.Duration
	PerAttempt  time.Duration
}

func (p Policy) Validate() error {
	if p.MaxAttempts < 1 || p.Base <= 0 || p.Cap < p.Base || p.PerAttempt <= 0 {
		return errors.New("invalid retry policy")
	}
	return nil
}

// Ceiling saturates BEFORE multiplication, including at MaxInt64 duration.
func (p Policy) Ceiling(retry int) (time.Duration, error) {
	if err := p.Validate(); err != nil {
		return 0, err
	}
	if retry < 0 {
		return 0, errors.New("negative retry index")
	}
	ceiling := p.Base
	for i := 0; i < retry && ceiling < p.Cap; i++ {
		if ceiling > p.Cap/2 {
			ceiling = p.Cap
		} else {
			ceiling *= 2
		}
	}
	return ceiling, nil
}

func (p Policy) Backoff(retry int) (time.Duration, error) {
	ceiling, err := p.Ceiling(retry)
	if err != nil {
		return 0, err
	}
	// uint64 keeps ceiling+1 representable even at MaxInt64.
	return time.Duration(rand.Uint64N(uint64(ceiling) + 1)), nil
}

// retryable is an allowlist: unknown errors should normally return false.
func Do(ctx context.Context, p Policy, retryable func(error) bool, fn func(context.Context) error) error {
	if err := p.Validate(); err != nil {
		return err
	}
	if retryable == nil || fn == nil {
		return errors.New("missing retry callback")
	}
	var last error
	for attempt := 0; attempt < p.MaxAttempts; attempt++ {
		if err := ctx.Err(); err != nil {
			return err
		}
		callCtx, cancel := context.WithTimeout(ctx, p.PerAttempt)
		last = fn(callCtx)
		cancel()
		if last == nil {
			return nil
		}
		if err := ctx.Err(); err != nil {
			return err
		}
		if !retryable(last) {
			return last
		}
		if attempt+1 == p.MaxAttempts {
			break
		}
		delay, _ := p.Backoff(attempt)
		timer := time.NewTimer(delay)
		select {
		case <-ctx.Done():
			timer.Stop()
			return ctx.Err()
		case <-timer.C:
		}
	}
	return fmt.Errorf("%w after %d attempts: %w", ErrBudget, p.MaxAttempts, last)
}

The Go angle ​

Go has no general business retry policy in the standard library, but net/http.Transport does retry certain network failures on previously used connections when the request is considered idempotent and its body can be replayed. Count those hidden physical attempts when investigating load. A transport recognizing Idempotency-Key does not make a server enforce it.

Use a reused http.Client, request contexts and explicit timeouts; close response bodies and recreate request bodies before retrying where necessary. math/rand/v2 is suitable for jitter, not secrets. Go's timer can be canceled, but the supplied handler must also honor its context. The snippets target Go 1.24 and retain compatible pinned broker clients.

Laravel ​

Before ​

A generous attempt count without classification or delay can hammer a dependency and repeat an unsafe POST.

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Http;

// A hundred immediate retries, no backoff, no time limit, and no distinction
// between a dead dependency and a malformed invoice.
#[Tries(100)]
class SendInvoice implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $invoiceId) {}

    public function handle(): void
    {
        Http::timeout(5)
            ->post(config('services.billing.url').'/invoices', ['id' => $this->invoiceId])
            ->throw(); // any failure, 4xx or 5xx, becomes an instant retry
    }
}

After ​

SendInvoice stores its absolute deadline and stable billing key at dispatch. It permits only known transient status codes, uses bounded call timeouts, and explicitly enforces the six-attempt cap because the time-based Laravel policy otherwise takes precedence. Retry-After parsing is separated so its date and overflow cases can be tested without a framework boot.

php
<?php

namespace App\Support;

use DateTimeImmutable;
use DateTimeZone;

final class RetryAfter
{
    /** Delta seconds or IMF-fixdate; malformed/past values use a safe fallback. */
    public static function seconds(?string $value, int $now, int $maximum = 300): int
    {
        $value = trim($value ?? '');
        if (preg_match('/^[0-9]+$/D', $value) === 1) {
            // Avoid integer overflow; maximum+1 tells the caller not to retry early.
            $normalized = ltrim($value, '0');
            if (strlen($normalized) > strlen((string) $maximum)) {
                return $maximum + 1;
            }
            return min($maximum + 1, (int) $value);
        }
        $date = DateTimeImmutable::createFromFormat('!D, d M Y H:i:s \G\M\T', $value, new DateTimeZone('GMT'));
        if ($date !== false && $date->format('D, d M Y H:i:s \G\M\T') === $value) {
            return min($maximum + 1, max(0, $date->getTimestamp() - $now));
        }
        return 30;
    }
}
php
<?php

namespace App\Jobs;

use App\Support\RetryAfter;
use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Support\Facades\Http;
use RuntimeException;

#[MaxExceptions(6)]
class SendInvoice implements ShouldQueue
{
    use Queueable;

    // expiresAt is an absolute Unix deadline assigned once before dispatch.
    // billingKey identifies this invoice operation, unchanged on every retry.
    public function __construct(public int $invoiceId, public string $billingKey, public int $expiresAt) {}

    /** @return array<int, int> Computed once into the dispatch payload. */
    public function backoff(): array
    {
        return array_map(fn (int $n) => random_int(0, min(300, 5 * 2 ** $n)), range(0, 5));
    }

    public function retryUntil(): DateTime
    {
        return (new DateTime())->setTimestamp($this->expiresAt);
    }

    public function handle(): void
    {
        // retryUntil takes precedence over Tries: enforce the independent cap here.
        $remaining = $this->expiresAt - time();
        if ($this->attempts() > 6 || $remaining <= 0 || $this->billingKey === '') {
            $this->fail(new RuntimeException('Invoice retry budget exhausted or missing key'));
            return;
        }

        // Requires a billing API that persists and enforces Idempotency-Key.
        // Do not add Http::retry(): the queue owns this retry budget.
        $response = Http::connectTimeout(min(2, $remaining))
            ->timeout(min(5, $remaining))
            ->withHeaders(['Idempotency-Key' => $this->billingKey])
            ->post(config('services.billing.url').'/invoices', ['id' => $this->invoiceId]);

        if ($response->successful()) {
            return;
        }
        if (in_array($response->status(), [429, 503], true) && $response->header('Retry-After') !== null) {
            $payload = $this->job?->payload() ?? [];
            $delays = explode(',', (string) ($payload['backoff'] ?? '30'));
            $local = (int) $delays[min(max(0, $this->attempts() - 1), count($delays) - 1)];
            $wait = max($local, RetryAfter::seconds($response->header('Retry-After'), time()));
            $remaining = $this->expiresAt - time();
            if ($wait > 300 || $wait >= $remaining || $this->attempts() >= 6) {
                $this->fail(new RuntimeException('Retry-After exceeds retry budget'));
                return;
            }
            // Preserve the server minimum; jitter only upward within our budget.
            $wait += random_int(0, min(10, 300 - $wait, $remaining - $wait - 1));
            $this->release($wait);
            return; // release() does not stop the PHP method.
        }
        if (in_array($response->status(), [408, 429, 500, 502, 503, 504], true)) {
            $response->throw(); // transient allowlist; queue backoff applies
        }
        $this->fail(new RuntimeException('Billing rejected invoice: '.$response->status()));
    }
}

The Laravel angle ​

The Laravel 13 queue guide names “the database, Amazon SQS, Redis, and Beanstalkd drivers”; it also documents synchronous and null drivers. RabbitMQ and Kafka require external packages. Laravel's Redis queue driver uses lists and sorted sets, not Redis Streams.

Laravel controlActual behaviorPolicy implication
--tries, #[Tries], tries()Total attempts; default worker attempt count is one; zero permits unlimited triesNever confuse attempts with additional retries
retryUntil()Takes precedence over triesAdd an application guard if both caps must apply
#[RetryFor]Relative retry window; retryUntil takes precedenceUseful convenience; keep business expiry explicit
#[MaxExceptions]Counts unhandled exceptions, not every manual releaseNot a total-attempt limit
backoff() / #[Backoff]Exception retry delay; array indexed by attempt, final entry repeatsA finite array is not a finite retry count
Dispatch payloadFramework serializes backoff and retryUntilRandom array values are chosen once at dispatch
release($delay)Makes job available later; attempts still increaseReturn immediately after release
releaseUsingBackoff()Uses the current attempt's configured backoffAvoid duplicating schedule selection
dontRetry / dontRetryWhenStops retries for selected exceptionsCentralize permanent-error classification where appropriate
retry_after versus --timeoutVisibility interval versus worker execution limitTimeout should be several seconds shorter than retry_after

The randomized backoff() array spreads jobs across a fleet, but it is not freshly randomized on each execution of the same array entry. Explicit release() can calculate fresh jitter. The server-hint branch takes the larger of the current stored backoff value and the server minimum, then adds bounded upward jitter; unhandled transient failures use the stored array. It avoids nesting Http::retry() under queue retries.

A connection error can occur after the server committed the request. The billing service must durably enforce billingKey; using a random new key on each attempt defeats that contract. For successful HTTP responses with business rejection in the body, adapt classification to the API's documented contract rather than assuming every 2xx means the invoice was accepted.

Broker differences ​

RabbitMQTTL tier / quorum delayConfirmed handoff → ACKKafkaRetry topic + due headerProduce → commit; may reorderRedis StreamsZSET ID + HASH envelopeLua → XADD → remove

These are alternative implementations of waiting and handoff. Do not install all three in front of the same operation. Queue limits, retention and terminal routing must be sized for delayed backlog as well as ready work.

RabbitMQ ​

A fixed TTL tier is a durable queue with no consumers, queue-level x-message-ttl, and a DLX route back to the work queue. All messages in that tier share a lifetime. Mixed per-message TTLs in one queue are unsuitable for arbitrary scheduling because an expired item can remain behind a nonexpired head item. x-expires expires the queue itself and must not be confused with message TTL.

OptionMechanismConstraint
TTL + DLX tiersOne queue per chosen intervalCoarse delays; default dead-lettering can lose messages
Legacy delayed-message exchangex-delayed-message, x-delayed-type, x-delayProject no longer maintained; node-local Mnesia storage; no mandatory-routing guarantee
Quorum delayed retry, 4.3+min(min_delay * delivery_count, max_delay)Linear, not exponential and not jittered
Quorum delayed delivery, 4.4+Publisher sets x-opt-delivery-timeRequires quorum queue and supported broker version

The plugin README describes intended delays of seconds, minutes or hours, at most a day or two, and warns about node loss and large delayed-message populations. Its retirement and the 4.3/4.4 distinctions are verified against the current primary documentation; inspect the actual deployed version before adopting a native feature.

Native retry's x-delayed-retry-type is disabled by default; all, failed and returned select which returns wait. x-delayed-retry-min is required when enabled; max caps the delay. With a 1-second minimum and a 30-second cap, delivery count 4 means 4 seconds under the formula. Starting in 4.3, basic.nack(requeue=true) does not increment the failure delivery count as it did previously; basic.reject marks failure. Thus a return mode can repeatedly use the minimum without consuming a failure-based delivery limit. Track the application's own attempt/time budget; see DLQ for poison handling.

Native 4.4 delay routes and replicates immediately, confirms acceptance, and exposes the message to consumers at its due time. The AMQP 0-9-1 header is a long integer in Unix milliseconds; AMQP 1.0 uses the corresponding annotation. Delayed messages count toward queue-length limits. That is still eligibility, not guaranteed completion at the timestamp.

The Go TTL topology enables quorum at-least-once dead-letter strategy and reject-publish overflow explicitly. A confirmed application republish alone cannot improve an unsafe subsequent TTL→DLX transfer. Provisioning policies are often easier to change operationally than hardcoded arguments; keep declarations consistent to avoid 406 errors.

go
package rabbitmq

import (
	"context"
	"errors"
	"fmt"
	amqp "github.com/rabbitmq/amqp091-go"
	"strconv"
	"time"
)

var Tiers = []time.Duration{5 * time.Second, 30 * time.Second, 5 * time.Minute}

const Work = "orders"
const Parked = "orders.parked"

func tierName(d time.Duration) string { return fmt.Sprintf("%s.retry.%s", Work, d) }

func Declare(ch *amqp.Channel) error {
	for _, name := range []string{Work, Parked} {
		if _, err := ch.QueueDeclare(name, true, false, false, false, amqp.Table{"x-queue-type": "quorum"}); err != nil {
			return err
		}
	}
	for _, d := range Tiers {
		_, err := ch.QueueDeclare(tierName(d), true, false, false, false, amqp.Table{
			"x-queue-type": "quorum", "x-message-ttl": d.Milliseconds(),
			"x-dead-letter-exchange": "", "x-dead-letter-routing-key": Work,
			"x-dead-letter-strategy": "at-least-once", "x-overflow": "reject-publish",
		})
		if err != nil {
			return err
		}
	}
	return nil
}

// retryMessage preserves logical identity; broker-managed death/routing/delay
// metadata is deliberately excluded from the newly published envelope.
func retryMessage(d amqp.Delivery, maxAttempts int) (string, amqp.Publishing, error) {
	if maxAttempts < 1 || d.MessageId == "" {
		return "", amqp.Publishing{}, errors.New("missing ID or invalid attempt budget")
	}
	attempt := 1
	if raw, ok := d.Headers["x-attempt"]; ok {
		s, ok := raw.(string)
		if !ok {
			return "", amqp.Publishing{}, errors.New("invalid x-attempt type")
		}
		n, err := strconv.Atoi(s)
		if err != nil || n < 1 || n > maxAttempts {
			return "", amqp.Publishing{}, errors.New("invalid x-attempt")
		}
		attempt = n
	}
	headers := amqp.Table{}
	for k, v := range d.Headers {
		switch k {
		case "x-death", "x-first-death-exchange", "x-first-death-queue", "x-first-death-reason", "x-last-death-exchange", "x-last-death-queue", "x-last-death-reason", "x-delay", "x-opt-delivery-time", "CC", "BCC":
			continue
		}
		headers[k] = v
	}
	target := Parked
	if attempt < maxAttempts {
		target = tierName(Tiers[min(attempt-1, len(Tiers)-1)])
		attempt++
	}
	headers["x-attempt"] = strconv.Itoa(attempt)
	msg := amqp.Publishing{Headers: headers, DeliveryMode: amqp.Persistent,
		ContentType: d.ContentType, ContentEncoding: d.ContentEncoding, CorrelationId: d.CorrelationId,
		MessageId: d.MessageId, Type: d.Type, AppId: d.AppId, Timestamp: d.Timestamp, Body: d.Body}
	return target, msg, nil
}

// confirmed uses a fresh dedicated channel, one outstanding publish, and a
// buffered return listener. A mandatory return arrives before its confirmation.
// The supplied connection needs bounded socket writes: amqp091-go's publishing
// context does not interrupt network writes. WaitContext bounds confirmation.
func confirmed(ctx context.Context, conn *amqp.Connection, target string, msg amqp.Publishing) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()
	returns := ch.NotifyReturn(make(chan amqp.Return, 1))
	if err = ch.Confirm(false); err != nil {
		return err
	}
	confirmation, err := ch.PublishWithDeferredConfirm("", target, true, false, msg)
	if err != nil {
		return err
	}
	ack, err := confirmation.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !ack {
		return errors.New("retry publish negatively confirmed")
	}
	select {
	case r, ok := <-returns:
		if !ok {
			return errors.New("publish channel closed")
		}
		return fmt.Errorf("retry unroutable: %d %s", r.ReplyCode, r.ReplyText)
	default:
	}
	return nil
}

// Retry ACKs the input only after confirmed routing. On error stop/close the
// consuming channel and back off reconnecting; do not enter an immediate NACK loop.
func Retry(ctx context.Context, conn *amqp.Connection, d amqp.Delivery, maxAttempts int) error {
	target, msg, err := retryMessage(d, maxAttempts)
	if err != nil {
		return err
	}
	if err = confirmed(ctx, conn, target, msg); err != nil {
		return err
	}
	return d.Ack(false)
}

// PublishAt requires RabbitMQ 4.4+ quorum queues. A confirm proves replicated
// acceptance, not execution at the requested instant. Keep msg.MessageId stable.
func PublishAt(ctx context.Context, conn *amqp.Connection, msg amqp.Publishing, at time.Time) error {
	if msg.MessageId == "" || !at.After(time.Now()) {
		return errors.New("missing ID or past due time")
	}
	headers := amqp.Table{}
	for k, v := range msg.Headers {
		headers[k] = v
	}
	headers["x-opt-delivery-time"] = at.UnixMilli()
	msg.Headers = headers
	msg.DeliveryMode = amqp.Persistent
	return confirmed(ctx, conn, Work, msg)
}

The publisher uses one dedicated channel per transfer for clarity. It waits for confirmation and checks mandatory returns before ACKing the original. On failure, the caller stops and closes the consuming channel, then reconnects with backoff. Production publishers can amortize channel creation with an audited correlation mechanism; do not reuse a timed-out confirm channel blindly.

vladimir-yuldashev/laravel-queue-rabbitmq implements laterRaw() using queues named from each distinct TTL, so unbounded per-second jitter values can create many queues. The job below reuses the HTTP policy with a small tier set. The inspected stock publishing method calls basic_publish() without waiting for confirms; it must not be presented as a lossless handoff. The raw php-amqplib adapter shows the additional confirm-and-return boundary needed in an audited transport.

php
<?php

namespace App\Jobs;

// vladimir-yuldashev/laravel-queue-rabbitmq maps delay/release to TTL+DLX.
// Reuse SendInvoice's classification, deadline, stable key and attempt cap.
// The inspected stock driver calls basic_publish without waiting for confirms:
// use an audited confirmed transport when a no-loss handoff is required.
class SendInvoiceOnRabbit extends SendInvoice
{
    public function backoff(): array
    {
        return [5, 30, 300]; // bounded queue count; final tier repeats
    }
}

// SendInvoiceOnRabbit::dispatch($id, $billingKey, time() + 1800)
//     ->onConnection('rabbitmq')->delay(30);
php
<?php

namespace App\Messaging;

use PhpAmqpLib\Connection\AbstractConnection;
use PhpAmqpLib\Message\AMQPMessage;
use RuntimeException;

final class ConfirmedRabbitRetry
{
    /** Raw php-amqplib transport; connection socket timeouts must also be set. */
    public static function transfer(AbstractConnection $connection, AMQPMessage $original,
        string $declaredTier, AMQPMessage $next): void
    {
        // next retains the logical message_id, trace/schema headers and bounded
        // application attempt. Its topology must use the same policies as Go.
        $channel = $connection->channel(); // dedicated: one outstanding publish
        $confirmed = false;
        $rejected = false;
        $returned = false;
        try {
            $channel->set_ack_handler(function () use (&$confirmed) { $confirmed = true; });
            $channel->set_nack_handler(function () use (&$rejected) { $rejected = true; });
            $channel->set_return_listener(function () use (&$returned) { $returned = true; });
            $channel->confirm_select();
            $channel->basic_publish($next, '', $declaredTier, true);
            $channel->wait_for_pending_acks_returns(5.0);
            if (! $confirmed || $rejected || $returned) {
                throw new RuntimeException('Retry was not confirmed and routed');
            }
            $original->ack(); // only after accepted routing
        } finally {
            $channel->close();
        }
        // On any exception, exit and close the consuming channel for redelivery.
        // An ACK failure after successful publish can duplicate the logical message.
    }
}

Kafka ​

Kafka's record timestamp is metadata, not an instruction to deliver later. This absence is an inference from the producer/consumer API: ProducerRecord exposes timestamp, key, value and headers, while consumers fetch available log records; there is no broker-enforced per-record not-before field in this API.

A retry-topic design writes a failed record to a tier such as orders.retry.30s with application not-before-ms, attempt, stable message-id, business deadline and trace headers. A retry consumer checks eligibility. The scheduler can instead live outside Kafka and publish only when due. Neither approach turns Kafka's log into a native timer queue.

ApproachBenefitCost
Wait and block original partitionKeeps later records behind the failureHead-of-line blocking and consumer liveness budget
Publish to retry topicMain topic can continueSame-key records can overtake the failed one
External persistent schedulerFlexible due-time orderingAdditional storage and publication boundary
Transactional consume→produceCan couple Kafka output and input offsetsDoes not make external HTTP/SQL effects exactly once

The Go example preserves identity and headers, bounds attempts, validates due timestamps, disables auto commit and blocks rebalances during one bounded processing interval. It checks fetch errors across partitions. On any processing or commit error it closes its owned client; restart creates a new client at committed offsets. Reusing the advanced local fetch position would skip the failed record even without committing it.

go
package kafka

import (
	"context"
	"errors"
	"fmt"
	"github.com/twmb/franz-go/pkg/kgo"
	"strconv"
	"time"
)

var ErrExhausted = errors.New("application attempt budget exhausted")
var tierTopic = []string{"orders.retry.5s", "orders.retry.30s", "orders.retry.5m"}
var tierDelay = []time.Duration{5 * time.Second, 30 * time.Second, 5 * time.Minute}

func header(r *kgo.Record, key string) (string, error) {
	value := ""
	seen := false
	for _, h := range r.Headers {
		if h.Key == key {
			if seen {
				return "", fmt.Errorf("duplicate %s", key)
			}
			seen = true
			value = string(h.Value)
		}
	}
	return value, nil
}
func retryRecord(r *kgo.Record, maxAttempts int, now time.Time) (*kgo.Record, error) {
	if maxAttempts < 1 {
		return nil, errors.New("invalid attempt budget")
	}
	id, e := header(r, "message-id")
	if e != nil || id == "" {
		return nil, errors.New("missing or duplicate message-id")
	}
	raw, e := header(r, "attempt")
	if e != nil {
		return nil, e
	}
	attempt := 1
	if raw != "" {
		attempt, e = strconv.Atoi(raw)
		if e != nil || attempt < 1 {
			return nil, errors.New("invalid attempt")
		}
	}
	if attempt >= maxAttempts {
		return nil, ErrExhausted
	}
	i := min(attempt-1, len(tierTopic)-1)
	headers := make([]kgo.RecordHeader, 0, len(r.Headers)+2)
	for _, h := range r.Headers {
		if h.Key != "not-before-ms" && h.Key != "attempt" {
			headers = append(headers, h)
		}
	}
	headers = append(headers, kgo.RecordHeader{Key: "not-before-ms", Value: []byte(strconv.FormatInt(now.Add(tierDelay[i]).UnixMilli(), 10))}, kgo.RecordHeader{Key: "attempt", Value: []byte(strconv.Itoa(attempt + 1))})
	// Keeping the key selects a partition WITHIN this topic; it does not preserve
	// order with records that continue through the original topic.
	return &kgo.Record{Topic: tierTopic[i], Key: r.Key, Value: r.Value, Headers: headers}, nil
}

// Caller commits the original only after this succeeds; a crash between produce
// and commit can duplicate the logical message. Use stable-ID idempotency.
func Schedule(ctx context.Context, cl *kgo.Client, r *kgo.Record, maxAttempts int) error {
	next, err := retryRecord(r, maxAttempts, time.Now())
	if err != nil {
		return err
	}
	return cl.ProduceSync(ctx, next).FirstErr()
}

func dueTime(r *kgo.Record, now time.Time) (time.Time, error) {
	raw, e := header(r, "not-before-ms")
	if e != nil {
		return time.Time{}, e
	}
	ms, e := strconv.ParseInt(raw, 10, 64)
	if e != nil || ms <= 0 {
		return time.Time{}, errors.New("invalid not-before-ms")
	}
	due := time.UnixMilli(ms)
	if due.After(now.Add(5*time.Minute + 5*time.Second)) {
		return time.Time{}, errors.New("due time exceeds tier/skew bound")
	}
	return due, nil
}

// RunRetryTier owns and CLOSES its client on every exit. Restart by constructing
// a fresh client so a failed poll cannot leave an advanced local fetch position.
// This deliberately simple loop blocks all of its assigned partitions while
// waiting. Use dedicated tier workers; per-partition concurrency is a separate design.
func RunRetryTier(ctx context.Context, brokers []string, topic, group string, process func(context.Context, *kgo.Record) error) error {
	cl, err := kgo.NewClient(kgo.SeedBrokers(brokers...), kgo.ConsumeTopics(topic), kgo.ConsumerGroup(group), kgo.DisableAutoCommit(), kgo.BlockRebalanceOnPoll(), kgo.RebalanceTimeout(10*time.Minute))
	if err != nil {
		return err
	}
	defer cl.Close()
	for {
		if err := ctx.Err(); err != nil {
			return err
		}
		fetches := cl.PollRecords(ctx, 1)
		if errs := fetches.Errors(); len(errs) > 0 {
			cl.AllowRebalance()
			return fmt.Errorf("fetch: %w", errs[0].Err)
		}
		records := fetches.Records()
		if len(records) == 0 {
			cl.AllowRebalance()
			continue
		}
		err := processOne(ctx, cl, records[0], process)
		cl.AllowRebalance()
		if err != nil {
			return err
		}
	}
}
func processOne(ctx context.Context, cl *kgo.Client, r *kgo.Record, process func(context.Context, *kgo.Record) error) error {
	due, err := dueTime(r, time.Now())
	if err != nil {
		return err
	}
	if wait := time.Until(due); wait > 0 {
		tp := map[string][]int32{r.Topic: {r.Partition}}
		cl.PauseFetchPartitions(tp)
		defer cl.ResumeFetchPartitions(tp)
		timer := time.NewTimer(wait)
		defer timer.Stop()
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-timer.C:
		}
	}
	callCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	if err := callCtx.Err(); err != nil {
		return err
	}
	if err := process(callCtx, r); err != nil {
		return err
	}
	return cl.CommitRecords(callCtx, r)
}

PauseFetchPartitions only pauses fetching. The simple sequential loop's timer blocks processing for all partitions assigned to that loop, not merely the paused one. Its maximum wait plus the shared handler-and-commit timeout is below the configured rebalance timeout; this requires the handler to respect its context. A production per-partition scheduler needs bounded buffers, revocation coordination and fair resumption. Java/librdkafka max.poll.interval.ms is a related liveness constraint, not a franz-go option with the same name.

Keeping the same key preserves partition affinity within the chosen retry topic, not sequence relative to the original topic. Synchronous publish followed by input commit remains at-least-once across that handoff. Producer idempotence does not deduplicate a logical record republished after a crash.

For PHP, mateusjunges/laravel-kafka documents bounded in-process retryFailedMessages: its parameter counts additional retries, and its backoff unit is milliseconds. The handler blocks this consumer while retrying. Its default exhausted-failure behavior advances past the failed message; stopOnFailure() below instead closes the consumer so a supervised restart can resume from committed progress. The retry count resets after a process restart, so use a durable operation budget for an outage that spans restarts. Terminal parking belongs to the DLQ policy.

php
<?php

namespace App\Messaging;

use Illuminate\Http\Client\ConnectionException;
use Junges\Kafka\Facades\Kafka;
use Throwable;

final class RetryOrders
{
    /** The handler must be idempotent and bound each dependency call's timeout. */
    public static function consume(callable $handler): void
    {
        Kafka::consumer(['orders'])
            ->withConsumerGroupId('orders-worker')
            ->withHandler($handler)
            // Three retries AFTER the first call: four handler calls at most.
            ->retryFailedMessages(3, backoffInMs: 1000,
                when: fn (Throwable $e) => $e instanceof ConnectionException)
            // Default package failure handling skips failed records. Stop instead;
            // supervisor restarts with delay. Permanent failures need the DLQ policy.
            ->stopOnFailure()
            ->build()
            ->consume();
    }
}

Redis Streams ​

Redis Streams does not supply a scheduled-delivery timestamp. A sorted set supplies a due-time index; a separate hash stores envelopes; a bounded Lua script moves due IDs into the stream. ZRANGE ... BYSCORE is the current command form; the older ZRANGEBYSCORE form is deprecated since Redis 6.2 but remains used in some framework internals.

The shared Lua scripts use Redis server time and validate types before mutation. Go embeds the files and PHP loads exactly those files, keeping their behavior aligned. The sample uses Redis 7+ as an operational baseline for server-time scripting and current ZRANGE syntax. Delays are limited to 24 hours and batches to 100 by this example's policy, not by Redis's generic sorted-set limit.

go
package redis

import (
	"context"
	_ "embed"
	"errors"
	goredis "github.com/redis/go-redis/v9"
	"time"
)

const delayedKey = "{orders}:delayed"
const payloadKey = "{orders}:payloads"
const streamKey = "{orders}:ready"

//go:embed schedule.lua
var scheduleLua string

//go:embed move.lua
var moveLua string
var scheduleScript = goredis.NewScript(scheduleLua)
var moveScript = goredis.NewScript(moveLua)

type Pending struct {
	ID, Payload string
	Delay       time.Duration
}

func (p Pending) validate() error {
	if len(p.ID) < 1 || len(p.ID) > 200 || p.Delay < 0 || p.Delay > 24*time.Hour || p.Delay%time.Millisecond != 0 {
		return errors.New("invalid message ID or delay (whole milliseconds, 0..24h)")
	}
	return nil
}

// Schedule uses the ID as member and stores the envelope separately. Different
// IDs with identical payloads remain separate. The same pending ID replaces its
// payload/due time; callers must retain its business identity across attempts.
func Schedule(ctx context.Context, rdb goredis.UniversalClient, p Pending) error {
	if err := p.validate(); err != nil {
		return err
	}
	return scheduleScript.Run(ctx, rdb, []string{delayedKey, payloadKey}, p.ID, p.Payload, p.Delay.Milliseconds()).Err()
}

// Tick uses Redis server time. Lua serializes competing schedulers; it does not
// guarantee rollback or durable replication. Deduplicate by message_id downstream.
func Tick(ctx context.Context, rdb goredis.UniversalClient, batch int) (int64, error) {
	if batch < 1 || batch > 100 {
		return 0, errors.New("batch must be 1..100")
	}
	return moveScript.Run(ctx, rdb, []string{delayedKey, payloadKey, streamKey}, batch).Int64()
}
func Run(ctx context.Context, rdb goredis.UniversalClient) error {
	ticker := time.NewTicker(500 * time.Millisecond)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-ticker.C:
			if _, err := Tick(ctx, rdb, 100); err != nil {
				return err
			}
		}
	}
}
lua
-- One Redis Cluster slot; client prefixes must preserve the same hash tag.
local function check(key, expected)
  local kind = redis.call('TYPE', key).ok
  if kind ~= 'none' and kind ~= expected then error('WRONGTYPE scheduler key') end
end
check(KEYS[1], 'zset')
check(KEYS[2], 'hash')
local delay = tonumber(ARGV[3])
if not delay or delay < 0 or delay > 86400000 or delay ~= math.floor(delay) then
  return redis.error_reply('invalid delay')
end
if #ARGV[1] == 0 or #ARGV[1] > 200 then return redis.error_reply('invalid message ID') end
local t = redis.call('TIME')
local due = t[1] * 1000 + math.floor(t[2] / 1000) + delay
redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
redis.call('ZADD', KEYS[1], due, ARGV[1])
return due
lua
local function check(key, expected)
  local kind = redis.call('TYPE', key).ok
  if kind ~= 'none' and kind ~= expected then error('WRONGTYPE scheduler key') end
end
check(KEYS[1], 'zset')
check(KEYS[2], 'hash')
check(KEYS[3], 'stream')
local batch = tonumber(ARGV[1])
if not batch or batch < 1 or batch > 100 or batch ~= math.floor(batch) then
  return redis.error_reply('invalid batch')
end
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local due = redis.call('ZRANGE', KEYS[1], '-inf', now, 'BYSCORE', 'LIMIT', 0, batch)
-- Validate the complete batch before any move; scripts do not roll back writes.
for _, id in ipairs(due) do
  if not redis.call('HGET', KEYS[2], id) then return redis.error_reply('missing payload') end
end
for _, id in ipairs(due) do
  local payload = redis.call('HGET', KEYS[2], id)
  redis.call('XADD', KEYS[3], '*', 'message_id', id, 'payload', payload)
  redis.call('ZREM', KEYS[1], id)
  redis.call('HDEL', KEYS[2], id)
end
return #due
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Redis;
use InvalidArgumentException;
use RuntimeException;

final class RedisScheduler
{
    private const DUE = '{orders}:delayed';
    private const PAYLOADS = '{orders}:payloads';
    private const STREAM = '{orders}:ready';

    // Keep the two shared Lua files beside these snippets when deploying them.
    private static function script(string $name): string
    {
        $lua = file_get_contents(__DIR__.'/../go/redis/'.$name.'.lua');
        if ($lua === false) {
            throw new RuntimeException('Missing scheduler Lua script');
        }
        return $lua;
    }

    public static function schedule(string $id, string $envelope, int $delayMs): void
    {
        if ($id === '' || strlen($id) > 200 || $delayMs < 0 || $delayMs > 86400000) {
            throw new InvalidArgumentException('Invalid ID or delay');
        }
        // Same pending ID updates the schedule; identical payloads with different
        // IDs remain separate. Redis server time determines the due score.
        Redis::eval(self::script('schedule'), 2, self::DUE, self::PAYLOADS, $id, $envelope, $delayMs);
    }

    public static function tick(int $batch = 100): int
    {
        if ($batch < 1 || $batch > 100) {
            throw new InvalidArgumentException('Batch must be 1..100');
        }
        return (int) Redis::eval(self::script('move'), 3, self::DUE, self::PAYLOADS, self::STREAM, $batch);
    }
}

Two scheduler instances cannot interleave inside one script. That does not make the system exactly once: a lost response, rescheduling after the item has already moved, Redis failover, or consumer redelivery can repeat an effect. In particular, the script stores a new stream entry ID while preserving the logical ID in message_id. Deduplicate the latter.

All three keys use {orders} so Redis Cluster places them in one slot. Check the effective keys after Laravel/client prefixing; an earlier brace pair in a prefix can change the chosen tag. A larger deployment can shard schedulers across multiple tags, with each atomic move confined to one tag. Atomic scripts do not create cross-slot transactions.

If the incoming work is already in a stream, schedule successfully before XACK; an ambiguous schedule result must leave the source recoverable. Laravel's built-in Redis queue already manages delayed jobs with sorted sets and lists, but it does not run this Streams scheduler. Queue internals explains that driver separately.

In production systems ​

  • AWS's published contention simulation demonstrates why unjittered exponential delays keep clusters of retries; its Builders' Library documents retries as extra load and describes token-bucket limiting.
  • RabbitMQ documents head-of-line effects for per-message TTL, and separately documents quorum native delayed retry/delivery with version-specific availability. These are product behaviors, not interchangeable implementation details.
  • Laravel serializes job retry metadata in the dispatch payload. Its documented precedence and release behavior explain why combining a deadline with tries is not a simple logical AND.
  • Google's SRE book distinguishes request-level and client-level retry budgets, which is why a perfectly bounded individual job can still participate in a fleet-wide outage.

Choosing a policy ​

SituationRecommendationWhy
Read-only call with short transient errorsSmall local attempt cap + Full Jitter + deadlineLow scheduling overhead within request latency budget
Side-effecting API with unknown outcomeStable idempotency key or reconciliation firstRetry may repeat an already committed action
Invalid schema / revoked accessStop and classify terminallyTime cannot repair the input or permission
429 with valid server hintHonor not-before, add bounded upward jitterAvoids disobeying the server's recovery policy
Minutes-long downstream outageDurable delayed attempts and shared token budgetFrees workers without an uncontrolled recovery surge
Few standard RabbitMQ delaysTTL tiers with audited DLX safetyPredictable topology and visible backlog
Arbitrary RabbitMQ due time on quorum 4.4+Native delayed deliveryNo legacy plugin timer store
Kafka order must survive failureBlock key/partition with explicit liveness planRetry-topic detours permit overtaking
Redis Streams due-time schedulingID-indexed ZSET + envelope HASH + bounded LuaExplicit identity and atomic local movement
Days-long business processDurable workflow timerNeeds durable process state beyond retry timing

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

An invoice-export command calls one billing API. Start with an explicit HTTP timeout, stable invoice operation key, an allowlist classifier and a short local retry wrapper. If a result is needed during the user's request, the outer deadline must include all waits. Persist a job when completing the operation later is acceptable; an in-memory goroutine is not a durable queue.

Modular monolith: shared deployment, separate ownership ​

The Billing module owns the invoice attempt policy; the HTTP adapter reports categorized errors and does not silently add another retry loop. A database budget row preserves count and deadline across queue worker restarts. If changing business state and scheduling the next attempt must succeed together, use the outbox boundary rather than hoping both writes finish.

Microservices: one operation across several services ​

Order sends an invoice command; Billing calls a provider; Notification announces completion. Retrying the whole Order→Billing→Notification chain after one provider timeout can repeat already successful steps. Put retry ownership at the failing dependency boundary and retain the operation key. Use sagas for compensation and outbox for reliable publication, without resetting the retry deadline at each service hop.

Distributed data: clocks, replicas and failover ​

A scheduler stores due times on one node and a worker reads them on another. Clock skew can make “due” disagree; replica lag can hide a newly scheduled operation; failover can lose unreplicated writes. Use authoritative scheduler time where feasible, primary reads for scheduling decisions, and explicit durability requirements. A deduplication retention window must cover the maximum retry/redelivery horizon, or an old retry can become a new effect after its identity record expires.

Scaling path: 1×, 10×, 100× ​

StageChangeConcrete reason
1×One owner, bounded local policyFew invoice jobs; keep behavior understandable
10×Durable delay tiers, per-dependency retry tokens, backlog-age metricsOutage no longer ties up every worker
100×Sharded scheduler ownership, tenant fairness, controlled recovery drainOne noisy tenant or recovered dependency must not consume the fleet

At higher scale, measure original operations, retry attempts, success-after-retry, budget exhaustion, scheduled depth, and lateness separately. A large delayed backlog with zero ready lag is still unresolved work. Messaging observability owns instrumentation details.

Lab: inspect the failure boundaries ​

The broker/database experiments below are expected, not run. No Docker, Compose or broker clusters were started. The Go boundary tests and standalone PHP parser test are local checks that do not require a broker; framework integration, replication failures and real scheduling latency remain unverified here.

1. Local policy and parser checks ​

bash
cd docs/snippets/messaging/retry-backoff-delayed/go
gofmt -l .
go vet ./...
go test ./...
cd ../php
php RetryAfterTest.php
# Expected: no gofmt output, Go packages pass, Retry-After boundaries passed.

The tests cover signed-duration saturation, invalid policy values, already-canceled contexts, exact attempt counting, preserved retry metadata, malformed Kafka due headers, Redis input limits, and delta/date/overflow forms of Retry-After.

2. Two workers and one database budget ​

On an existing PostgreSQL instance, create the example table and seed row. Run the conditional update from two SQL clients using the same ID and a 30-second delay.

text
1 Client A: reserves next attempt, setting next_attempt_at 30 seconds ahead
2 Client B: reevaluates the row; next_attempt_at is not due, gets zero rows
3 Move deadline into the past; either client now gets zero rows
4 Expected: restarting the worker does not reset attempts or extend deadline

This experiment reserves budget only. Do not publish on zero rows, and do not claim the update alone solved atomic scheduling.

3. RabbitMQ route failure and crash gap ​

On an existing test broker, declare the example work/tier queues. In one consumer, receive without auto ACK; in the publisher path, deliberately target a nonexistent queue with mandatory publishing.

text
1 Retry publish targets missing.queue -> basic.return 312 NO_ROUTE
2 Expected: transfer returns an error, source remains unacknowledged
3 Restore routing; publish retry successfully, kill worker before source ACK
4 Expected: original can redeliver and retry copy can arrive; same business key deduplicates

For TTL behavior, compare one tier queue per lifetime with a mixed per-message TTL queue. Observe that the latter's expired short-lived record can remain behind a longer-lived head. Do not infer timing precision from a quiet test broker.

4. Kafka overtaking and restart ​

Use an existing test topic with two records for the same key: A then B. Move failing A to the retry topic and commit its original offset only after produce succeeds.

text
1 Main consumer: A fails -> retry topic, then B succeeds
2 Retry consumer: A is not due yet -> waits; later A succeeds
3 Expected: completion order B then A, despite preserving the key
4 Kill retry worker before commit; restart with a NEW client
5 Expected: uncommitted A is eligible for redelivery; dedup handles prior effect

Also inject an invalid not-before-ms. Expected: the example exits instead of immediately executing the malformed schedule. A production terminal policy must decide how to isolate the bad record.

5. Redis identity and concurrent drain ​

Against an existing Redis 7+ test instance, call Schedule twice with different IDs, the same payload, and zero delay. Run two Tick(..., 100) callers concurrently.

text
1 Schedule id-A -> payload X; schedule id-B -> payload X
2 Expected: two sorted-set members and two envelopes, not one overwritten member
3 Two drainers execute Lua serially -> each pending ID moves once in this healthy run
4 Expected: stream contains message_id A and B; scheduler structures are empty
5 Reschedule id-A after it moved -> another stream entry may exist; logical dedup still required

Replace the payload hash with an incompatible type in an isolated test namespace. Expected: type validation fails before movement. This checks a known script failure boundary; it is not evidence that all runtime failures roll back.

Common misconceptions ​

BeliefReality
A timeout means nothing happenedThe server may have committed before the response was lost
Three retries always means three attemptsAPIs disagree; define whether the first attempt is included
Exponential backoff prevents stormsCorrelated workers still align; add jitter and a shared budget
A maximum delay is a retry limitThe operation can repeat at the cap forever without another limit
Every 4xx is permanent408, 429 and domain-specific conflicts need separate treatment
Retry-After is always a numberHTTP dates are valid; parse deliberately
Delayed delivery means exact execution timeIt means eligibility; backlog and capacity can make it late
Successful publish call permits ACKConfirmed routing and acceptance are separate from local buffering
Same Kafka key preserves order across retry topicsDifferent topics have independent logs and processing paths
Redis Lua is a rollback transactionScripts run atomically but do not roll back prior writes on every error
Laravel tries and retryUntil both cap executionThe time-based policy takes precedence; add a separate count guard if needed
release() ends the PHP methodIt schedules another attempt; return explicitly
New transport ID means a new business operationPreserve logical identity across deliveries

Cheat sheet ​

TopicRemember
ClassifierAllowlist transient failures; unknown is not automatically retryable
SafetyTimeout can mean success with a lost response; keep idempotency key
CountingN total attempts means N-1 retries
TimeOverall deadline includes queue wait, backoff and execution
Full JitterU(0, min(cap, base*2^k)); saturate before multiplication
Equal JitterKeep half the envelope and randomize the other half
Decorrelated JitterNext envelope depends on previous randomized delay
AmplificationMultiply independent layer attempt counts
Fleet guardShared retry tokens plus concurrency controls
RabbitMQConfirm + mandatory route check before ACK; audit DLX safety separately
KafkaDue header is application data; retry topics permit overtaking
Redis StreamsZSET IDs + HASH envelopes + bounded same-slot Lua
LaravelretryUntil wins over tries; releases count; final backoff entry repeats
RecoveryBound backlog drain and inspect scheduled lateness

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A billing POST times out. Why is immediate repetition unsafe even if the error is transient? Must-know ​

Answer

Answer: The provider may already have committed. Repeat only under an idempotency contract with the same operation key, or reconcile the result first.

2 — Three layers each allow three total attempts. How many calls can reach the final dependency? Must-know ​

Answer

Answer: Up to 27. If each allowed three retries after the initial call, the upper bound would instead be 64.

3 — What is the difference between cap, attempt budget and deadline? Must-know ​

Answer

Answer: The cap limits one delay, the attempt budget limits starts, and the deadline limits the operation's useful lifetime. None substitutes for the other two.

4 — Why can an expired RabbitMQ message still occupy a mixed-TTL queue? Good to know ​

Answer

Answer: Per-message expiration cleanup/dead-lettering has head-of-line constraints; a shorter-lived item can wait behind an unexpired head. Fixed queue-level TTL tiers avoid mixing those lifetimes.

5 — A RabbitMQ publish is confirmed but mandatory routing returned the message. May the source be ACKed? Important ​

Answer

Answer: No. An unroutable message can still be confirmed. Both acceptance and routing must be checked.

6 — Why does a retry topic break original per-key completion order even if the key is unchanged? Important ​

Answer

Answer: The original and retry topics are independent logs and processing paths; later original records can complete while the failed record waits.

7 — What goes wrong when Redis uses the whole payload as the ZSET member? Good to know ​

Answer

Answer: Identical payloads coalesce because members are unique. Use distinct stable message IDs and separate envelope storage.

8 — How should a valid Retry-After beyond the job deadline be handled? Important ​

Answer

Answer: End this retry policy or transfer to a separately authorized longer-lived process. Do not shorten the server's minimum and retry early.

9 — Does defining Laravel tries=6 and retryUntil() enforce both limits? Important ​

Answer

Answer: No. The time-based method takes precedence. Enforce an independent application count guard if both limits are required.

10 — Why is a successful Lua move not an exactly-once business guarantee? Must-know ​

Answer

Answer: Atomic execution only prevents interleaving within that Redis operation. Failover, ambiguous responses, rescheduling and downstream redelivery can still repeat effects.

Glossary ​

TermMeaning
Retry policyClassification, limits, timing and terminal outcome for repeated work
Transient / permanent failureA failure that may heal without changing intent / one needing a corrective change
Ambiguous outcomeCaller cannot tell whether the remote effect committed
Idempotency key / logical message IDStable identity of one business operation across deliveries
Attempt / retryOne execution / an additional execution after failure
Attempt budget / MaxAttemptsMaximum total starts, including the first in this chapter
Deadline / time budgetLatest useful time for more work on the operation
Per-attempt timeout / cancellationBound on one call / request to stop cooperative execution
Backoff / base / capWaiting policy / initial envelope / maximum envelope
Constant / linear / exponential backoffFixed / arithmetically growing / multiplicatively growing delay
JitterRandom timing variation that spreads correlated callers
Full JitterUniform delay from zero through the current envelope
Equal JitterHalf the envelope plus random delay over the remaining half
Decorrelated JitterDelay drawn using the previous randomized delay
Retry amplification / retry stormMultiplication of physical work / synchronized or excessive retry load
Shared retry budget / token bucketFleet/client allowance for extra attempts / burst-and-refill implementation
Circuit breaker / half-open probeDependency admission state / limited recovery trial
Delayed delivery / not-before timeEligibility after a due time, not exact-time execution
Message expiration / maximum ageBusiness or transport limit after which work is no longer useful
Retry-After / IMF-fixdateHTTP minimum-wait hint / canonical HTTP date format
Clock skew / latenessClock disagreement / actual start minus scheduled due time
Durable handoffTransferring responsibility before settling current delivery
Publisher confirm / mandatory returnRabbitMQ acceptance signal / unroutable-publication signal
TTL / DLX / delay tierMessage lifetime / dead-letter exchange / queue or topic for a delay class
x-message-ttl / expiration / x-expiresRabbitMQ queue-level message TTL / per-message TTL / unused-queue expiration
x-delay / x-delayed-messageLegacy RabbitMQ plugin header / exchange type
x-opt-delivery-timeRabbitMQ native quorum delivery timestamp, Unix milliseconds
x-delayed-retry-min/max/typeRabbitMQ quorum native linear retry controls
delivery-count / x-acquired-countRabbitMQ failed-delivery count / consumer-assignment count
Head-of-line blocking / overtakingEarlier work holds later work / later work completes first
Retry topic / not-before-msKafka retry path / application-owned due-time header
Offset commit / rebalanceKafka recovery-position update / group ownership redistribution
BlockRebalanceOnPoll / PauseFetchPartitionsfranz-go processing ownership option / fetch suspension
Sorted set / ZSET / scoreRedis ordered unique-member collection / its abbreviation / ordering number
HASH envelope store / message_idPayload storage indexed by logical ID / identity carried into stream entries
ZRANGE ... BYSCORE / XADDRedis due-range selection / stream append
Lua atomicity / rollbackNo command interleaving / undo of prior writes, which scripts do not generally supply
Hash tag / CROSSSLOTRedis Cluster co-location marker / error for incompatible multi-key placement
backoff / release / releaseUsingBackoffLaravel exception delay / explicit rescheduling / configured-delay release
retryUntil / RetryFor / Tries / MaxExceptionsLaravel deadline / relative window / attempt count / unhandled-exception count
retry_after / --timeoutLaravel connection redelivery interval / worker execution limit
dontRetry / dontRetryWhenLaravel exception types or predicate that end retries
retryFailedMessages / stopOnFailureLaravel Kafka local retries / close-on-failure behavior
at-least-once dead-letter strategy / reject-publishRabbitMQ safer DLX transfer / reject new publications at overflow
Recovery drain / tenant fairnessRate of delayed-backlog release / sharing capacity across customers

References ​

All sources below were fetched and saved during the chapter review; reference URLs returned HTTP 200. Broker behaviors are version-qualified where required. No broker experiment is claimed as executed.

Built by Morteza Negahi