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 checklist | One minute |
| Which failures deserve another attempt | Classification |
| Attempt counting, deadlines and cancellation | Budgets |
| Exact jitter formulas | Backoff and jitter |
| Preventing a retry storm | Amplification |
| Deciding where waiting happens | Delay placement |
| RabbitMQ versions, Kafka topics, Redis Lua | Broker differences |
Laravel backoff, retryUntil, release | Laravel |
| A review and failure-injection exercise | Lab |
Everything in one minute
| Question | Policy decision | Example |
|---|---|---|
| Can repeating succeed? | Classify the failure | Temporary 503 versus invalid invoice |
| Can repeating cause damage? | Require an idempotency contract | Same billing operation key on every POST |
| How much work is allowed? | Total attempts, including the first | 6 attempts means at most 5 retries |
| How long is it useful? | Absolute deadline plus per-attempt timeout | Stop the operation after 30 minutes |
| When is another call allowed? | Backoff, jitter, server hints | max(local_delay, Retry-After) |
| Where does the wait live? | Memory, broker, or persistent scheduler | 100ms locally; minutes in durable storage |
| What protects the dependency? | A shared retry budget | Retry tokens separate from original traffic |
| What happens at exhaustion? | An explicit terminal policy | Fail, park, reconcile, or escalate |
| Mechanism | What it provides | What it does not provide |
|---|---|---|
| Exponential backoff | Increasing delay envelope | Random spreading or a finite lifetime |
| Jitter | Less synchronization across workers | Less total work unless a budget also exists |
| Delayed delivery | A not-before time | An exact execution time or reserved worker capacity |
| Publisher confirmation | Broker acceptance of a publication | Consumer business success |
| Retry topic | A separate Kafka failure path | Ordering with the original topic |
| Redis sorted set | Due-time indexing | A Streams scheduling feature by itself |
Laravel retryUntil() | Time-based job admission limit | A 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 recovery | Protect the system |
|---|---|
| Retry a short network interruption | Do not retry bad credentials indefinitely |
| Wait through a deployment | Do not occupy every worker while waiting |
| Preserve pending work across crashes | Bound scheduled storage and message age |
| Continue unrelated orders | Accept or explicitly prevent overtaking |
| Honor the server's recovery hint | Stop 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.
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.
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 contractReal 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.
| Failure | Default decision | Required condition |
|---|---|---|
| Connection reset / timeout | Bounded retry | Repetition safe; outcome may be ambiguous |
| HTTP 408, 429, 502, 503, 504 | Candidate for retry | Endpoint contract and remaining budget |
| HTTP 400 / schema rejection | Stop | Correct the input before a new operation |
| HTTP 401 / 403 | Stop or one controlled credential refresh | Never hide a persistent permission error in retries |
| HTTP 409 | Domain-specific | Refresh version/state when the API requires it |
| Unknown exception | Stop by default | Add an explicit retryable category after investigation |
| Cancellation / expired operation | Stop | Caller 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.
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 clockFor 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.
| Limit | Persist or propagate | Common mistake |
|---|---|---|
| Total attempts | Across republishing and worker restarts | Resetting to zero on every retry topic |
| Absolute deadline | In the logical operation envelope | Recomputing “now + 30 minutes” on every execution |
| Per-call timeout | Into the actual HTTP/DB/client operation | Timing only the sleep loop |
| Maximum message age | From business creation time | Treating a fresh delivery as fresh business intent |
| Shared retry allowance | Across the callers it protects | Giving 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.
-- 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.-- 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.
| Policy | Delay formula | Consequence |
|---|---|---|
| Immediate | 0 | Useful only for carefully bounded local races; otherwise a hot loop |
| Constant | b | Simple but synchronized across callers |
| Linear | min(C, b * (k+1)) | Slower growth; RabbitMQ native delayed retry uses delivery count |
| Exponential without jitter | B(k) | Reduces frequency but keeps cohorts together |
| Full Jitter | U(0, B(k)) | Mean approximately B(k)/2; zero is allowed |
| Equal Jitter | B(k)/2 + U(0, B(k)/2) | Minimum half the envelope; mean about 3B(k)/4 |
| Decorrelated Jitter | min(C, U(b, 3 * previous_delay)) | Carries previous-delay state; initialize it to b |
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 operationUse 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.
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 failureAt 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.
| Guard | What it limits | Important scope |
|---|---|---|
| Per-operation attempt cap | Work caused by one message | Persist across redeliveries |
| Token bucket for retries | Extra calls over time with a finite burst | Per dependency; coordinate or divide across workers |
| Retry-to-original ratio | Retry traffic relative to new work | Define denominator and window explicitly |
| Concurrency limit | Calls simultaneously in flight | Include retries in the same dependency limit |
| Circuit breaker | Attempts while dependency is unhealthy | Half-open probes also need a budget |
| Controlled backlog drain | Recovery traffic | Fairness 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.
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.
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| Placement | Best fit | Cost / failure boundary |
|---|---|---|
| Short cancellable timer | Small transient disturbance within request budget | Occupies an execution slot |
| RabbitMQ TTL tier | A small finite set of delay classes | Approximate time; DLX transfer needs its own safety configuration |
| RabbitMQ quorum native delay | Per-message due time on supported versions | Version and queue-type dependency |
| Kafka retry topic | Decouple failed records from main traffic | Scheduler/consumer logic; original ordering changes |
| Redis ZSET scheduler | Explicit due-time index | Application owns payload identity, atomic movement and persistence |
| Durable workflow timer | Days-long business coordination | Broader 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.
| Input | Meaning | Action in the PHP helper |
|---|---|---|
120 | Wait at least 120 seconds | Use 120, then bounded upward jitter |
| Valid IMF-fixdate | Wait until the given GMT date | Convert relative to current wall clock |
| Date in the past | Minimum is already satisfied | Zero minimum; local policy may still wait |
| Invalid or negative text | Not a valid delta | Use documented fallback of 30 seconds |
| Huge numeric value | Beyond the example's 300-second horizon | Return over-limit marker; job fails instead of retrying early |
| Hint after job deadline | Work would no longer be useful | End 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.
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 path | Acceptance before settlement | Residual risk |
|---|---|---|
| RabbitMQ republish | Publisher confirm and mandatory-return check | Duplicate if original ACK is lost; TTL→DLX has separate guarantees |
| Kafka retry topic | Synchronous successful produce before input commit | Duplicate on crash before commit; transactions are a separate design |
| Redis scheduler | Successful schedule script before original XACK | Retry 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 property | Example implementation | Boundary |
|---|---|---|
| Identity | ID in ZSET, envelope in HASH | IDs must not collide across business operations |
| Due clock | Redis TIME | Redis clock still needs operational discipline |
| Concurrent drainers | One bounded Lua script | Serial execution is not rollback |
| Redis Cluster locality | {orders} in every key | Client prefixes must retain the effective hash tag |
| Bounded work | At most 100 items per tick | One Lua script blocks other commands while running |
| Delivery | XADD before removing pending ID | Persistence/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 / signal | Product and unit | Interpretation |
|---|---|---|
MaxAttempts, PerAttempt, outer context | This Go example; count / duration / deadline | All three bounds are independent |
x-message-ttl | RabbitMQ queue argument; milliseconds | Message lifetime within a queue, used for a fixed delay tier |
expiration | RabbitMQ message property; decimal millisecond string | Per-message TTL; mixed values create head-of-line effects |
x-expires | RabbitMQ queue argument; milliseconds | Deletes an unused queue; not a message delay |
x-delay | RabbitMQ legacy plugin; milliseconds | Delay before routing through its custom exchange |
x-opt-delivery-time | RabbitMQ quorum 4.4+; Unix milliseconds | Native publisher-requested not-before time |
x-delayed-retry-min/max/type | RabbitMQ quorum 4.3+; milliseconds / mode | Native linear redelivery policy |
not-before-ms, attempt | Application Kafka headers | Kafka itself does not schedule from these names |
DisableAutoCommit, BlockRebalanceOnPoll | franz-go options | Manual settlement with bounded ownership during processing |
ZRANGE ... BYSCORE, LIMIT | Redis | Due selection with an explicit batch bound |
backoff(), release($delay) | Laravel 13; seconds or supported date forms | Exception schedule versus explicit release |
retryUntil(), #[RetryFor] | Laravel 13; absolute time / relative window | Time-based attempt policy |
retry_after, --timeout | Laravel queue connection / worker; seconds | Redelivery visibility versus worker execution time; neither is backoff |
| Failure signal | Response |
|---|---|
AMQP 312 NO_ROUTE / mandatory return | Do not ACK source; fix routing and reconnect with backoff |
AMQP 406 PRECONDITION_FAILED | Fix mismatched queue declaration; retrying the same declaration cannot help |
| AMQP negative publisher confirm / connection loss | Keep source unsettled; outcome can be ambiguous |
| Kafka produce or commit failure | Exit the simple loop; restart with a new client and committed offsets |
Malformed not-before-ms | Stop/route to invalid-message policy; never treat as epoch zero |
Redis WRONGTYPE / missing payload | Repair scheduler state; repeating unchanged input is not a fix |
Redis CROSSSLOT | Correct effective key hash tags; backoff cannot repair key design |
Go context.Canceled / DeadlineExceeded on outer context | Stop new attempts |
Laravel MaxAttemptsExceededException | Inspect attempts, releases and time policy; follow terminal handling |
Solving the recurring problems
| Problem | Solution | Benefit | Cost / limit |
|---|---|---|---|
| Brief dependency blip | Few cancellable local retries | Small latency overhead | Occupies a worker and consumes request deadline |
| Minutes-long outage | Persist delayed attempts | Frees workers | More storage and handoff paths |
| Simultaneous recovery surge | Jitter plus shared retry tokens | Bounds burst and ongoing retry load | Coordination/fairness policy |
| Business deadline passed | Stop before another call | Avoids stale effects | Needs an explicit terminal outcome |
| Retry publication failed | Keep original unsettled | Avoids acknowledge-before-publish loss | Can duplicate on ambiguous acceptance |
| Strict same-key sequence required | Keep partition/key blocked or use a coordinated gate | Prevents overtaking | Head-of-line blocking; see ordering chapter |
| Same payload appears twice | Distinct stable IDs in scheduler | Both messages survive | Requires real operation identity |
| Count resets after restart | Durable envelope or budget row | Cap remains meaningful | State 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.
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.
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
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
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
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 control | Actual behavior | Policy implication |
|---|---|---|
--tries, #[Tries], tries() | Total attempts; default worker attempt count is one; zero permits unlimited tries | Never confuse attempts with additional retries |
retryUntil() | Takes precedence over tries | Add an application guard if both caps must apply |
#[RetryFor] | Relative retry window; retryUntil takes precedence | Useful convenience; keep business expiry explicit |
#[MaxExceptions] | Counts unhandled exceptions, not every manual release | Not a total-attempt limit |
backoff() / #[Backoff] | Exception retry delay; array indexed by attempt, final entry repeats | A finite array is not a finite retry count |
| Dispatch payload | Framework serializes backoff and retryUntil | Random array values are chosen once at dispatch |
release($delay) | Makes job available later; attempts still increase | Return immediately after release |
releaseUsingBackoff() | Uses the current attempt's configured backoff | Avoid duplicating schedule selection |
dontRetry / dontRetryWhen | Stops retries for selected exceptions | Centralize permanent-error classification where appropriate |
retry_after versus --timeout | Visibility interval versus worker execution limit | Timeout 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
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.
| Option | Mechanism | Constraint |
|---|---|---|
| TTL + DLX tiers | One queue per chosen interval | Coarse delays; default dead-lettering can lose messages |
| Legacy delayed-message exchange | x-delayed-message, x-delayed-type, x-delay | Project 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-time | Requires 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.
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
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
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.
| Approach | Benefit | Cost |
|---|---|---|
| Wait and block original partition | Keeps later records behind the failure | Head-of-line blocking and consumer liveness budget |
| Publish to retry topic | Main topic can continue | Same-key records can overtake the failed one |
| External persistent scheduler | Flexible due-time ordering | Additional storage and publication boundary |
| Transactional consume→produce | Can couple Kafka output and input offsets | Does 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.
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
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.
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
}
}
}
}-- 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 duelocal 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
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
triesis 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
| Situation | Recommendation | Why |
|---|---|---|
| Read-only call with short transient errors | Small local attempt cap + Full Jitter + deadline | Low scheduling overhead within request latency budget |
| Side-effecting API with unknown outcome | Stable idempotency key or reconciliation first | Retry may repeat an already committed action |
| Invalid schema / revoked access | Stop and classify terminally | Time cannot repair the input or permission |
| 429 with valid server hint | Honor not-before, add bounded upward jitter | Avoids disobeying the server's recovery policy |
| Minutes-long downstream outage | Durable delayed attempts and shared token budget | Frees workers without an uncontrolled recovery surge |
| Few standard RabbitMQ delays | TTL tiers with audited DLX safety | Predictable topology and visible backlog |
| Arbitrary RabbitMQ due time on quorum 4.4+ | Native delayed delivery | No legacy plugin timer store |
| Kafka order must survive failure | Block key/partition with explicit liveness plan | Retry-topic detours permit overtaking |
| Redis Streams due-time scheduling | ID-indexed ZSET + envelope HASH + bounded Lua | Explicit identity and atomic local movement |
| Days-long business process | Durable workflow timer | Needs 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×
| Stage | Change | Concrete reason |
|---|---|---|
| 1× | One owner, bounded local policy | Few invoice jobs; keep behavior understandable |
| 10× | Durable delay tiers, per-dependency retry tokens, backlog-age metrics | Outage no longer ties up every worker |
| 100× | Sharded scheduler ownership, tenant fairness, controlled recovery drain | One 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
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.
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 deadlineThis 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.
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 deduplicatesFor 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.
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 effectAlso 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.
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 requiredReplace 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
| Belief | Reality |
|---|---|
| A timeout means nothing happened | The server may have committed before the response was lost |
| Three retries always means three attempts | APIs disagree; define whether the first attempt is included |
| Exponential backoff prevents storms | Correlated workers still align; add jitter and a shared budget |
| A maximum delay is a retry limit | The operation can repeat at the cap forever without another limit |
| Every 4xx is permanent | 408, 429 and domain-specific conflicts need separate treatment |
Retry-After is always a number | HTTP dates are valid; parse deliberately |
| Delayed delivery means exact execution time | It means eligibility; backlog and capacity can make it late |
| Successful publish call permits ACK | Confirmed routing and acceptance are separate from local buffering |
| Same Kafka key preserves order across retry topics | Different topics have independent logs and processing paths |
| Redis Lua is a rollback transaction | Scripts run atomically but do not roll back prior writes on every error |
Laravel tries and retryUntil both cap execution | The time-based policy takes precedence; add a separate count guard if needed |
release() ends the PHP method | It schedules another attempt; return explicitly |
| New transport ID means a new business operation | Preserve logical identity across deliveries |
Cheat sheet
| Topic | Remember |
|---|---|
| Classifier | Allowlist transient failures; unknown is not automatically retryable |
| Safety | Timeout can mean success with a lost response; keep idempotency key |
| Counting | N total attempts means N-1 retries |
| Time | Overall deadline includes queue wait, backoff and execution |
| Full Jitter | U(0, min(cap, base*2^k)); saturate before multiplication |
| Equal Jitter | Keep half the envelope and randomize the other half |
| Decorrelated Jitter | Next envelope depends on previous randomized delay |
| Amplification | Multiply independent layer attempt counts |
| Fleet guard | Shared retry tokens plus concurrency controls |
| RabbitMQ | Confirm + mandatory route check before ACK; audit DLX safety separately |
| Kafka | Due header is application data; retry topics permit overtaking |
| Redis Streams | ZSET IDs + HASH envelopes + bounded same-slot Lua |
| Laravel | retryUntil wins over tries; releases count; final backoff entry repeats |
| Recovery | Bound backlog drain and inspect scheduled lateness |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Retry policy | Classification, limits, timing and terminal outcome for repeated work |
| Transient / permanent failure | A failure that may heal without changing intent / one needing a corrective change |
| Ambiguous outcome | Caller cannot tell whether the remote effect committed |
| Idempotency key / logical message ID | Stable identity of one business operation across deliveries |
| Attempt / retry | One execution / an additional execution after failure |
Attempt budget / MaxAttempts | Maximum total starts, including the first in this chapter |
| Deadline / time budget | Latest useful time for more work on the operation |
| Per-attempt timeout / cancellation | Bound on one call / request to stop cooperative execution |
| Backoff / base / cap | Waiting policy / initial envelope / maximum envelope |
| Constant / linear / exponential backoff | Fixed / arithmetically growing / multiplicatively growing delay |
| Jitter | Random timing variation that spreads correlated callers |
| Full Jitter | Uniform delay from zero through the current envelope |
| Equal Jitter | Half the envelope plus random delay over the remaining half |
| Decorrelated Jitter | Delay drawn using the previous randomized delay |
| Retry amplification / retry storm | Multiplication of physical work / synchronized or excessive retry load |
| Shared retry budget / token bucket | Fleet/client allowance for extra attempts / burst-and-refill implementation |
| Circuit breaker / half-open probe | Dependency admission state / limited recovery trial |
| Delayed delivery / not-before time | Eligibility after a due time, not exact-time execution |
| Message expiration / maximum age | Business or transport limit after which work is no longer useful |
Retry-After / IMF-fixdate | HTTP minimum-wait hint / canonical HTTP date format |
| Clock skew / lateness | Clock disagreement / actual start minus scheduled due time |
| Durable handoff | Transferring responsibility before settling current delivery |
| Publisher confirm / mandatory return | RabbitMQ acceptance signal / unroutable-publication signal |
| TTL / DLX / delay tier | Message lifetime / dead-letter exchange / queue or topic for a delay class |
x-message-ttl / expiration / x-expires | RabbitMQ queue-level message TTL / per-message TTL / unused-queue expiration |
x-delay / x-delayed-message | Legacy RabbitMQ plugin header / exchange type |
x-opt-delivery-time | RabbitMQ native quorum delivery timestamp, Unix milliseconds |
x-delayed-retry-min/max/type | RabbitMQ quorum native linear retry controls |
delivery-count / x-acquired-count | RabbitMQ failed-delivery count / consumer-assignment count |
| Head-of-line blocking / overtaking | Earlier work holds later work / later work completes first |
Retry topic / not-before-ms | Kafka retry path / application-owned due-time header |
| Offset commit / rebalance | Kafka recovery-position update / group ownership redistribution |
BlockRebalanceOnPoll / PauseFetchPartitions | franz-go processing ownership option / fetch suspension |
| Sorted set / ZSET / score | Redis ordered unique-member collection / its abbreviation / ordering number |
HASH envelope store / message_id | Payload storage indexed by logical ID / identity carried into stream entries |
ZRANGE ... BYSCORE / XADD | Redis due-range selection / stream append |
| Lua atomicity / rollback | No command interleaving / undo of prior writes, which scripts do not generally supply |
Hash tag / CROSSSLOT | Redis Cluster co-location marker / error for incompatible multi-key placement |
backoff / release / releaseUsingBackoff | Laravel exception delay / explicit rescheduling / configured-delay release |
retryUntil / RetryFor / Tries / MaxExceptions | Laravel deadline / relative window / attempt count / unhandled-exception count |
retry_after / --timeout | Laravel connection redelivery interval / worker execution limit |
dontRetry / dontRetryWhen | Laravel exception types or predicate that end retries |
retryFailedMessages / stopOnFailure | Laravel Kafka local retries / close-on-failure behavior |
at-least-once dead-letter strategy / reject-publish | RabbitMQ safer DLX transfer / reject new publications at overflow |
| Recovery drain / tenant fairness | Rate 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.
- Marc Brooker: Exponential Backoff and Jitter; AWS Builders' Library: Timeouts, retries, and backoff with jitter.
- Google SRE: Handling overload — retry budgets.
- RabbitMQ: TTL, quorum queues, dead lettering, publisher confirms and consumer acknowledgments.
- RabbitMQ: delayed-message plugin README.
- Kafka source: ProducerRecord, KafkaConsumer.
- Go clients: amqp091-go, franz-go kgo, go-redis; standard library: net/http.
- Redis: ZADD, ZRANGE, Lua scripting, Cluster specification, Streams.
- HTTP: RFC 9110, including Retry-After and safe/idempotent method semantics.
- Laravel 13: queues, HTTP client; framework source: Queue, Worker, RedisQueue.
- Laravel RabbitMQ: README, RabbitMQQueue implementation; php-amqplib: channel confirms API.
- Laravel Kafka: README, handling failed messages.