Lesson 5 of 9 · 27m
Messenger: Async Work That Survives Failure
Commands, handlers, transports, retries, idempotency, serialization, and the operational design behind reliable background processing.
Messenger makes background work easy, which is exactly why production queues become graveyards of duplicate emails and poison messages retried forever. The tool is simple. Reliability is the design work.
A message is intent, not a service call
final readonly class GenerateInvoicePdf
{
public function __construct(public string $invoiceId) {}
}
final class GenerateInvoicePdfHandler
{
public function __invoke(GenerateInvoicePdf $message): void
{
// reload the invoice, render, store
}
}Messages should be small, serializable, and meaningful months later when an operator inspects the failure queue. Store ids and reload state; do not serialize entities and their accidental object graphs.
Configure transport behavior explicitly
framework:
messenger:
transports:
async:
dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
retry_strategy:
max_retries: 3
delay: 1000
multiplier: 2
routing:
App\Message\GenerateInvoicePdf: asyncRun workers with ceilings so long-running PHP processes recycle leaks instead of becoming incidents:
php bin/console messenger:consume async --time-limit=3600 --memory-limit=256MRetries amplify whatever is wrong
A handler that always fails will retry exactly as configured. A handler that partially succeeds can duplicate effects on every retry. Make work idempotent:
if ($this->storage->exists($invoice->pdfPath())) {
return; // replay-safe: generation already completed
}Use natural idempotency keys, unique constraints, upserts, or explicit processing records. Queues are allowed to redeliver.
Failure queues are operational interfaces
messenger:failed:show, retry, and remove are not enough by themselves. Alert on failure depth and age. Four thousand dead messages are user-visible breakage accumulating silently. Choose async where latency, isolation, or burst absorption justifies it — not because scale is fashionable. Async adds deploy ordering, schema compatibility, replay, and observability costs.
Field notes
- Configure a failure transport before production, not after the first incident.
- Do not dispatch inside a database transaction unless you understand outbox semantics; workers can run before commit.
- Do not swallow exceptions to make workers green. Red queues are information.
- Measure queue latency, not merely worker CPU.
- Adding a required message constructor property is a breaking deploy when old payloads or workers coexist.
Was this lesson helpful?