Symfony 8.2 is a huge release for the Messenger component. We already introduced the outbox and claim check options, the Messenger inbox, Messenger flows, cross-application messaging, signed transports, faster workers and the MongoDB transport. This article showcases the rest of its new features.

Sending Messages in Batches

Joppe De Cuyper Nicolas Grekas
Contributed by Joppe De Cuyper and Nicolas Grekas in #66627

Dispatching many messages in a loop makes one request to the transport per message, which is slow when importing a file or notifying thousands of users. Symfony 8.2 adds a BatchDispatcher that sends them in batches:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Symfony\Component\Messenger\BatchDispatcher;
use Symfony\Component\Messenger\MessageBusInterface;

$dispatcher = new BatchDispatcher($bus);

$envelopes = $dispatcher->dispatch([
    new OrderCreated(1),
    new OrderCreated(2),
    // ...
]);

// or, when the code that dispatches the messages expects a bus
$envelopes = $dispatcher->run(
    fn (MessageBusInterface $bus) => $importer->import($file, $bus)
);

Each message still goes through all the middleware of the bus, but messages are sent only after all of them went through it. If any of them fails before that, no message is sent.

The Amazon SQS, AMQP, Doctrine, Redis, MongoDB and AMPHP SQL transports (and the transactional outbox) send these batches with as few requests as possible. In local benchmarks, sending 2,500 messages to Redis took 67 ms instead of 1,038 ms. The other transports send the messages one by one.

Adding Middleware with an Attribute

Nicolas Grekas
Contributed by Nicolas Grekas in #66590

Until now, the only way to add a middleware to a bus was to list it in the configuration of that bus. In Symfony 8.2, a middleware can add itself to a bus with the new #[AsMessageMiddleware] attribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/Messenger/AuditMiddleware.php
namespace App\Messenger;

use Symfony\Component\Messenger\Attribute\AsMessageMiddleware;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;

#[AsMessageMiddleware(bus: 'command.bus', after: 'validation')]
final class AuditMiddleware implements MiddlewareInterface
{
    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        // ...

        return $stack->next()->handle($envelope, $stack);
    }
}

The bus argument is mandatory (use '*' to add the middleware to all buses). The before and after arguments accept the names used in the configuration (validation, send_message, etc.), service IDs or class names. This also lets bundles add their own middleware without requiring you to configure them.

Restricting the Messages of a Bus

Nicolas Grekas
Contributed by Nicolas Grekas in #66586

In applications that use multiple buses for commands, queries and events, nothing stops you from dispatching a query on the command bus. Also, many of them wrap each bus only to get the original exception of the handler instead of a HandlerFailedException. Symfony 8.2 adds two bus options that solve both problems:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# config/packages/messenger.yaml
framework:
    messenger:
        default_bus: event.bus
        buses:
            command.bus:
                messages: App\Message\CommandInterface
                unwrap_exceptions: true
            query.bus:
                messages: App\Message\QueryInterface
                unwrap_exceptions: true
            # Symfony dispatches its own messages on the default bus (e.g. the
            # emails sent by the Mailer), so don't restrict its messages
            event.bus: ~

The messages option lists the classes or interfaces that your application can dispatch on the bus; any other message throws an exception. The unwrap_exceptions option throws the exception of the failing handler instead of the HandlerFailedException that wraps it. Both options apply only to the messages dispatched by your application, not to the ones received by workers.

Choosing the Transport in the Handler

Nicolas Grekas
Contributed by Nicolas Grekas in #65898

When two handlers of the same message must run on different transports, you have to route the message to both transports and set the fromTransport option in each handler. Both definitions must match, and a typo in fromTransport means that the handler never runs, without any error. In Symfony 8.2, the handler can define all this with the new transport option:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(transport: 'notifications')]
final class NotifyCustomer
{
    public function __invoke(OrderWasPlaced $event): void
    {
        // ...
    }
}

#[AsMessageHandler(transport: 'projections')]
final class UpdateOrdersList
{
    public function __invoke(OrderWasPlaced $event): void
    {
        // ...
    }
}

The OrderWasPlaced message is sent to both transports and each handler only handles the copy received from its own transport, so you don't need to add anything to the routing configuration. A wrong transport name now fails when building the container.

Events Before and After Each Handler

Benjamin Morel
Contributed by Benjamin Morel in #52425

The existing worker events (WorkerMessageHandledEvent, WorkerMessageFailedEvent, etc.) are dispatched once per message and only for messages consumed by a worker. Symfony 8.2 dispatches three new events around each handler call: HandlerStartingEvent, HandlerSuccessEvent and HandlerFailureEvent. They are also dispatched for messages handled synchronously and they give you the envelope and the descriptor of the handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Messenger\Event\HandlerFailureEvent;

final class HandlerFailureListener
{
    // ...

    #[AsEventListener]
    public function __invoke(HandlerFailureEvent $event): void
    {
        $this->logger->error('The "{handler}" handler failed.', [
            'handler' => $event->handlerDescriptor->getName(),
            'message' => $event->envelope->getMessage()::class,
            'exception' => $event->exception,
        ]);
    }
}

Renaming Messages Safely

Yonel Ceruto
Contributed by Yonel Ceruto in #64952

The serializedTypeName option of #[AsMessage] replaces the class name of the message with a stable name in the serialized messages. However, changing that name later (or renaming a message class that didn't have one) was risky: the messages already waiting in the transports could no longer be decoded. The new serializedTypeNameAliases option lists other names that are also decoded as this message:

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace App\Message;

use Symfony\Component\Messenger\Attribute\AsMessage;

#[AsMessage(
    serializedTypeName: 'order.created',
    // the names used by this message before it was renamed
    serializedTypeNameAliases: ['order.new', 'App\Message\NewOrder'],
)]
class OrderCreated
{
    // ...
}

Aliases are only used when decoding (new messages are always sent with the main name), so in a rolling deployment you must update the consumers before the producers.

Pausing Transports After Failures

HypeMC
Contributed by HypeMC in #66964

When a handler depends on a service that is down or rate limited (a database, an API returning 429 responses, etc.), the worker keeps fetching messages that are going to fail. An outage of a few minutes can move a whole queue to the failure transport, while making things worse for the service that is struggling.

Symfony 8.2 adds a cooldown_strategy option to transports. After several messages received from a transport fail in a row, the worker stops fetching from it for a while and keeps consuming its other transports:

1
2
3
4
5
6
7
8
9
10
11
# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            api:
                dsn: '%env(API_TRANSPORT_DSN)%'
                cooldown_strategy:
                    failure_threshold: 5 # failures in a row before the first cooldown
                    delay: 1000          # duration of the first cooldown, in ms
                    multiplier: 2        # each further failure in a row doubles it
                    max_delay: 60000

In this example, five failures in a row pause the transport for 1 second, and each further failure in a row pauses it again for 2 seconds, 4 seconds, etc. up to 60 seconds. A message handled successfully resets the count. Errors when fetching messages (e.g. while the broker restarts) count as failures too, and each worker counts its own failures.

New Options to Consume Messages

Peter van der Wal Zoran Shefot Bogoevski
Contributed by Peter van der Wal and Zoran Shefot Bogoevski in #57757 and #66870

The --all option of messenger:consume consumes all the transports of the application, but you couldn't control in which order. Symfony 8.2 adds a priority option to transports (higher values are consumed first; the default is 0):

1
2
3
4
5
6
7
8
9
# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            important:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options: { queue_name: important }
                priority: 10
            async: '%env(MESSENGER_TRANSPORT_DSN)%'

In addition, the new --stop-when-empty option makes the worker handle the messages that are in the transports and exit, instead of waiting for new ones (delayed messages stay in the transports). It's useful in deployments, cron jobs and CI:

1
$ php bin/console messenger:consume async --stop-when-empty

Stopping the Workers of Some Transports

Nicolas Grekas
Contributed by Nicolas Grekas in #66689

The messenger:stop-workers command stops all the workers of the application, so your process manager can restart them. In Symfony 8.2, you can pass the names of some transports to stop only the workers that consume them:

1
$ php bin/console messenger:stop-workers scheduler_default

The new WorkerRestarter service does the same from your code. For example, when a Scheduler schedule is built from data stored in the database, the workers that are already running don't see the changes made in that data. Stop them after saving the changes, so the new workers load the updated schedule:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Messenger\WorkerRestarter;

class TaskManager
{
    public function __construct(
        private WorkerRestarter $restartWorkers,
    ) {
    }

    public function save(Task $task): void
    {
        // ... save the task that the schedule provider reads

        ($this->restartWorkers)('scheduler_default');
    }
}

Inspecting Pending and Failed Messages

Payene Denis KOMBATE Nicolas Grekas
Contributed by Payene Denis KOMBATE and Nicolas Grekas in #64829 and #65096

The messenger:failed:show command lets you look at the messages of the failure transport, but there was no way to see the messages waiting in the other transports. The new messenger:show command does that:

1
2
3
4
5
6
7
8
# lists the pending messages (their ID and class)
$ php bin/console messenger:show async

# shows the details of a message (add -vv to see its contents)
$ php bin/console messenger:show async 1234

# counts the pending messages of each class
$ php bin/console messenger:show async --stats

It works with the transports that can list their messages, such as Doctrine.

The commands that manage failed messages are improved too, so after an incident you can retry or remove only some of them without passing their IDs one by one. The messenger:failed:retry, messenger:failed:remove and messenger:failed:show commands add the --failed-after and --failed-before options, and messenger:failed:retry also adds the --class-filter option that the other two already had:

1
2
3
4
5
6
7
# the mail provider rate-limited the application between 08:00 and 09:30
$ php bin/console messenger:failed:retry --force \
    --class-filter='App\Message\SendEmail' \
    --failed-after='2026-11-20 08:00' --failed-before='2026-11-20 09:30'

# relative dates work too
$ php bin/console messenger:failed:remove --failed-after='-1 hour'

Amazon SQS Fair Queues

Grzegorz Kuźnik
Contributed by Grzegorz Kuźnik in #62080

In multi-tenant applications, a tenant that sends lots of messages delays the messages of everybody else. Amazon SQS solves this with fair queues: messages of standard queues can include a group ID and SQS balances the delivery across those groups, without having to convert them into FIFO queues.

In Symfony 8.2, add the new AmazonSqsFairQueueStamp to set that group:

1
2
3
4
5
use Symfony\Component\Messenger\Bridge\AmazonSqs\Transport\AmazonSqsFairQueueStamp;

$bus->dispatch(new GenerateReport($reportId), [
    new AmazonSqsFairQueueStamp('tenant-'.$tenant->getId()),
]);

AMPHP SQL Transport

Fabien Potencier
Contributed by Fabien Potencier in #64892

The Doctrine transport runs blocking queries. That's fine in most applications, but it stalls the whole process when it runs on an event loop. Symfony 8.2 adds a transport that stores the messages in SQLite, MySQL or PostgreSQL using the non-blocking drivers of AMPHP. First, install it together with the driver of your database:

1
2
# use "amphp/mysql" for MySQL and "fabpot/amphp-sqlite3" for SQLite
$ composer require symfony/amp-sql-messenger amphp/postgres

Then, use one of its DSNs in your transport:

1
2
3
4
# .env
MESSENGER_TRANSPORT_DSN=amp-postgres://user:password@127.0.0.1/app
# MESSENGER_TRANSPORT_DSN=amp-mysql://user:password@127.0.0.1/app
# MESSENGER_TRANSPORT_DSN=amp-sqlite:///var/messenger.db

The schema of its table is different from the one of the Doctrine transport, so they can't share a table.

Published in #Living on the edge