DEV Community

Cover image for Retry #1 Forever: What Symfony Messenger 8.1 Expects From Your Custom Serializer
Matt Mochalkin
Matt Mochalkin

Posted on

Retry #1 Forever: What Symfony Messenger 8.1 Expects From Your Custom Serializer

Your worker is logging the same line over and over:

WARNING: Sending for retry #1 using 0 ms delay. Error: "Cannot decode message: unknown encryption key "k2"."
Enter fullscreen mode Exit fullscreen mode

Retry #1, again and again. max_retries is 3. The failure transport is empty. The message is still in the queue, nothing else in that queue moves, and nothing crashed, so no alert fired.

That is what a custom Messenger serializer written before Symfony 8.1 does on 8.1.0 through 8.1.10 when it meets a payload it cannot read. I hit it while writing a serializer decorator for compression and encryption (that article mentions it in two sentences). This one is the full story: what 8.1 changed in the decode contract and why, where the retry counter goes, the fix that shipped in 8.1.11 and how to write decode() today so a poisoned message ends up on the failure transport instead of in a loop. There is a second, unrelated trap in the Redis transport at the end, found the same week.

Prerequisites

  • symfony/messenger 8.1. The loop exists on 8.1.0 to 8.1.10; the fix is in 8.1.11 (released 4 November 2026) and in 8.2.
  • Any transport with a receiver: the reproducer uses symfony/doctrine-messenger 8.1 on SQLite in memory, no framework, one PHP file.
  • A custom serializer, or a decorator around the built-in Serializer. If every transport you have uses the stock Serializer or PhpSerializer, you are not affected by the loop, but the contract in section 4 still applies to any serializer you write next.

The reproducer is at mattleads/messenger-decode-throw-repro: php repro.php throw and php repro.php return.

1. What 8.0 did with a message it could not decode

Before 8.1, a serializer reported a decoding failure by throwing MessageDecodingFailedException from decode(). The Doctrine receiver on 8.0 handled it like this:

// symfony/doctrine-messenger 8.0, DoctrineReceiver::createEnvelopeFromData()
try {
    $envelope = $this->serializer->decode([
        'body' => $data['body'],
        'headers' => $data['headers'],
    ]);
} catch (MessageDecodingFailedException $exception) {
    $this->connection->reject($data['id']);

    throw $exception;
}
Enter fullscreen mode Exit fullscreen mode

Reject, then rethrow. The reject deletes the row. The rethrow escapes Worker::run(), which has no catch around $receiver->get(), and messenger:consume only wraps the run in a finally. So the worker process exited with the exception and the message was gone. Under a process manager the worker restarted and ate the next poisoned message the same way. Nothing reached the failure transport, because the failure path starts at the bus and the message never got there.

The usual way to meet this was a deploy that renamed a message class while the queue still held the old name. Symfony issue #44117, opened in 2021, asked that those messages stop being deleted.

2. What 8.1 changed, and the piece that makes retries work

Symfony 8.1 (May 2026) routes decoding failures through the same pipeline as a failing handler. Nicolas Grekas' PR #62888 did three things:

  1. MessageDecodingFailedException got a wrap() factory and an encodedEnvelope property. wrap($encodedEnvelope, $message) returns an Envelope whose message is the exception, and the exception carries the raw body and headers it could not read.
  2. Receivers no longer delete and throw. They yield the wrapped envelope with their own stamps, so ack() and reject() work on it like on any message.
  3. A new DecodeFailedMessageMiddleware sits early in the bus. When the message is a MessageDecodingFailedException, it looks up the serializer of the transport that received it and calls decode() again. If decoding now works (the class was deployed, the key arrived), the real message continues down the stack with the stamps of the failed envelope merged in. If it still fails, the exception is thrown and the retry listener does its job.

The contract for serializers changed with it. From the 8.1.0 docblock of SerializerInterface::decode():

On failure, implementations SHOULD return an Envelope wrapping a MessageDecodingFailedException instead of throwing, so that the worker can route the failure through the normal retry/DLQ path. Throwing a MessageDecodingFailedException is still supported for BC with custom serializers; transports will wrap the exception as a fallback.

How does Messenger know this is retry #2 and not retry #1? Through a stamp. SendFailedMessageForRetryListener reads RedeliveryStamp::getRetryCountFromEnvelope(), which is the count on the last RedeliveryStamp of the envelope, or 0 if there is none. When a message is sent back for a retry, the listener adds a new RedeliveryStamp with the incremented count, and the serializer writes it into the headers as X-Message-Stamp-...RedeliveryStamp. On the next delivery the serializer decodes the headers, the stamp is back on the envelope, the count continues.

So the retry counter lives in the headers of the message, and it comes back only if decode() puts it back. That is the whole bug.

The built-in Serializer on 8.1 decodes the stamps first and keeps the ones that decode on every failure path:

// symfony/messenger 8.1.11, Serializer::decode()
// a failure keeps the stamps that decode, so that its retries are counted
$stamps = $this->decodeStamps($encodedEnvelope, $stampFailure);
// ...
try {
    $message = $this->serializer->deserialize($encodedEnvelope['body'], $type, $this->format, $context);
} catch (\Throwable $e) {
    return MessageDecodingFailedException::wrap($encodedEnvelope, 'Could not decode message: '.$e->getMessage(), (int) $e->getCode(), $e)->with(...$stamps);
}
Enter fullscreen mode Exit fullscreen mode

It took three fixes on the 8.1 branch to get the stock serializer there. PR #65122 (August 2026) stopped encode() from serializing the live exception as the new body, which had made the payload roughly double on every round, and re-sends the original body instead. PRs #66460 and #66452 (September 2026) kept the stamps when the body is empty or a stamp header is broken, and sent messages with a bad signature straight to the failure transport, since a retry cannot make a signature verify. Each of those was the same lost counter in a different place. Custom serializers had the fourth.

3. The trap: throw, and the counter never comes back

Every receiver on 8.1 kept the catch as the BC fallback the docblock promised. The 8.1.10 Doctrine receiver:

// symfony/doctrine-messenger 8.1.10 and 8.1.11, DoctrineReceiver::createEnvelopeFromData()
$stamps = [
    new DoctrineReceivedStamp($data['id']),
    new TransportMessageIdStamp($data['id']),
];

try {
    return $this->serializer->decode($data = [
        'body' => $data['body'],
        'headers' => $data['headers'],
    ])->withoutAll(TransportMessageIdStamp::class)->with(...$stamps);
} catch (MessageDecodingFailedException $e) {
    return MessageDecodingFailedException::wrap($data, $e->getMessage(), $e->getCode(), $e)->with(...$stamps);
}
Enter fullscreen mode Exit fullscreen mode

Look at what $stamps holds in the catch: the receiver's two stamps. Nothing from the headers. The receiver cannot decode them, because the only component that knows the header format just threw. The RedeliveryStamp is in the row, in the headers column, and it never reaches the envelope.

From there the sequence is mechanical. The wrapped envelope reaches DecodeFailedMessageMiddleware, which calls decode() again. The serializer throws again. On 8.1.0 to 8.1.10 the middleware had no try around that call, so the raw MessageDecodingFailedException escapes to the worker. The retry listener sees an envelope with no RedeliveryStamp, computes retry count 0, decides 0 < 3, and sends the message back with a RedeliveryStamp(1). The serializer's encode() writes it into the headers. Next delivery, the serializer throws before reading headers, the stamp is lost, count is 0 again. Retry #1, forever.

The reproducer has one serializer with two modes. It wraps the stock Serializer and pretends it cannot read the body:

final class UnreadableSerializer implements SerializerInterface
{
    public function decode(array $encodedEnvelope): Envelope
    {
        $error = 'Cannot decode message: unknown encryption key "k2".';

        if ('throw' === $this->mode) {
            // pre-8.1 contract, "still supported for BC" according to SerializerInterface::decode()
            throw new MessageDecodingFailedException($error);
        }

        // 8.1 contract: return the failure, and keep the stamps that still decode from the headers
        $stamps = array_merge(...array_values($this->inner->decode($encodedEnvelope)->all()));

        return MessageDecodingFailedException::wrap($encodedEnvelope, $error)->with(...$stamps);
    }
}
Enter fullscreen mode Exit fullscreen mode

Doctrine transport, max_retries: 3, a failure transport, one message, one worker with a time limit. php repro.php throw on 8.1.10:

WARNING: ... Sending for retry #1 using 0 ms delay. Error: "Cannot decode message: unknown encryption key "k2"."
WARNING: ... Sending for retry #1 using 0 ms delay. ...
WARNING: ... Sending for retry #1 using 0 ms delay. ...
(repeats until the worker is stopped)

mode=throw  still queued on async: 1  on failure transport: 0
Enter fullscreen mode Exit fullscreen mode

php repro.php return, same serializer, same message:

WARNING: ... Sending for retry #1 using 0 ms delay. ...
WARNING: ... Sending for retry #2 using 0 ms delay. ...
WARNING: ... Sending for retry #3 using 0 ms delay. ...
CRITICAL: ... Removing from transport after 3 retries. ...
INFO: Rejected message ... will be sent to the failure transport ...

mode=return  still queued on async: 0  on failure transport: 1
Enter fullscreen mode Exit fullscreen mode

The only difference between the two runs is whether decode() throws or returns.

Two things make this worse than the 8.0 behavior in practice. On 8.0 the worker died, which is loud. On 8.1 the worker stays up and busy, the queue depth stays flat at one, and the failure transport, the place you look when something is wrong with a message, is empty. And the throwing path is the one every serializer written against 7.x or 8.0 uses, because it was the only path that existed.

4. The fix in 8.1.11

The receiver cannot restore the counter, so the fix had to live where the second decode() happens. The issue I opened proposed two options: treat a thrown failure as unrecoverable in the middleware, or make the retry listener read the count back from the raw header when the envelope has no stamp. The second only works for serializers that use the stock header format. Ptraaah, a first-time contributor, took the first option in PR #67799 the same day:

// symfony/messenger 8.1.11, DecodeFailedMessageMiddleware::handle()
try {
    $decodedEnvelope = $serializer->decode($message->encodedEnvelope);
} catch (MessageDecodingFailedException $e) {
    // the stamps of a thrown failure are lost and its retries cannot be counted, so it should not be retried
    throw $e->getPrevious() instanceof UnrecoverableExceptionInterface ? $e->getPrevious() : new UnrecoverableMessageHandlingException($e->getMessage(), $e->getCode(), $e);
}
Enter fullscreen mode Exit fullscreen mode

A thrown decoding failure becomes an UnrecoverableMessageHandlingException, with the original exception as previous. The retry listener sees an unrecoverable exception, skips the retries, and the message goes to the failure transport after 0 retries. From there messenger:failed:retry replays it through DecodeFailedMessageMiddleware once the serializer can read it. Serializers that return wrap() keep their retries, since their stamps are intact.

Nicolas Grekas added a worker-level test to FailureIntegrationTest that runs a throwing serializer through a real Worker, asserts one failure with count 0 and class UnrecoverableMessageHandlingException, and then replays the message from the failure transport once the serializer works. He also changed SigningSerializer: it used to catch everything its inner serializer threw and return it as a wrapped failure, which lost the inner serializer's stamps the same way. It now rethrows what the inner serializer throws (wrapped in MessageDecodingFailedException if it was something else), so the fix covers signed messages too.

The docblock no longer promises that throwing is equivalent:

Throwing a MessageDecodingFailedException is still supported for BC, but the stamps of the message are then lost. In this case, the message is sent to the failure transport without being retried.

What a serializer that cannot read a payload gets on each version:

decode() does 8.0 8.1.0 to 8.1.10 8.1.11 and later
throws MessageDecodingFailedException message deleted, worker exits retry #1 forever, failure transport empty failure transport after 0 retries, replay possible
returns wrap() with the decoded stamps not available retried up to max_retries, then failure transport same
returns wrap() without stamps not available retry #1 forever retry #1 forever

The last row is the one to remember. The fix handles throwing. It cannot handle a serializer that returns a wrapped failure and drops the stamps, because from the outside that envelope looks like a first delivery. If you return, you must return the stamps.

5. The contract to write against today

Three rules, taken from the 8.1.11 docblock and the docs' custom serializer example.

Return the failure, do not throw it. MessageDecodingFailedException::wrap($encodedEnvelope, $message, $code, $previous) gives you the envelope. The raw body and headers go into the exception, so the message can be sent again as it was received.

Keep every stamp you can still decode. For a decorator around the stock Serializer that is one call: the inner serializer's decode() on the unreadable payload returns its own failure envelope, and that envelope carries the stamps it read from the headers. Take them:

public function decode(array $encodedEnvelope): Envelope
{
    try {
        $body = $this->open($encodedEnvelope); // decrypt, decompress, whatever can fail
    } catch (\Throwable $e) {
        // the inner serializer still reads the headers, and the RedeliveryStamp is in them
        $stamps = array_merge(...array_values($this->inner->decode($encodedEnvelope)->all()));

        return MessageDecodingFailedException::wrap($encodedEnvelope, $e->getMessage(), (int) $e->getCode(), $e)->with(...$stamps);
    }

    return $this->inner->decode(['body' => $body] + $encodedEnvelope);
}
Enter fullscreen mode Exit fullscreen mode

This relies on the stamps living in the headers, which is how Serializer stores them. PhpSerializer puts the whole envelope in the body, so a decorator around it has nothing to recover when the body is unreadable, and a thrown failure on 8.1.11 is the honest answer there.

Re-send a failure as it was received. When the failed message is retried or moved to the failure transport, your encode() gets an envelope whose message is the MessageDecodingFailedException. Do not transform that body again. The stock Serializer already handles it: it re-emits encodedEnvelope['body'] as is, keeps the original type header, and writes the current stamps, including the new RedeliveryStamp, into the headers. A decorator only has to step aside:

public function encode(Envelope $envelope): array
{
    $encoded = $this->inner->encode($envelope);

    // a decoding failure is sent again with its original body, which is transformed already
    if ($envelope->getMessage() instanceof MessageDecodingFailedException) {
        return $encoded;
    }

    $encoded['body'] = $this->seal($encoded['body']);

    return $encoded;
}
Enter fullscreen mode Exit fullscreen mode

A serializer that does not delegate, like the token decoder in the docs, returns $message->encodedEnvelope directly from encode() for a failure. That is the example the docs show since PR #23459, which replaced the old return new Envelope($throwable) in the "Message Serializer For Custom Data Formats" section. The old example dispatched a plain throwable as a message, and its encode() then threw when the worker tried to re-send it.

One configuration rule goes with this. The failure transport must use the same serializer as the transport that fed it, because DecodeFailedMessageMiddleware re-decodes with the serializer of the original transport and the failure transport has to be able to store the payload that serializer produced. The docs say so under "Handling Decode Failures". The reproducer gets away with a PhpSerializer on the failure transport only because it never replays.

6. The sibling trap: the Redis DSN overrides consumer

Found the same week, while testing the Redis transport. The docs list consumer as an option you can set in the DSN or under options in messenger.yaml, with an example that sets it from an env var under options. Right above that list sits the "Full DSN Example", and it ends in /messages/symfony/consumer.

In Connection::parseDsn() the query string is merged over the options array, and in fromDsn() the path segments are read last:

// symfony/redis-messenger 8.1.11, Connection::fromDsn()
$pathParts = explode('/', rtrim($params['path'] ?? '', '/'));
$options['stream'] = $pathParts[1] ?? $options['stream'];
$options['group'] = $pathParts[2] ?? $options['group'];
$options['consumer'] = $pathParts[3] ?? $options['consumer'];
Enter fullscreen mode Exit fullscreen mode

So whoever copies the full example and then sets consumer: '%env(MESSENGER_CONSUMER_NAME)%' gets every worker registered in Redis under the literal name consumer, with no warning. Verified on symfony/redis-messenger 8.1.10 against a live Redis, with consumer: worker-42 under options:

DSN Consumer registered in Redis
redis://localhost/messages worker-42
redis://localhost/messages/symfony worker-42
redis://localhost/messages/symfony/consumer consumer
redis://localhost?consumer=dsnq dsnq
redis://localhost/messages/symfony/dsnpath?consumer=dsnq dsnpath

The precedence is the same in 5.4, 6.4 and 7.4. Note the docs' general "Transport Configuration" section says options under options take precedence over the DSN; for the Redis transport the code does the opposite, and the path wins over the query. The Redis section now says so (docs PR #23472, merged into 6.4 so it reaches every maintained branch): when the name comes from options, stop the DSN path at /stream/group.

The name is not cosmetic. Redis tracks the pending entries of a stream group per consumer name, so every worker that shares the name consumer shares one pending list, and the per-worker accounting the option exists for is gone.

7. How this went upstream

For anyone who has not sent a bug to Symfony before, the sequence, with dates.

On 1 November 2026 I opened symfony-docs PR #23459 to fix the custom serializer example, because the docs example was the first thing I had copied and it was wrong on 8.1. Javier Eguiluz merged it the next day.

On 2 November I opened symfony/symfony issue #67791 with the one-file reproducer linked above and the two options from section 4. Ten hours later Ptraaah, a first-time contributor, picked option 1 and opened PR #67799 with tests. The next morning I ran the PR branch against the reproducer on 8.1.10 (throw mode now lands on the failure transport after 0 retries, return mode unchanged) and suggested a worker-level test in FailureIntegrationTest, where the three earlier counter fixes had put theirs. Nicolas Grekas added that test and the SigningSerializer change, and merged on 3 November. 8.1.11 shipped on 4 November with it.

The Redis docs PR #23472 went in on 5 November and was merged the next day.

Three things made it quick. The reproducer had no framework, so anyone could run it in a minute. The issue named the exact line in each receiver where the stamps were lost, which turned "retried forever" into a known shape the maintainers had already fixed three times. And the proposed fix was the smallest one that matched an existing pattern in the same file.

Conclusion

If you maintain a custom Messenger serializer, decide these three things now.

  • On 8.1.0 to 8.1.10, update to 8.1.11. Until then, a serializer that throws from decode() loops at retry #1 on any poisoned message, and your failure transport will not tell you.
  • Return wrap() with the stamps if you want retries. A decorator around Serializer gets them from the inner serializer's own failure envelope. If you cannot recover the stamps, throw, and accept that the message goes to the failure transport on first sight, which on 8.1.11 is what throwing means.
  • Let the failure re-send itself. In encode(), pass a MessageDecodingFailedException message through untransformed and give the failure transport the same serializer as its source.

And if your Redis DSN has three path segments, check what name your workers are registered under.

Source Code: You can find the full implementation and follow the project's progress on GitHub: https://github.com/mattleads/messenger-decode-throw-repro

Let's Connect!

If you found this helpful or have questions about the implementation, I'd love to hear from you. Let's stay in touch and keep the conversation going across these platforms:

Top comments (0)