Dead-Letter Queue (DLQ)
“What will the messaging system do with a message it cannot deliver?” — Gregor Hohpe and Bobby Woolf, Dead Letter Channel
Summary: A DLQ preserves work that normal processing cannot currently complete, together with evidence and a recovery decision. Focus: Failure classification, durable transfer, broker differences, parking ownership, and controlled replay. Learning goal: Explain every crash window between failure, parking, acknowledgment, and replay, then implement a recoverable transfer.
This chapter owns the terminal failure path. Retry and delayed delivery owns schedules; acknowledgment owns settlement primitives; idempotent consumers owns business deduplication. A parking destination is useful only when somebody can recover what it contains.
Page map
| Looking for | Go to |
|---|---|
| Whether an error belongs in a DLQ | Classification |
| A guarantee that parking does not silently discard work | Transfer boundary |
| What to save alongside the body | Failure envelope |
RabbitMQ DLX and x-death details | Broker differences |
| Kafka offset and Redis PEL traps | Broker differences |
Laravel failed_jobs and queue:retry | Laravel |
| A replay plan for an incident | Solutions |
| Reproducible failure experiments | Lab |
Everything in one minute
| Question | Working answer | Failure if ignored |
|---|---|---|
| Is this a retry destination? | A retry destination has an automatic next attempt; a parking lot waits for a decision | A supposed DLQ becomes another infinite loop |
| Does parking mean success? | It means responsibility moved to a recovery workflow | Business work remains incomplete |
| Can I acknowledge first? | Only if losing the failed work is acceptable | Crash after acknowledgment loses the only copy |
| Is publish then acknowledge enough? | It prevents one loss window but permits duplicates | Crash after publish creates two parked copies |
| Is replay the original delivery? | Usually a new transport delivery with the same business identity | New IDs defeat deduplication |
| Does a nonempty DLQ always indicate bad input? | No: exhaustion, expiry, overflow, or dependency failures can also park work | Incident classification points to the wrong owner |
| Property | RabbitMQ | Kafka | Redis Streams | Laravel worker |
|---|---|---|---|---|
| Parking primitive | DLX routes to a queue | Application writes a DLT topic | Application writes a parking stream | Configured failed-job provider |
| Source progress | Reject without requeue | Commit next offset | XACK removes group pending entry | Worker records terminal failure |
| Failure history | Broker x-death | Application or framework headers | Application metadata and PEL counter | Payload, exception, connection, queue |
| Automatic terminal threshold | Quorum delivery-limit | Consumer policy | Recovery policy | Attempt/deadline policy |
| Durability trap | Default DLX transfer lacks internal confirms | Publish and commit are separate | MULTI does not roll back command errors | Storage may be disabled or unavailable |
| Replay ordering | Re-enters behind other work | New offset after newer records | New stream ID after newer entries | New reservation after newer jobs |
Where it comes from
Enterprise Integration Patterns calls the destination a Dead Letter Channel. Historically it concerns messages a messaging system cannot deliver; applications also use the name for failures a receiver cannot process. The latter overlaps the Invalid Message Channel idea: structurally invalid or semantically unsupported input is isolated for investigation.
The name describes a responsibility, not a portable protocol operation. RabbitMQ provides broker dead-letter routing. Kafka consumer applications normally build a dead-letter topic (DLT). Redis Streams exposes pending deliveries and claims, leaving parking to the application. Laravel records failed asynchronous jobs through a configured provider. An operator must inspect the actual mechanism before assigning a delivery guarantee to the word “DLQ”.
Why it exists
One corrupt invoice should not consume all workers forever. One failed inventory event should also not disappear merely because later orders need to proceed. A DLQ trades immediate progress for a separate recovery obligation.
| Keep retrying in the main path | Isolate into a parking lot |
|---|---|
| Preserves processing order if the partition stops | Allows later messages to progress |
| A transient dependency may recover automatically | Requires explicit repair or disposition |
| A poison message can monopolize capacity | Parking needs storage, retention, and ownership |
| Failure stays near the normal handler | Recovery may run against newer code and data |
Three misunderstandings to remove first: a DLQ does not repair a message; parking does not undo a partially completed business action; an acknowledgment is not proof that a parking destination durably accepted a copy.
What it is really about
A consumer moves responsibility from normal processing to exception handling. The invariant is: until the terminal record is durably accepted, the source must remain recoverable. After acceptance, duplicates are possible unless both sides share an atomic boundary. After replay, the business effect must still respect its original identity.
The failure branch ends at a decision, not at a trash can. “Resolved” may mean replayed successfully, superseded by a newer fact, deliberately discarded with a reason, or reconciled through another business action.
An everyday picture
At a parcel depot, an unreadable address goes to an exception desk. The clerk keeps the parcel, its tracking number, the failed address, and the reason. The desk can correct the address, ask the sender, or return the parcel. Moving it to that desk is not delivery to the customer. Putting it back on the conveyor without correcting the address just repeats the failure.
Concept catalogue
Failure classification Must-know
In plain words: Decide whether another attempt can help before deciding where to put the message.
Common misunderstanding: A poison message is any message that failed once. A network timeout says little about whether the payload is bad.
Definition: A poison message fails deterministically under the current consumer contract; a transient failure may succeed after conditions change. A terminal failure is the policy decision to stop automatic attempts, regardless of the original cause.
1 Producer -> worker: event E, schema version 9
2 Worker -> schema registry: version unsupported by this deployment
3 Worker -> parking: E + unsupported-version + consumer build
4 Operator -> deploy compatible consumer; replay selected EReal scenarios: An invalid currency code is permanent until corrected; a database outage is transient; a missing order may reflect replication lag; an ambiguous payment timeout requires reconciliation before another charge.
| Failure | Classification question | Action |
|---|---|---|
| Invalid JSON or unsupported version | Can this build decode the bytes? | Park raw bytes immediately |
| Dependency unavailable | Is the outage broad across healthy messages? | Pause or bounded retry; avoid flooding parking |
| Authentication denied | Did credentials or permissions change? | Stop the affected consumer and alert |
| Business rule rejected | Is rejection an expected business outcome? | Record the outcome; do not automatically label it poison |
| External request timed out | Could the side effect already have happened? | Reconcile with a stable idempotency key |
| Attempt budget exhausted | Is further automated work useful? | Park with the last cause and budget evidence |
How to use it: Store a stable reason code separately from an exception string. Go can classify with errors.Is; Laravel can call $this->fail($exception) for a known permanent failure. A SQL report groups reason codes without exposing payloads.
Parking lot and quarantine Must-know
In plain words: A parking lot holds work until someone decides what should happen next.
Common misunderstanding: A queue called retry and a queue called dead differ because of their names. Their consumers and routing rules determine their behavior.
Definition: Parking is an operational state with no unconditional automatic return to the normal path. Quarantine is a restricted parking area for suspect or unsafe content. A retry destination schedules another automatic attempt.
1 Worker -> retries: dependency timeout, automatic retry remains permitted
2 Retry policy -> parking: automatic budget exhausted
3 Operator -> inspect: classify, assign owner, preserve original bytes
4 Repair tool -> replay: selected batch after a verified fixReal scenarios: A consumer bug affects one release; an import contains malformed rows; a tenant is temporarily suspended. These need different owners and replay conditions even if all are parked.
| Mechanism | What prevents an accidental loop |
|---|---|
| RabbitMQ parking queue | No TTL/DLX route automatically returns it to work |
| Kafka DLT | Recovery group is separate from the normal input group |
| Redis parking stream | Reaper reads the work stream, not its own parking output |
| Laravel failed-job provider | queue:retry runs deliberately after diagnosis |
How to use it: Name parking by consumer responsibility, such as orders.billing.DLT, rather than by producer alone. Two subscribers may disagree about whether the same event is processable.
The transfer boundary Must-know
In plain words: Keep the source recoverable until its parked replacement is accepted.
Common misunderstanding: Two individually reliable operations make a reliable move. Their order and the crash between them determine the result.
Definition: A transfer is loss-resistant when source completion cannot happen before a durable destination write; it is duplicate-resistant only with a shared atomic boundary or deduplication.
1 Worker -> DLQ: write failure record
2 DLQ -> worker: accepted
3 Worker crashes before source acknowledgment
4 Source -> replacement worker: delivers again
5 Replacement -> DLQ: another copy; stable source identity exposes duplicationReal scenarios: Kafka DLT publish succeeds but offset commit times out; RabbitMQ target confirmation is lost; Redis client loses the script response. Recovery must distinguish “unknown” from “not done”.
| Transfer | Safe direction | Remaining boundary |
|---|---|---|
| RabbitMQ quorum at-least-once DLX | Internal confirm before removing source responsibility | Target duplicates; broker/storage failure assumptions |
| Kafka manual consumer | Confirm DLT publish before commit | Crash creates duplicate DLT records |
| Kafka transaction | DLT write and consumed offsets commit together | Applies within Kafka, not external database/HTTP effects |
| Redis Lua parking | Validate ownership, XADD, then XACK | Persistence/failover durability; scripts have no rollback |
| Laravel failure storage | Configured provider records failure | Driver and framework failure paths require monitoring |
How to use it: The Go Kafka test deliberately fails publication and verifies that commit never runs. The Redis script stops on an XADD error before acknowledgment. Do not “fix” an unavailable DLQ by acknowledging the source anyway.
Failure envelope and forensic evidence Important
In plain words: Keep enough context to reproduce the failure without guessing which message it was.
Common misunderstanding: The exception text alone is sufficient. It may omit the source position, consumer version, or body that failed to deserialize.
Definition: A failure envelope is application metadata around the original message or a protected reference to it. Transport identity identifies a delivery; business identity identifies the operation whose effect must not repeat.
1 Decoder -> error: cannot parse body
2 Envelope writer -> preserve: raw bytes + content type + source coordinates
3 Envelope writer -> annotate: stable reason + consumer version + failure time
4 Investigator -> reproduce against the original contract, not a reconstructed object| Field | Purpose | Caution |
|---|---|---|
event_id | Business deduplication identity | Keep it across replay |
| Original queue/topic/stream | Destination lineage | Store a routing allowlist, not arbitrary operator input |
| Group, partition, offset or stream ID | Identifies the failing consumer delivery | Kafka coordinates need the group to identify responsibility |
| Raw body or encrypted payload reference | Recover malformed content | Apply size and retention limits |
| Reason code and exception class | Stable classification | Stack traces and exception messages can contain secrets |
| Attempt/delivery count | Shows the chosen stopping threshold | Delivery is not necessarily one handler execution |
| First/last failure time | Measures unresolved age | Producer timestamp is not parking time |
| Consumer build and schema version | Explains compatibility | A replay may run different code |
| Replay batch and operator identity | Audit of recovery decisions | Do not replace the original event identity |
How to use it: Store trusted metadata outside the original payload namespace. The Redis example prefixes original fields with payload. so input cannot overwrite reason. The Kafka example preserves bytes and key plus an explicit safe allowlist (event_id, schema_version, content-type), while rebuilding failure headers. Adapt that allowlist to the actual contract; never silently remove an identity or schema header needed for replay.
Replay, redrive, and ordering Must-know
In plain words: Replay is another delivery attempt, after a repair, with the original business identity.
Common misunderstanding: Putting a failed record back restores its place in history. A newly published message normally follows messages already processed.
Definition: Redrive is the operational transfer from a failure destination back to a processing path. Replay may re-execute side effects, so it needs eligibility checks, idempotency, rate limits, and audit.
1 Orders partition: E1 changes address; E2 ships order
2 E1 fails and is parked; consumer processes E2
3 Operator fixes decoder and republishes E1
4 Handler must detect stale version; transport order cannot undo shipmentReal scenarios: Replaying payments must not double charge; replaying an expired reservation may be invalid; replaying a notification may be safe but confusing; rebuilding a projection may use a separate repair path.
| Requirement | Recovery strategy | Cost |
|---|---|---|
| Strict dependent sequence | Stop partition/key until repaired | Later work waits |
| Independent messages | Park and continue | Need separate recovery ownership |
| Latest-state projection | Apply only increasing entity versions | Requires trustworthy versions |
| Irreversible external effect | Reconcile before replay | More operational work |
| Large incident | Canary, then bounded batches | Slower drain protects normal traffic |
How to use it: Preserve event_id; add replay_batch_id separately. A successful publish marks a record “replay dispatched”, not “business resolved”. Resolve it only after observing the expected effect or reconciliation result.
Retention, ownership, and capacity Important
In plain words: Unresolved messages consume both storage and human attention.
Common misunderstanding: A DLQ is safe because it is durable. Expiration, truncation, permission changes, and unattended backlog can still destroy recoverability.
Definition: A recovery service level sets who responds, how quickly, what retention is needed, and what happens before retained evidence expires.
Real scenarios: A weekend schema incident is discovered after a one-day retention window; replay saturates a payment API; a cross-team DLQ has no assigned owner; a failure storm fills the source quorum queue because the destination is down.
| Measure | Interpretation | Response |
|---|---|---|
| New parked messages per minute | New failures, independent of drain rate | Compare by deployment and reason |
| Oldest unresolved failure | Recovery is falling behind | Escalate before retention expires |
| Parking write failures | Primary work cannot be safely transferred | Stop advancement; restore destination |
| Replay failure fraction | Fix or selection may be wrong | Stop the batch |
| Bytes retained | Capacity requirement | Size for incident horizon plus overhead |
| Unowned records | Process failure | Assign a team and runbook |
How to use it: Capacity planning starts with failure_rate × mean_payload_bytes × retention_seconds, plus replication and index overhead. At 10 failed messages/s, 4 KiB each, and seven days, bodies alone are about 24.8 GB decimal. This is an estimate, not a benchmark.
Mechanics and exact controls
RabbitMQ history is not a universal attempt counter Important
x-death records dead-letter events, compressed by queue and reason, most recent first. Its count is the number of dead-letterings for that pair. A requeue alone does not create a dead-letter event. x-delivery-count on quorum deliveries is a different counter; in RabbitMQ 4.3+ basic.nack(requeue=true) does not count as a failed delivery toward the limit, while basic.reject does. Do not infer handler attempts from either without understanding the path.
| Control or field | Meaning |
|---|---|
dead-letter-exchange | Policy destination exchange; normal exchange routing still applies |
dead-letter-routing-key | Optional replacement routing key |
x-dead-letter-exchange | Queue declaration argument; overrides the matching policy value |
dead-letter-strategy=at-least-once | Source quorum queue keeps responsibility until internal confirms |
overflow=reject-publish | Required for quorum at-least-once DLX; drop-head disables that guarantee |
delivery-limit | Quorum poison-delivery backstop; default 20 since RabbitMQ 4.0 |
x-death.reason | rejected, expired, maxlen, or delivery_limit |
x-death.count | Count for one queue/reason pair, not total business attempts |
x-first-death-* / x-last-death-* | First/most recent queue, exchange, reason |
original-expiration | Preserved AMQP 0-9-1 expiration; original TTL is removed on dead-lettering |
A whole queue expiring does not dead-letter its messages. An automatic cycle with no rejection can be detected and dropped. At-most-once DLX can lose messages when its exchange or target is unavailable; quorum at-least-once transfer retains and retries, consuming source capacity. Changing that strategy back to at-most-once can delete unconfirmed dead letters. Target durability still matters.
Kafka coordinates and Redis ownership Important
For Kafka, committing offset k+1 means resuming after record k; it also passes every earlier offset in that partition. “Skip committing the bad record” fails if a later commit overtakes it. The example processes one record at a time and stops on transfer uncertainty. A production worker must keep processing bounded relative to group liveness; consumer scaling covers rebalances.
For Redis, XPENDING describes a consumer group's pending entries list (PEL), including owner, idle time, and delivery count. XCLAIM or cursor-based XAUTOCLAIM transfers idle ownership; JUSTID avoids incrementing the delivery count. A claim is not a fence against a slow old worker. The parking script rechecks current ownership, and business writes still need idempotency or fencing.
XAUTOCLAIM returns a next cursor: continue even if a scan returns no messages, until 0-0. Redis 7+ also reports deleted source entries it removes from the PEL. That is loss detection, not recovery of their bodies. Avoid trimming a source before pending work and all relevant groups are safe; see Redis Streams.
| Failure signal | Meaning | Response |
|---|---|---|
AMQP 406 PRECONDITION_FAILED | Existing queue arguments conflict with declaration | Fix topology deployment; do not hot-delete a live queue |
| RabbitMQ DLX forward failure log | Destination cannot accept transfer | Check exchange, bindings, target quorum, limits |
| Kafka DLT produce error | Destination write not known successful | Do not commit; stop or pause |
| Kafka commit error | Source progress is uncertain | Stop; allow duplicate-safe recovery |
Redis NOGROUP | Consumer group missing | Restore expected topology; do not acknowledge elsewhere |
Redis WRONGTYPE | Destination/source is not a stream | Fix key collision; failed XADD must leave source pending |
Redis CROSSSLOT | Script keys do not share a cluster slot | Use a common hash tag or another transfer protocol |
NOT_OWNER / SOURCE_PAYLOAD_MISSING | Application script detected stale ownership or absent body | Reinspect pending state; escalate absent evidence |
Solving classic problems
Build a recovery register
A broker parking destination holds the bytes; an operational register tracks who owns the decision. PostgreSQL below illustrates an application-owned register, not Laravel's failed_jobs schema. A unique source identity makes repeated parking discoveries refer to the same case.
CREATE TABLE failure_case (
case_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
consumer_name text NOT NULL,
source_identity text NOT NULL,
event_id text,
reason_code text NOT NULL,
payload_ref text NOT NULL,
first_failed_at timestamptz NOT NULL DEFAULT now(),
owner_team text NOT NULL,
state text NOT NULL DEFAULT 'parked'
CHECK (state IN ('parked', 'approved', 'dispatched', 'resolved', 'discarded')),
replay_batch_id text,
UNIQUE (consumer_name, source_identity)
);
SELECT owner_team, reason_code, count(*), min(first_failed_at) AS oldest
FROM failure_case
WHERE state IN ('parked', 'approved', 'dispatched')
GROUP BY owner_team, reason_code;Do not write this row, acknowledge the broker, and assume the payload reference has become durable by association. Persist the protected payload first or use an outbox transaction for the database-to-broker recovery path. Database transactions cannot atomically acknowledge every broker.
Repair and replay without a second incident
| Problem | Solution | Benefit | Limitation |
|---|---|---|---|
| DLQ destination unavailable | Keep source recoverable and stop advancing | Avoids silent loss | Normal work may slow or stop |
| All records fail after deploy | Roll back/pause, classify a sample | Stops a failure storm | Requires deployment evidence |
| Mixed reasons in one DLQ | Filter by reason, version, tenant, age | Replays only eligible records | Metadata must be trustworthy |
| Duplicate parked copies | Deduplicate by source and consumer; effect by event ID | Stable incident accounting | Source ID alone is not a business key |
| Payload needs correction | Preserve original; create audited corrected version | Maintains evidence | Decide whether it is the same business operation |
| DLQ is near retention expiry | Export protected evidence or extend retention | Buys investigation time | Privacy and storage obligations remain |
| Ordered dependent workflow | Block key/partition or reconcile state | Prevents invalid later actions | Reduced throughput |
| Replay overload | Separate quota, canary, pause threshold | Protects live traffic | Longer recovery duration |
A concrete runbook is: identify the owning consumer; preserve original evidence; fix or reconcile the cause; choose eligible records; dry-run validation; replay a small canary; observe effects and new failures; increase bounded batch size; mark resolved only from evidence. Record rejected replay candidates too.
Choosing a failure path
| Situation | Choose | Why |
|---|---|---|
| Malformed immutable bytes | Immediate quarantine | Time alone cannot repair decoding |
| Short dependency outage | Bounded retry or pause | Parking everything shifts an outage into manual work |
| Expected business rejection | Normal rejected outcome | A valid refusal is not necessarily infrastructure failure |
| Exhausted automatic budget | Parking with ownership | Preserves work while stopping resource waste |
| Strictly ordered dependent records | Stop affected sequence | Skipping creates invalid downstream state |
| Independent analytics events | Park and continue | One bad event need not block the partition forever |
| Irreversible payment uncertainty | Reconcile before replay | Retrying may duplicate a completed charge |
| Intentionally disposable telemetry | Explicit discard policy | A recovery queue may cost more than the data is worth |
Go
Before
Every failure is requeued. For malformed input, this creates repeated delivery without progress. It is intentionally bad design, not recommended recovery behavior.
// Package main is the poison loop: every failure goes straight back to the head
// of the queue, so one bad message is redelivered forever and starves the rest.
package main
import (
"errors"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
)
func process(body []byte) error {
if len(body) == 0 {
return errors.New("empty payload") // will never succeed, however often it is retried
}
return nil
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("AMQP_URL is not set")
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if _, err := ch.QueueDeclare("orders", true, false, false, false, nil); err != nil {
log.Fatal(err)
}
deliveries, err := ch.Consume("orders", "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := process(d.Body); err != nil {
log.Printf("failed, requeueing: %v", err)
_ = d.Nack(false, true) // requeue=true: no limit, no record, no way out
continue
}
_ = d.Ack(false)
}
}After
Known permanent failures are rejected without requeue. Settlement errors propagate; the worker exits rather than treating uncertain acknowledgment as success. The quorum queue's broker limit remains a backstop, not a substitute for classifying errors.
package main
import (
"errors"
"log"
"os"
amqp "github.com/rabbitmq/amqp091-go"
)
var errPermanent = errors.New("permanent failure")
func process(body []byte) error {
if len(body) == 0 {
return errPermanent
}
return nil
}
// deliveryCount reads the quorum-queue x-delivery-count header, which is only
// present on redelivered messages.
func deliveryCount(d amqp.Delivery) int64 {
switch v := d.Headers["x-delivery-count"].(type) {
case int64:
return v
case int32:
return int64(v)
}
return 0
}
// handle rejects with requeue until the budget is spent, then rejects without
// requeue so the broker dead-letters the message. basic.reject (not nack) is
// used because RabbitMQ 4.3+ counts only reject towards the delivery limit.
func handle(d amqp.Delivery) error {
err := process(d.Body)
switch {
case err == nil:
return d.Ack(false)
case errors.Is(err, errPermanent) || deliveryCount(d)+1 >= maxAttempts:
log.Printf("parking message: %v", err)
return d.Reject(false) // requeue=false: routed to orders.dlx
default:
return d.Reject(true) // counts as one failed delivery
}
}
// describeDeath summarises the x-death history of a parked message: the queue
// it died in, why, and how many times.
func describeDeath(d amqp.Delivery) (queue, reason string, count int64) {
deaths, _ := d.Headers["x-death"].([]interface{})
if len(deaths) == 0 {
return "", "", 0
}
latest, _ := deaths[0].(amqp.Table) // ordered by recency
queue, _ = latest["queue"].(string)
reason, _ = latest["reason"].(string)
count, _ = latest["count"].(int64)
return queue, reason, count
}
// inspectParked peeks at one parked message and puts it back; the parking lot
// keeps it until a human decides.
func inspectParked(ch *amqp.Channel) error {
d, ok, err := ch.Get(parkedQueue, false)
if err != nil || !ok {
return err
}
queue, reason, count := describeDeath(d)
log.Printf("parked: from=%s reason=%s count=%d", queue, reason, count)
return d.Nack(false, true)
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
log.Fatal("AMQP_URL is not set")
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if err := declareTopology(ch); err != nil {
log.Fatal(err)
}
deliveries, err := ch.Consume(workQueue, "", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
if err := handle(d); err != nil {
log.Fatal(err)
}
}
}The Go angle
Keep classification, destination write, and source settlement separately testable. Do not bury CommitRecords or Ack failures inside callbacks that continue to later records. The snippets compile without connecting to a broker; the “valid payload” branch is a teaching placeholder for an idempotent business handler. Connection credentials, bounded shutdown, and deployment topology belong in the host application.
Laravel
Before
An unlimited attempt policy combined with manual release can keep broken input circulating without a useful terminal record.
<?php
namespace App\Jobs;
use App\Services\OrderImporter;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Throwable;
class ImportOrder implements ShouldQueue
{
use InteractsWithQueue, Queueable;
// 0 means "retry forever": the worker never moves this job to failed_jobs.
public int $tries = 0;
public function __construct(public array $payload) {}
public function handle(OrderImporter $importer): void
{
try {
$importer->import($this->payload);
} catch (Throwable $e) {
// Swallow everything and put the job back. A malformed payload will
// loop here for ever, and nobody is told.
$this->release(5);
}
}
}After
#[Tries(5)] bounds automatic attempts. A known permanent exception calls fail() and immediately returns; other exceptions reach the worker. failed() logs a stable identity and exception class, avoiding raw payloads.
<?php
namespace App\Jobs;
use App\Exceptions\MalformedOrder;
use App\Services\OrderImporter;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Log;
use Throwable;
// After 5 attempts the worker writes the job to failed_jobs (the parking lot).
#[Tries(5)]
class ImportOrder implements ShouldQueue
{
use Queueable;
public function __construct(public array $payload) {}
public function handle(OrderImporter $importer): void
{
try {
$importer->import($this->payload);
} catch (MalformedOrder $e) {
// Retrying cannot help: fail now instead of burning the remaining attempts.
$this->fail($e);
return;
}
// Any other exception propagates, so the worker counts the attempt.
}
// A failure callback is not an exactly-once side-effect boundary.
// $exception may be MaxAttemptsExceededException
// when the attempts ran out without a thrown exception.
public function failed(?Throwable $exception): void
{
Log::error('order import parked', [
'order_id' => $this->payload['id'] ?? null,
'exception' => $exception ? $exception::class : null,
]);
}
}
// Operations, from the shell:
// php artisan queue:failed list parked jobs (id, queue, failed_at)
// php artisan queue:retry <uuid> replay one job after fixing the cause
// php artisan queue:retry --queue=orders replay everything from one queue
// php artisan queue:forget <uuid> drop one that should never be replayed
// php artisan queue:prune-failed --hours=720 age parked jobs outThe Laravel angle
Laravel 13 documents “database, Amazon SQS, Redis, and Beanstalkd drivers” along with synchronous and null drivers. RabbitMQ and Kafka need packages. Laravel's Redis queue driver is not Redis Streams. A failed asynchronous job can be stored by the configured failed-job provider; the default database workflow uses failed_jobs, while DynamoDB is another documented provider and queue.failed.driver=null disables storage.
failed_jobs is an application recovery record, not proof that every broker failure reached a durable DLQ. Synchronous exceptions are not stored there. A new job instance is used for failed(), so mutations made inside handle() are not reliable diagnostic state. An attempt can be spent by release, middleware, or timeout without completing the handler.
| Operation | Purpose | Operational caution |
|---|---|---|
make:queue-failed-table, migrate | Create missing failed-job storage | Check the configured provider first |
queue:failed | List failed jobs | Restrict payload inspection access |
queue:retry UUID | Republish one failed job | Fix cause and preserve business identity |
queue:retry --queue=orders | Retry selected queue's jobs | Selection may contain different causes |
queue:retry all | Retry all recorded failures | Usually too broad during an incident |
queue:forget UUID | Delete one failure record | Deletion is a disposition decision |
queue:flush | Delete failed-job records | Does not mean business recovery succeeded |
queue:prune-failed --hours=720 | Retain the last 30 days | Default prune horizon is 24 hours |
Queue::failing() | Observe JobFailed globally | Monitoring hooks can also fail |
horizon:forget | Delete failures managed through Horizon | Use the Horizon command for its records |
See Laravel queue internals for worker lifecycle, and retry for retryUntil, backoff, and release schedules. Neither a failure callback nor queue:retry makes external side effects exactly once.
Broker differences
RabbitMQ
A dead letter exchange (DLX) is a normal exchange. A DLQ exists only when an appropriate queue is bound to it. Dead-lettering occurs on rejection without requeue, message TTL expiration, queue-length eviction, or quorum delivery-limit exhaustion. At-least-once transfer requires a source quorum queue, dead-letter-strategy=at-least-once, overflow=reject-publish, a DLX, and the required stream_queue feature flag. Verify enabled flags when upgrading older clusters.
Use a policy for changeable controls; hardcoded queue arguments override matching policy values. The Go example declares explicit arguments to make a standalone lab self-contained. The source and parking queues are durable quorum queues; publishers should use persistent messages when target restart survival matters. If the target is unavailable, retained dead letters can fill the source and reject new publishes.
// Package main declares a work queue whose dead-lettered messages land in a
// parking queue. In production prefer a policy over hardcoded arguments, so the
// DLX can change without redeploying applications.
package main
import (
amqp "github.com/rabbitmq/amqp091-go"
)
const (
workQueue = "orders"
dlxName = "orders.dlx"
parkedQueue = "orders.parked"
parkedKey = "orders.parked"
maxAttempts = 5
)
func declareTopology(ch *amqp.Channel) error {
if err := ch.ExchangeDeclare(dlxName, "direct", true, false, false, false, nil); err != nil {
return err
}
// The parking lot: a durable quorum queue nobody consumes automatically.
if _, err := ch.QueueDeclare(parkedQueue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
}); err != nil {
return err
}
if err := ch.QueueBind(parkedQueue, parkedKey, dlxName, false, nil); err != nil {
return err
}
// The work queue. The delivery limit is the broker-side backstop: a message
// returned more often than this is dead-lettered with reason delivery_limit.
_, err := ch.QueueDeclare(workQueue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
"x-dead-letter-exchange": dlxName,
"x-dead-letter-routing-key": parkedKey,
"x-delivery-limit": int64(maxAttempts),
"x-dead-letter-strategy": "at-least-once",
"x-overflow": "reject-publish",
})
return err
}For Laravel, vladimir-yuldashev/laravel-queue-rabbitmq supplies the driver. Its reroute_failed, failed_exchange, and failed_routing_key options configure broker routing for failed jobs. Declare and bind the destination separately. Apply the quorum safety policy to the source; enabling package rerouting alone does not select at-least-once DLX.
<?php
// config/queue.php (fragment) for vladimir-yuldashev/laravel-queue-rabbitmq.
// With reroute_failed the package declares the queue with x-dead-letter-exchange
// and x-dead-letter-routing-key, and rejects (requeue = false) a job it marks failed.
// Bind a parking queue to failed-exchange yourself; the package does not.
return [
'connections' => [
'rabbitmq' => [
'driver' => 'rabbitmq',
'hosts' => [[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_USER', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),
'vhost' => env('RABBITMQ_VHOST', '/'),
]],
'options' => [
'queue' => [
'quorum' => true,
'reroute_failed' => true,
'failed_exchange' => 'orders.dlx',
'failed_routing_key' => 'orders.parked',
],
],
],
],
];# Example policy for an existing source quorum queue; expected, not run.
rabbitmqctl set_policy orders-dlq '^orders$' \
'{"dead-letter-exchange":"orders.dlx","dead-letter-routing-key":"orders.parked","dead-letter-strategy":"at-least-once","overflow":"reject-publish","delivery-limit":5}' \
--apply-to quorum_queues --priority 10Do not replay both a Laravel failed-job record and its RabbitMQ parked copy independently. Choose one recovery authority, correlate the other copy, and mark the same business recovery decision in both operational views.
Kafka
A normal Kafka consumer has no per-record reject-to-DLQ operation. It publishes a dead-letter topic record and advances its group position. Retry topics are an application convention, and their delay schedules live in retry and delayed delivery. The Go example retains raw bytes, key, original coordinates, and consumer group; a DLT publish failure or commit error stops the worker. BlockRebalanceOnPoll protects the short poll/process/commit window; it requires AllowRebalance and bounded work. One 10-second per-record context covers publication plus commit, below the configured 30-second rebalance timeout. Cancellation is cooperative: an application handler must honor its own timeouts; context cancellation cannot forcibly stop arbitrary blocking code. A timeout is an unknown outcome, so the worker stops and recovery remains duplicate-safe.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
const group = "orders-billing"
func safeHeaders(headers []kgo.RecordHeader) []kgo.RecordHeader {
var safe []kgo.RecordHeader
for _, h := range headers {
switch h.Key {
case "event_id", "schema_version", "content-type":
safe = append(safe, kgo.RecordHeader{Key: h.Key, Value: append([]byte(nil), h.Value...)})
}
}
return safe
}
func toDLT(r *kgo.Record, reason string) *kgo.Record {
// Keep raw bytes: even a deserialization failure must be recoverable.
// Do not blindly propagate headers containing credentials or prior DLT metadata.
return &kgo.Record{Topic: "orders.billing.DLT", Key: r.Key, Value: r.Value,
Headers: append(safeHeaders(r.Headers), []kgo.RecordHeader{
{Key: "dlt.original-topic", Value: []byte(r.Topic)},
{Key: "dlt.original-partition", Value: []byte(strconv.Itoa(int(r.Partition)))},
{Key: "dlt.original-offset", Value: []byte(strconv.FormatInt(r.Offset, 10))},
{Key: "dlt.consumer-group", Value: []byte(group)},
{Key: "dlt.reason", Value: []byte(reason)},
{Key: "dlt.failed-at", Value: []byte(time.Now().UTC().Format(time.RFC3339))},
}...),
}
}
// settle deliberately permits duplicates after a crash between publish and
// commit. A failed publish must NEVER advance the consumed offset.
func settle(ctx context.Context, r *kgo.Record,
publish func(context.Context, *kgo.Record) error,
commit func(context.Context, *kgo.Record) error) error {
if err := publish(ctx, toDLT(r, "empty-payload")); err != nil {
return err
}
return commit(ctx, r)
}
func run(ctx context.Context, brokers string) error {
cl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.ConsumerGroup(group), kgo.ConsumeTopics("orders"),
kgo.DisableAutoCommit(), kgo.BlockRebalanceOnPoll(), kgo.RebalanceTimeout(30*time.Second))
if err != nil {
return err
}
defer cl.Close()
for ctx.Err() == nil {
fetches := cl.PollRecords(ctx, 1)
if errs := fetches.Errors(); len(errs) > 0 {
cl.AllowRebalance()
return fmt.Errorf("fetch: %w", errs[0].Err)
}
for _, r := range fetches.Records() {
// One budget covers both publish and commit, below rebalance timeout.
recordCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
if len(r.Value) == 0 {
err = settle(recordCtx, r,
func(ctx context.Context, out *kgo.Record) error { return cl.ProduceSync(ctx, out).FirstErr() },
func(ctx context.Context, in *kgo.Record) error { return cl.CommitRecords(ctx, in) })
} else {
// Replace with an idempotent business handler BEFORE committing.
err = cl.CommitRecords(recordCtx, r)
}
cancel()
if err != nil {
cl.AllowRebalance()
return err
}
}
cl.AllowRebalance()
}
return ctx.Err()
}
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
log.Print("set KAFKA_BROKERS to run")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, brokers); err != nil && !errors.Is(err, context.Canceled) {
log.Fatal(err)
}
}The separate publish and commit permit duplicate parked copies after a crash. A Kafka transaction can combine DLT output and consumed offsets when every relevant effect stays in Kafka; see delivery guarantees. Preserving the key does not promise the same partition number if topic partition counts differ, and parking does not preserve business execution order.
The mateusjunges/laravel-kafka v2.13 documentation provides withDlq(), retryFailedMessages(), and stopOnFailure(). Without DLQ or stop-on-failure, failed records may be skipped. However, the package Consumer source snapshot at commit 7e05df68b484 reviewed on 2026-11-26 calls raw producev, ignores the return from flush(12000), then calls commitDlq; it does not verify each message's delivery report there. Manual commit mode alone does not repair that exception path. Do not treat that helper as a durable-transfer guarantee without auditing the installed version.
The Laravel-compatible adapter below deliberately uses the underlying php-rdkafka client directly. It disables automatic commit and offset storage, retains raw bytes and safe contract headers, checks both flush completion and the per-message delivery report, and only then commits. A timeout or any error escapes and stops the loop. The business handler must be bounded and idempotent. run() receives the configured broker list and an application-owned callable; the Laravel command using it must let exceptions terminate the worker so later commits cannot overtake the failure.
<?php
namespace App\Messaging;
use JsonException;
use RdKafka\Conf;
use RdKafka\KafkaConsumer;
use RdKafka\Message;
use RdKafka\Producer;
use RuntimeException;
use UnexpectedValueException;
// Laravel service using ext-rdkafka directly. Call run() from a console command;
// let exceptions exit the command. Do not catch-and-continue outside this loop.
final class KafkaDlq
{
public function run(string $brokers, callable $importOnce): void
{
$consumerConfig = new Conf;
$consumerConfig->set('metadata.broker.list', $brokers);
$consumerConfig->set('group.id', 'orders-billing');
$consumerConfig->set('enable.auto.commit', 'false');
$consumerConfig->set('enable.auto.offset.store', 'false');
$consumer = new KafkaConsumer($consumerConfig);
$consumer->subscribe(['orders']);
$reported = false;
$deliveryError = null;
$producerConfig = new Conf;
$producerConfig->set('metadata.broker.list', $brokers);
$producerConfig->set('enable.idempotence', 'true');
$producerConfig->set('delivery.timeout.ms', '5000');
$producerConfig->set('request.timeout.ms', '3000');
$producerConfig->setDrMsgCb(function ($producer, Message $report) use (&$reported, &$deliveryError): void {
// Exactly one record is outstanding, so this report belongs to it.
$reported = true;
if ($report->err !== RD_KAFKA_RESP_ERR_NO_ERROR) {
$deliveryError = $report->errstr();
}
});
$producer = new Producer($producerConfig);
$parking = $producer->newTopic('orders.billing.DLT');
try {
while (true) {
$message = $consumer->consume(1000);
if (in_array($message->err, [RD_KAFKA_RESP_ERR__TIMED_OUT, RD_KAFKA_RESP_ERR__PARTITION_EOF], true)) {
continue;
}
if ($message->err !== RD_KAFKA_RESP_ERR_NO_ERROR) {
throw new RuntimeException($message->errstr());
}
$reason = null;
try {
$body = json_decode($message->payload, true, flags: JSON_THROW_ON_ERROR);
if (!is_array($body) || !isset($body['event_id'])) {
throw new UnexpectedValueException('missing-event-id');
}
} catch (JsonException|UnexpectedValueException $exception) {
$reason = 'invalid-contract';
}
if ($reason === null) {
// Application-owned, bounded, idempotent business operation.
// Its exceptions stop the worker; they are not all poison input.
$importOnce($body);
} else {
$reported = false;
$deliveryError = null;
$headers = array_intersect_key($message->headers ?? [], array_flip([
'event_id', 'schema_version', 'content-type',
]));
$headers += [
'dlt.original-topic' => $message->topic_name,
'dlt.original-partition' => (string) $message->partition,
'dlt.original-offset' => (string) $message->offset,
'dlt.consumer-group' => 'orders-billing',
'dlt.reason' => $reason,
'dlt.failed-at' => gmdate(DATE_ATOM),
];
$parking->producev(RD_KAFKA_PARTITION_UA, 0, $message->payload, $message->key, $headers);
$flushResult = $producer->flush(6000);
if ($flushResult !== RD_KAFKA_RESP_ERR_NO_ERROR || !$reported || $deliveryError !== null) {
throw new RuntimeException('Parking not confirmed: '.($deliveryError ?? 'missing report or flush timeout'));
}
}
// A commit exception stops the loop. Unknown outcomes may duplicate
// parking on restart, so recovery uses group + original coordinates.
$consumer->commit($message);
}
} finally {
$consumer->close();
}
}
}Kafka Connect sink error handling is a separate subsystem: errors.tolerance=none is fail-fast; all permits supported processing errors to be skipped, errors.deadletterqueue.topic.name selects the DLT, and errors.deadletterqueue.context.headers.enable=true adds context. This is not a promise that any connector error, such as a lost external database, is quarantined. Connector-specific retry and reporting still matter.
Redis Streams
A pending delivery is not a DLQ. XPENDING, XCLAIM, and XAUTOCLAIM let a recovery worker find or take idle entries. The Go sweep follows the full cursor and uses a cryptographically random consumer name for each process incarnation, so an old reaper cannot pass the ownership check after a new one claims the entry. It parks at a chosen delivery/claim threshold: XAUTOCLAIM increments that counter even when the sweeper never executes business code. This is a recovery-assignment budget, not a count of actual handler retries; persist a separate attempt counter when policy needs that meaning. Entries below the threshold remain pending for the application's retry worker; the sweep is not a scheduler and does not invent successful processing.
package main
import (
"context"
"crypto/rand"
_ "embed"
"encoding/hex"
"fmt"
"log"
"os"
"time"
"github.com/redis/go-redis/v9"
)
const (
stream = "{orders}:work"
group = "billing"
parking = "{orders}:billing:parked"
)
//go:embed park.lua
var parkingLua string
var parkingScript = redis.NewScript(parkingLua)
func park(ctx context.Context, rdb *redis.Client, id, consumer, reason string) error {
_, err := parkingScript.Run(ctx, rdb, []string{stream, parking}, group,
consumer, id, reason, time.Now().UTC().Format(time.RFC3339)).Result()
return err
}
// sweep parks entries after five delivery/claim assignments, NOT five handler executions. Entries below the threshold remain
// pending for the application's recovery worker; this is NOT a retry scheduler.
func sweep(ctx context.Context, rdb *redis.Client, consumer string) error {
cursor := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream, Group: group, Consumer: consumer,
MinIdle: time.Minute, Start: cursor, Count: 50,
}).Result()
if err != nil {
return err
}
for _, m := range msgs {
pending, err := rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
Stream: stream, Group: group, Start: m.ID, End: m.ID, Count: 1,
}).Result()
if err != nil {
return err
}
if len(pending) == 0 || pending[0].Consumer != consumer {
continue
}
if pending[0].RetryCount >= 5 {
if err := park(ctx, rdb, m.ID, consumer, "delivery-budget-exhausted"); err != nil {
return fmt.Errorf("park %s: %w", m.ID, err)
}
}
}
cursor = next
if cursor == "0-0" {
return nil
}
}
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
log.Print("set REDIS_ADDR to run the recovery sweep")
return
}
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var incarnation [16]byte
if _, err := rand.Read(incarnation[:]); err != nil {
log.Fatal(err)
}
consumer := "reaper-" + hex.EncodeToString(incarnation[:])
if err := sweep(ctx, rdb, consumer); err != nil {
log.Fatal(err)
}
}The shared Lua script checks pending ownership, retrieves the source body, appends a failure envelope, then acknowledges this group. If the parking XADD errors, execution stops before XACK. If the client loses a successful reply, repeating the call finds no pending entry and returns without another copy. These properties assume the same Redis state survives; replication and persistence can still bound durability.
-- KEYS: source, parking. ARGV: group, consumer, source ID, reason, timestamp.
-- Both keys must share a Redis Cluster hash tag. Do not XDEL shared history.
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[3], ARGV[3], 1)
if #pending == 0 then return '' end
if pending[1][2] ~= ARGV[2] then return redis.error_reply('NOT_OWNER') end
local entries = redis.call('XRANGE', KEYS[1], ARGV[3], ARGV[3])
if #entries == 0 then return redis.error_reply('SOURCE_PAYLOAD_MISSING') end
local args = {'XADD', KEYS[2], '*',
'original_stream', KEYS[1], 'original_id', ARGV[3], 'group', ARGV[1],
'deliveries', tostring(pending[1][4]), 'reason', ARGV[4], 'parked_at', ARGV[5]}
for i = 1, #entries[1][2], 2 do
args[#args + 1] = 'payload.' .. entries[1][2][i]
args[#args + 1] = entries[1][2][i + 1]
end
-- If XADD fails, execution stops BEFORE XACK. Redis scripts do not roll back.
local parked = redis.call(unpack(args))
redis.call('XACK', KEYS[1], ARGV[1], ARGV[3])
return parkedThe script deliberately omits XDEL: another consumer group may still need the source entry. Both keys share {orders} for one Redis Cluster slot. Lua prevents command interleaving, not rollback of arbitrary failures; keep types, ACLs, group lifetime, and script arguments controlled. A stale business handler can still race recovery, so its effect must be idempotent.
Laravel calls the same script through the documented Redis::eval facade interface. This is raw Redis Streams integration, not the Laravel Redis queue driver.
<?php
namespace App\Messaging;
use Illuminate\Support\Facades\Redis;
use RuntimeException;
final class RedisParking
{
// Laravel normalizes EVAL's argument order for PhpRedis and Predis.
// Deploy the shared Lua file alongside this class (or adjust this path).
public function park(string $id, string $consumer, string $reason): string
{
$script = file_get_contents(__DIR__.'/../go/after/redis/park.lua');
if ($script === false) {
throw new RuntimeException('Missing parking script');
}
return (string) Redis::eval(
$script,
2,
'{orders}:work',
'{orders}:billing:parked',
'billing',
$consumer,
$id,
$reason,
gmdate(DATE_ATOM),
);
}
}In production systems
- RabbitMQ's documented quorum transfer retains unconfirmed dead letters and can accumulate duplicates at the target. Alert on transfer failure and source capacity, not only target depth.
- Kafka Connect documents sink-specific dead-letter controls; ordinary Kafka applications must implement their own transfer contract or select a framework with an explicit one.
- Redis documents removal of missing bodies from the PEL during
XAUTOCLAIM; trimming history before recovery can leave no payload to replay. - Laravel documents failed-job providers and retry commands; enabling a worker without checking failed storage leaves a gap in operational recovery.
In architecture: from a single process to a distributed system
Monolith: one process, one database
A CSV import stores rejected row references and reason codes in the same database as import progress. A repair screen can correct one row without a broker. If external email was already sent, a database rollback does not unsend it; track the effect's stable identity before retrying the row.
Modular monolith: explicit owners
Billing and shipping may share a deployment but need separate recovery responsibilities. Store consumer_name with source identity; a shipping repair must not accidentally re-run billing. A shared failure table is useful if ownership and access remain explicit.
Microservices: ownership follows the consumer
Orders publishes OrderPlaced; Billing parks it because a tax code is unsupported, while Shipping succeeds. Replaying onto a shared fan-out input can invoke Shipping again. Prefer a consumer-specific recovery route or ensure every subscriber deduplicates the original event. An outbox can make a repair record and recovery publication reliable; a saga handles business compensation when the original workflow cannot resume.
Distributed data: replicas, shards, and regions
A missing reference read from a lagging replica is not automatically invalid input. Check authoritative state before permanently rejecting it. Redis keys in different cluster slots cannot use the illustrated script together. Cross-region parking and source acknowledgment do not share a transaction; preserve original identity, define regional ownership, and reconcile unknown outcomes after failover.
Scaling path
| Load | Recovery design | Example |
|---|---|---|
| 1× | Per-consumer parking and manual selected replay | One operator repairs a malformed import |
| 10× | Indexed recovery register, reason dashboards, bounded replay workers | A deploy parks thousands of one schema version |
| 100× | Tenant/key isolation, quotas, protected payload storage, automated eligibility checks | Large replay runs alongside live orders without starving them |
The recovery path needs its own throughput budget. A queue that can accept 100,000 failed records per minute but whose owning team can classify ten per day is storing an operational debt, not delivering resilience.
Lab
All broker/Laravel experiments below are expected, not run. Use an existing disposable test environment. No Docker, Compose, or cluster startup is required by this chapter. The Go unit tests exercise transfer ordering without a broker; PHP syntax validation does not prove live package behavior.
1. Verify the source is not acknowledged when parking fails
cd docs/snippets/messaging/dead-letter-queue/go
go test ./after/kafka ./after/rabbitmq
# expected: parking failure never commits; channel settlement errors propagate.Read TestParkingFailureDoesNotCommit and TestCommitFailureIsReturnedAfterParking. They establish the intended local control flow. They do not simulate replica loss, rebalance timing, or a real broker protocol.
2. Observe RabbitMQ death history
Run the Go topology/consumer against a disposable RabbitMQ endpoint supplied in AMQP_URL. Publish an empty persistent message to queue orders through your normal confirmed publisher. The consumer rejects it without requeue; inspect orders.parked with manual acknowledgment and return it after inspection.
# expected, not run; the topology is created by the Go program.
go run ./after/rabbitmq
# Separate terminal:
rabbitmqctl list_queues name messages_ready messages_unacknowledged
# expected: orders.parked gains one; x-death reason is rejected, count is 1.Temporarily remove the target binding in this disposable environment and repeat. With the illustrated quorum at-least-once configuration, transfer remains unconfirmed at the source; restoring the binding allows forwarding. Do not change strategy to at-most-once as a recovery shortcut.
3. Expose the Kafka duplicate window
Create orders and orders.billing.DLT with your deployment's normal replication settings. Run the Go example, send an empty payload, and observe its origin headers in the DLT. Instrument a process exit immediately after ProduceSync returns and before CommitRecords; restart the consumer.
1 First run -> DLT: source orders partition 0 offset 12
2 First run -> process exits before source commit
3 Restart -> source offset 12 delivered again
4 Restart -> DLT receives another copy with identical original coordinatesExpected, not run: two DLT records can describe one original failure. Deduplicate the recovery case by group and source coordinates; do not assume Kafka producer idempotence merges application republishes after restart.
4. Redis parking failure, duplicate call, and second group
redis-cli XGROUP CREATE '{orders}:work' billing 0 MKSTREAM
redis-cli XGROUP CREATE '{orders}:work' audit 0
redis-cli XADD '{orders}:work' '*' event_id evt-1 body malformed
redis-cli XREADGROUP GROUP billing reaper-1 COUNT 1 STREAMS '{orders}:work' '>'
# Copy the returned stream ID into MSG_ID in your test shell.
# Use the same script as both client implementations:
redis-cli --eval after/redis/park.lua '{orders}:work' '{orders}:billing:parked' , billing reaper-1 "$MSG_ID" invalid-schema 2026-11-26T00:00:00Z
redis-cli XPENDING '{orders}:work' billing
redis-cli XLEN '{orders}:billing:parked'
redis-cli XREADGROUP GROUP audit auditor COUNT 1 STREAMS '{orders}:work' '>'
# expected, not run: billing pending=0; parking length=1; audit still reads body.Repeat the script with the same ID: expected, not run, no second parked entry. For a new source entry, use a separate parking key holding a string and run the script against it: expected WRONGTYPE, with the source still pending. Never overwrite a real stream for this experiment.
5. Laravel targeted recovery
php artisan queue:failed
php artisan queue:retry YOUR_FAILED_JOB_UUID
php artisan queue:failed
# expected, not run: selected job is dispatched; verify its business effect separately.
# Do not infer business completion from disappearance of the failed-job row.Cause a known permanent importer exception in a disposable Laravel 13 application with failed storage enabled. Verify the failure record, the original event ID, and the log hook. Repair the cause, retry only that UUID, and check that repeated delivery does not duplicate the business effect.
Common misconceptions
| Belief | Reality |
|---|---|
| A DLQ means the business operation completed | It means recovery responsibility changed |
| Every failure deserves parking | A broad outage may call for pausing; expected rejection is a normal outcome |
| DLX and DLQ are synonyms | An exchange routes; a queue stores |
| RabbitMQ DLX is always lossless | Default transfer is at-most-once; quorum safety needs explicit configuration |
x-death.count is total attempts | It counts deaths for a queue/reason pair |
| Skipping a Kafka commit protects the bad record | A later commit in that partition can pass it |
| Producer idempotence removes duplicate redrives | A new application publish can be a new record |
| Redis PEL is a parking stream | It tracks unacknowledged group deliveries |
Redis MULTI rolls back failed commands | Runtime command errors do not undo the other commands |
XDEL is cleanup for one group | It removes shared stream content needed by other groups |
failed() sees the final mutated job state | Laravel constructs a new job instance for the callback |
queue:retry all is a harmless repair | It can repeat side effects and overwhelm live dependencies |
| Empty DLQ proves health | Records may be lost, expired, skipped, or never stored |
Cheat sheet
| Topic | Remember |
|---|---|
| Classification | Permanent, transient, expected rejection, and unknown outcome differ |
| Terminal state | Exhaustion is a policy decision, not proof of poison |
| Transfer order | Accept parking before advancing the source |
| Duplicate boundary | Publish then acknowledge still has a crash window |
| Envelope | Original bytes, identity, coordinates, consumer, reason, version, times |
| RabbitMQ safety | Source quorum + at-least-once DLX + reject-publish + valid target |
| RabbitMQ history | Read x-death by queue/reason; do not call it handler attempts |
| Kafka | A committed position covers earlier records in that partition |
| Redis | Recheck ownership, append, acknowledge; retain shared source history |
| Laravel | Configure failed storage; retry selected IDs after repair |
| Replay | Keep event identity; add a separate replay batch identity |
| Ordering | Parking allows successors to run; replay cannot restore history |
| Operations | Measure new failures and oldest unresolved age, plus transfer failures |
| Retention | Recovery horizon must fit inside retained evidence |
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 — Why is acknowledging before parking unsafe? Must-know
Answer
Answer: A crash or destination failure after acknowledgment leaves neither recoverable source responsibility nor a durable parked copy.
2 — Why can publish-before-commit still create duplicates? Important
Answer
Answer: The publish may succeed and the worker may crash before source progress is recorded. Recovery repeats the source record and its parking write.
3 — What does RabbitMQ x-death.count=3 prove? Good to know
Answer
Answer: Three dead-letter events for the recorded queue/reason pair. It does not count every handler invocation or every requeue.
4 — Which settings make quorum DLX transfer at least once? Good to know
Answer
Answer: A source quorum queue with at-least-once dead-letter strategy, reject-publish overflow, configured DLX, required feature flag, and a usable destination topology. Persistence and target durability still matter.
5 — Why can committing a later Kafka message lose an earlier failed one? Important
Answer
Answer: Offsets represent a partition position, not individual acknowledgments. The later commit advances the group's resume position beyond earlier records too.
6 — Why does the Redis script omit XDEL? Good to know
Answer
Answer: XACK settles only the named group's pending entry; XDEL removes shared stream content that other groups may still need.
7 — Does an idle Redis claim prove the previous worker stopped? Important
Answer
Answer: No. A slow worker may still run. Recheck ownership before parking and make business effects idempotent or fenced.
8 — Why should replay preserve the business event ID? Must-know
Answer
Answer: The operation may already have partially or fully succeeded. A new business ID could bypass deduplication and repeat its effect.
9 — Can failed() rely on properties assigned inside Laravel handle()? Good to know
Answer
Answer: No. Laravel constructs a fresh instance for the failure callback. Persist needed diagnostic state or use original serialized identity.
10 — When is parking the wrong response to a failed record? Important
Answer
Answer: Examples include an expected business refusal, a broad transient outage better handled by pausing, or an ordered dependency where skipping makes later actions invalid.
Glossary
| Term | Meaning |
|---|---|
| Dead Letter Channel / DLQ | Destination for work the normal delivery/processing path cannot complete |
| Invalid Message Channel | Destination for input a receiver cannot meaningfully process |
| Dead-letter topic (DLT) | Kafka topic used by an application/framework for failed records |
| Poison message | Input that repeatedly fails under the current consumer contract |
| Transient failure | Failure that may clear as external conditions change |
| Terminal failure | Decision to stop automatic attempts |
| Parking lot | Holding state awaiting an explicit recovery decision |
| Quarantine | Parking with restricted handling for suspect content |
| Failure envelope | Original content or reference plus diagnostic metadata |
| Source identity | Coordinates identifying the original transport record |
| Business identity / event ID | Stable identity used to prevent repeated business effects |
| Replay / redrive | Sending selected failed work through a processing path again |
| Replay batch | Audited set of recovery attempts with its own identity |
| DLX | RabbitMQ normal exchange used to route dead-lettered messages |
dead-letter-exchange / x-dead-letter-exchange | RabbitMQ policy / declaration form of the DLX destination |
dead-letter-routing-key | Optional routing-key replacement during dead-lettering |
dead-letter-strategy | RabbitMQ quorum transfer safety mode |
overflow=reject-publish | Reject new publishes instead of evicting the head; needed for safe quorum DLX |
delivery-limit | Quorum maximum failed-delivery backstop |
x-death | Compressed RabbitMQ history by queue and reason |
x-delivery-count | RabbitMQ quorum failed-delivery counter, distinct from death history |
x-first-death-* / x-last-death-* | RabbitMQ first/latest dead-letter origin metadata |
original-expiration | Original AMQP expiration preserved after TTL removal |
| Publisher confirm | Broker acceptance signal used by reliable transfer protocols |
| Retry topic | Application destination for a later automatic attempt |
| Offset commit | Kafka group resume-position update |
| Kafka transaction | Atomic Kafka records and included consumed-offset update |
| Kafka Connect DLQ | Sink connector error-reporting path, not ordinary consumer behavior |
errors.tolerance | Connect fail-fast or tolerate-supported-errors setting |
errors.deadletterqueue.topic.name | Connect dead-letter destination |
errors.deadletterqueue.context.headers.enable | Connect option to attach diagnostic context headers |
| Pending entries list (PEL) | Redis group's delivered but unacknowledged entries |
XPENDING | Redis pending summary or detailed owner/idle/count query |
XCLAIM / XAUTOCLAIM | Explicit / cursor-based transfer of idle pending ownership |
JUSTID | Claim option returning IDs without incrementing delivery count |
XACK | Removes an entry from one consumer group's pending state |
XDEL | Deletes shared stream content |
| Hash tag | Redis key substring selecting a common Cluster slot |
Lua / EVAL | Redis server-side script execution without command interleaving |
failed_jobs | Laravel database failed-job storage |
queue:retry | Laravel failed-job redispatch command |
failed() / Queue::failing() | Per-job / global Laravel failure observation hooks |
| Retention | How long recovery evidence remains available |
| Oldest unresolved age | Time since the oldest case still lacking a final disposition |
| Idempotency | Repetition has no additional business effect |
| Fencing | Rejecting actions from a stale owner using a checked authority/version |
References
- Hohpe and Woolf: Dead Letter Channel.
- RabbitMQ: Dead Letter Exchanges, Quorum Queues.
- Apache Kafka: Design and delivery semantics, Kafka Connect configuration.
- Redis: XPENDING, XCLAIM, XAUTOCLAIM, EVAL.
- Laravel 13: Queues, Redis scripting.
- Laravel RabbitMQ package: README.
- Audited client sources: Laravel Kafka Consumer, Producer, php-rdkafka README.
- Laravel Kafka v2.13: Failed messages, Consumer options.
- php-rdkafka: Delivery reports, Flush.
- Go clients: amqp091-go, franz-go kgo, go-redis.