Skip to content

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 forGo to
Whether an error belongs in a DLQClassification
A guarantee that parking does not silently discard workTransfer boundary
What to save alongside the bodyFailure envelope
RabbitMQ DLX and x-death detailsBroker differences
Kafka offset and Redis PEL trapsBroker differences
Laravel failed_jobs and queue:retryLaravel
A replay plan for an incidentSolutions
Reproducible failure experimentsLab

Everything in one minute ​

QuestionWorking answerFailure if ignored
Is this a retry destination?A retry destination has an automatic next attempt; a parking lot waits for a decisionA supposed DLQ becomes another infinite loop
Does parking mean success?It means responsibility moved to a recovery workflowBusiness work remains incomplete
Can I acknowledge first?Only if losing the failed work is acceptableCrash after acknowledgment loses the only copy
Is publish then acknowledge enough?It prevents one loss window but permits duplicatesCrash after publish creates two parked copies
Is replay the original delivery?Usually a new transport delivery with the same business identityNew IDs defeat deduplication
Does a nonempty DLQ always indicate bad input?No: exhaustion, expiry, overflow, or dependency failures can also park workIncident classification points to the wrong owner
PropertyRabbitMQKafkaRedis StreamsLaravel worker
Parking primitiveDLX routes to a queueApplication writes a DLT topicApplication writes a parking streamConfigured failed-job provider
Source progressReject without requeueCommit next offsetXACK removes group pending entryWorker records terminal failure
Failure historyBroker x-deathApplication or framework headersApplication metadata and PEL counterPayload, exception, connection, queue
Automatic terminal thresholdQuorum delivery-limitConsumer policyRecovery policyAttempt/deadline policy
Durability trapDefault DLX transfer lacks internal confirmsPublish and commit are separateMULTI does not roll back command errorsStorage may be disabled or unavailable
Replay orderingRe-enters behind other workNew offset after newer recordsNew stream ID after newer entriesNew 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 pathIsolate into a parking lot
Preserves processing order if the partition stopsAllows later messages to progress
A transient dependency may recover automaticallyRequires explicit repair or disposition
A poison message can monopolize capacityParking needs storage, retention, and ownership
Failure stays near the normal handlerRecovery 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.

Sourcemessage + identityClassifyfailure or successRetry destinationautomatic next tryParking lotowner + evidenceRepair and replaysame event identitydelivertransientterminalreviewParking preserves responsibility; it does not complete the business operation.

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.

text
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 E

Real 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.

FailureClassification questionAction
Invalid JSON or unsupported versionCan this build decode the bytes?Park raw bytes immediately
Dependency unavailableIs the outage broad across healthy messages?Pause or bounded retry; avoid flooding parking
Authentication deniedDid credentials or permissions change?Stop the affected consumer and alert
Business rule rejectedIs rejection an expected business outcome?Record the outcome; do not automatically label it poison
External request timed outCould the side effect already have happened?Reconcile with a stable idempotency key
Attempt budget exhaustedIs 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.

text
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 fix

Real 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.

MechanismWhat prevents an accidental loop
RabbitMQ parking queueNo TTL/DLX route automatically returns it to work
Kafka DLTRecovery group is separate from the normal input group
Redis parking streamReaper reads the work stream, not its own parking output
Laravel failed-job providerqueue: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.

text
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 duplication

Real 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”.

TransferSafe directionRemaining boundary
RabbitMQ quorum at-least-once DLXInternal confirm before removing source responsibilityTarget duplicates; broker/storage failure assumptions
Kafka manual consumerConfirm DLT publish before commitCrash creates duplicate DLT records
Kafka transactionDLT write and consumed offsets commit togetherApplies within Kafka, not external database/HTTP effects
Redis Lua parkingValidate ownership, XADD, then XACKPersistence/failover durability; scripts have no rollback
Laravel failure storageConfigured provider records failureDriver 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.

Unsafeacknowledge sourceCrashno parked copyLost worksource cannot recoverSaferpublish parking copyCrash before acksource redeliversDuplicate possiblededuplicate by identitythenresultacceptedretryAn atomic boundary can close the gap only for effects inside that boundary.

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.

text
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
FieldPurposeCaution
event_idBusiness deduplication identityKeep it across replay
Original queue/topic/streamDestination lineageStore a routing allowlist, not arbitrary operator input
Group, partition, offset or stream IDIdentifies the failing consumer deliveryKafka coordinates need the group to identify responsibility
Raw body or encrypted payload referenceRecover malformed contentApply size and retention limits
Reason code and exception classStable classificationStack traces and exception messages can contain secrets
Attempt/delivery countShows the chosen stopping thresholdDelivery is not necessarily one handler execution
First/last failure timeMeasures unresolved ageProducer timestamp is not parking time
Consumer build and schema versionExplains compatibilityA replay may run different code
Replay batch and operator identityAudit of recovery decisionsDo 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.

text
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 shipment

Real 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.

RequirementRecovery strategyCost
Strict dependent sequenceStop partition/key until repairedLater work waits
Independent messagesPark and continueNeed separate recovery ownership
Latest-state projectionApply only increasing entity versionsRequires trustworthy versions
Irreversible external effectReconcile before replayMore operational work
Large incidentCanary, then bounded batchesSlower 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.

Inspectreason + versionRepaireligible selectionCanaryobserve effectsBounded replaylive-traffic quotaResolveverify business statePreserve original event ID; add a separate replay batch ID.Stop on new failures. A successful publish is not proof of business completion.

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.

MeasureInterpretationResponse
New parked messages per minuteNew failures, independent of drain rateCompare by deployment and reason
Oldest unresolved failureRecovery is falling behindEscalate before retention expires
Parking write failuresPrimary work cannot be safely transferredStop advancement; restore destination
Replay failure fractionFix or selection may be wrongStop the batch
Bytes retainedCapacity requirementSize for incident horizon plus overhead
Unowned recordsProcess failureAssign 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 fieldMeaning
dead-letter-exchangePolicy destination exchange; normal exchange routing still applies
dead-letter-routing-keyOptional replacement routing key
x-dead-letter-exchangeQueue declaration argument; overrides the matching policy value
dead-letter-strategy=at-least-onceSource quorum queue keeps responsibility until internal confirms
overflow=reject-publishRequired for quorum at-least-once DLX; drop-head disables that guarantee
delivery-limitQuorum poison-delivery backstop; default 20 since RabbitMQ 4.0
x-death.reasonrejected, expired, maxlen, or delivery_limit
x-death.countCount for one queue/reason pair, not total business attempts
x-first-death-* / x-last-death-*First/most recent queue, exchange, reason
original-expirationPreserved 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 signalMeaningResponse
AMQP 406 PRECONDITION_FAILEDExisting queue arguments conflict with declarationFix topology deployment; do not hot-delete a live queue
RabbitMQ DLX forward failure logDestination cannot accept transferCheck exchange, bindings, target quorum, limits
Kafka DLT produce errorDestination write not known successfulDo not commit; stop or pause
Kafka commit errorSource progress is uncertainStop; allow duplicate-safe recovery
Redis NOGROUPConsumer group missingRestore expected topology; do not acknowledge elsewhere
Redis WRONGTYPEDestination/source is not a streamFix key collision; failed XADD must leave source pending
Redis CROSSSLOTScript keys do not share a cluster slotUse a common hash tag or another transfer protocol
NOT_OWNER / SOURCE_PAYLOAD_MISSINGApplication script detected stale ownership or absent bodyReinspect 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.

sql
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 ​

ProblemSolutionBenefitLimitation
DLQ destination unavailableKeep source recoverable and stop advancingAvoids silent lossNormal work may slow or stop
All records fail after deployRoll back/pause, classify a sampleStops a failure stormRequires deployment evidence
Mixed reasons in one DLQFilter by reason, version, tenant, ageReplays only eligible recordsMetadata must be trustworthy
Duplicate parked copiesDeduplicate by source and consumer; effect by event IDStable incident accountingSource ID alone is not a business key
Payload needs correctionPreserve original; create audited corrected versionMaintains evidenceDecide whether it is the same business operation
DLQ is near retention expiryExport protected evidence or extend retentionBuys investigation timePrivacy and storage obligations remain
Ordered dependent workflowBlock key/partition or reconcile statePrevents invalid later actionsReduced throughput
Replay overloadSeparate quota, canary, pause thresholdProtects live trafficLonger 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 ​

SituationChooseWhy
Malformed immutable bytesImmediate quarantineTime alone cannot repair decoding
Short dependency outageBounded retry or pauseParking everything shifts an outage into manual work
Expected business rejectionNormal rejected outcomeA valid refusal is not necessarily infrastructure failure
Exhausted automatic budgetParking with ownershipPreserves work while stopping resource waste
Strictly ordered dependent recordsStop affected sequenceSkipping creates invalid downstream state
Independent analytics eventsPark and continueOne bad event need not block the partition forever
Irreversible payment uncertaintyReconcile before replayRetrying may duplicate a completed charge
Intentionally disposable telemetryExplicit discard policyA 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.

go
// 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.

go
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
<?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
<?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 out

The 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.

OperationPurposeOperational caution
make:queue-failed-table, migrateCreate missing failed-job storageCheck the configured provider first
queue:failedList failed jobsRestrict payload inspection access
queue:retry UUIDRepublish one failed jobFix cause and preserve business identity
queue:retry --queue=ordersRetry selected queue's jobsSelection may contain different causes
queue:retry allRetry all recorded failuresUsually too broad during an incident
queue:forget UUIDDelete one failure recordDeletion is a disposition decision
queue:flushDelete failed-job recordsDoes not mean business recovery succeeded
queue:prune-failed --hours=720Retain the last 30 daysDefault prune horizon is 24 hours
Queue::failing()Observe JobFailed globallyMonitoring hooks can also fail
horizon:forgetDelete failures managed through HorizonUse 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.

go
// 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
<?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',
                ],
            ],
        ],
    ],
];
bash
# 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 10

Do 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.

go
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
<?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.

go
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.

lua
-- 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 parked

The 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
<?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 ​

LoadRecovery designExample
1×Per-consumer parking and manual selected replayOne operator repairs a malformed import
10×Indexed recovery register, reason dashboards, bounded replay workersA deploy parks thousands of one schema version
100×Tenant/key isolation, quotas, protected payload storage, automated eligibility checksLarge 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 ​

bash
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.

bash
# 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.

text
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 coordinates

Expected, 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 ​

bash
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 ​

bash
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 ​

BeliefReality
A DLQ means the business operation completedIt means recovery responsibility changed
Every failure deserves parkingA broad outage may call for pausing; expected rejection is a normal outcome
DLX and DLQ are synonymsAn exchange routes; a queue stores
RabbitMQ DLX is always losslessDefault transfer is at-most-once; quorum safety needs explicit configuration
x-death.count is total attemptsIt counts deaths for a queue/reason pair
Skipping a Kafka commit protects the bad recordA later commit in that partition can pass it
Producer idempotence removes duplicate redrivesA new application publish can be a new record
Redis PEL is a parking streamIt tracks unacknowledged group deliveries
Redis MULTI rolls back failed commandsRuntime command errors do not undo the other commands
XDEL is cleanup for one groupIt removes shared stream content needed by other groups
failed() sees the final mutated job stateLaravel constructs a new job instance for the callback
queue:retry all is a harmless repairIt can repeat side effects and overwhelm live dependencies
Empty DLQ proves healthRecords may be lost, expired, skipped, or never stored

Cheat sheet ​

TopicRemember
ClassificationPermanent, transient, expected rejection, and unknown outcome differ
Terminal stateExhaustion is a policy decision, not proof of poison
Transfer orderAccept parking before advancing the source
Duplicate boundaryPublish then acknowledge still has a crash window
EnvelopeOriginal bytes, identity, coordinates, consumer, reason, version, times
RabbitMQ safetySource quorum + at-least-once DLX + reject-publish + valid target
RabbitMQ historyRead x-death by queue/reason; do not call it handler attempts
KafkaA committed position covers earlier records in that partition
RedisRecheck ownership, append, acknowledge; retain shared source history
LaravelConfigure failed storage; retry selected IDs after repair
ReplayKeep event identity; add a separate replay batch identity
OrderingParking allows successors to run; replay cannot restore history
OperationsMeasure new failures and oldest unresolved age, plus transfer failures
RetentionRecovery horizon must fit inside retained evidence

Self-check: questions & answers ​

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

1 — 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 ​

TermMeaning
Dead Letter Channel / DLQDestination for work the normal delivery/processing path cannot complete
Invalid Message ChannelDestination for input a receiver cannot meaningfully process
Dead-letter topic (DLT)Kafka topic used by an application/framework for failed records
Poison messageInput that repeatedly fails under the current consumer contract
Transient failureFailure that may clear as external conditions change
Terminal failureDecision to stop automatic attempts
Parking lotHolding state awaiting an explicit recovery decision
QuarantineParking with restricted handling for suspect content
Failure envelopeOriginal content or reference plus diagnostic metadata
Source identityCoordinates identifying the original transport record
Business identity / event IDStable identity used to prevent repeated business effects
Replay / redriveSending selected failed work through a processing path again
Replay batchAudited set of recovery attempts with its own identity
DLXRabbitMQ normal exchange used to route dead-lettered messages
dead-letter-exchange / x-dead-letter-exchangeRabbitMQ policy / declaration form of the DLX destination
dead-letter-routing-keyOptional routing-key replacement during dead-lettering
dead-letter-strategyRabbitMQ quorum transfer safety mode
overflow=reject-publishReject new publishes instead of evicting the head; needed for safe quorum DLX
delivery-limitQuorum maximum failed-delivery backstop
x-deathCompressed RabbitMQ history by queue and reason
x-delivery-countRabbitMQ quorum failed-delivery counter, distinct from death history
x-first-death-* / x-last-death-*RabbitMQ first/latest dead-letter origin metadata
original-expirationOriginal AMQP expiration preserved after TTL removal
Publisher confirmBroker acceptance signal used by reliable transfer protocols
Retry topicApplication destination for a later automatic attempt
Offset commitKafka group resume-position update
Kafka transactionAtomic Kafka records and included consumed-offset update
Kafka Connect DLQSink connector error-reporting path, not ordinary consumer behavior
errors.toleranceConnect fail-fast or tolerate-supported-errors setting
errors.deadletterqueue.topic.nameConnect dead-letter destination
errors.deadletterqueue.context.headers.enableConnect option to attach diagnostic context headers
Pending entries list (PEL)Redis group's delivered but unacknowledged entries
XPENDINGRedis pending summary or detailed owner/idle/count query
XCLAIM / XAUTOCLAIMExplicit / cursor-based transfer of idle pending ownership
JUSTIDClaim option returning IDs without incrementing delivery count
XACKRemoves an entry from one consumer group's pending state
XDELDeletes shared stream content
Hash tagRedis key substring selecting a common Cluster slot
Lua / EVALRedis server-side script execution without command interleaving
failed_jobsLaravel database failed-job storage
queue:retryLaravel failed-job redispatch command
failed() / Queue::failing()Per-job / global Laravel failure observation hooks
RetentionHow long recovery evidence remains available
Oldest unresolved ageTime since the oldest case still lacking a final disposition
IdempotencyRepetition has no additional business effect
FencingRejecting actions from a stale owner using a checked authority/version

References ​

Built by Morteza Negahi