Learn Symfony · 10/12

Background Jobs with the Messenger Component

8 min read

Welcome to the world of background processing in Symfony! 🚀

When building web applications, speed is everything. Users expect instantaneous feedback. But what happens when your application needs to do heavy lifting—like generating a monthly PDF report, processing uploaded videos, or sending out thousands of newsletters? If you do this while the user is waiting, they will be stuck staring at a loading spinner.

The Symfony Messenger component is the industry-standard tool to solve this. It provides a message bus and queue system to handle tasks in the background, keeping your application lightning-fast.

Let's break down how to master this component step by step.


1. Why Async? The Motivation Behind Message Queues ⏱️

Definition

Asynchronous processing (Async) is a programming model where a task is executed independently of the main application flow. Instead of waiting for the task to finish, the system moves on to the next instruction immediately. A Message Queue is the underlying system that stores these pending tasks until they are ready to be processed.

The Problem

In a standard synchronous web request, PHP reads the code top-to-bottom. If a user registers on your site, and your code needs to:

  1. Save the user to the database (0.05 seconds)
  2. Generate a personalized welcome PDF (3 seconds)
  3. Send a welcome email via a third-party API (2 seconds)

The user has to wait over 5 seconds just to see the "Registration Successful" page. In the web world, 5 seconds is the digital equivalent of being put on hold with terrible elevator music for three hours.

The Solution

We use a Message Queue to handle tasks asynchronously. We instantly complete the fast tasks (saving the user), throw a "note" into a queue saying "Hey, please send an email to User #42 when you have time," and immediately return a success page to the user.

🍕 The Pizza Shop Simulation

Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly.

  • Synchronous Flow: A customer walks in and orders a Pepperoni pizza. You, the cashier, walk to the kitchen, make the dough, bake the pizza, box it, hand it to the customer, and only then turn to the next customer in line. The line goes out the door, and people are furious.
  • Asynchronous Flow (Queues): A customer orders. You write their order on a ticket (the Message), stick it on the kitchen rail (the Queue/Transport), and immediately say "That will be ready soon!" You instantly take the next customer's order. Meanwhile, your chefs in the back (the Workers) pull tickets off the rail and make the pizzas in the background.

By decoupling the "taking the order" from "making the pizza," your system scales infinitely better.


2. Creating Messages and Message Handlers ✉️

Before doing anything, let's install the Messenger component. Strictly using the latest Symfony standard, run this in your terminal:

bash
composer require symfony/messenger

Definition

  • Message: A plain PHP class (Data Transfer Object) that holds only the data needed to perform a specific task.
  • Message Handler: A PHP class containing the business logic. It listens for a specific Message and executes the work.

The Problem

How do we package a task so that a background worker knows exactly what to do and what data to use?

The Solution

We create a simple Message class to hold the data and a Handler class to execute the logic. The Messenger component connects the two.

Step 1: The Message

A Message should be extremely simple. Industry Standard Tip: Never pass full database objects (like Doctrine Entities) into a message. By the time the worker processes the message (which could be hours later if the queue is busy), the entity data might have changed in the database. Instead, pass the Entity ID.

php
// src/Message/SendWelcomeEmail.php
namespace App\Message;

class SendWelcomeEmail
{
    public function __construct(
        private int $userId,
    ) {}

    public function getUserId(): int
    {
        return $this->userId;
    }
}

Step 2: The Handler

Next, we create the Handler. We tell Symfony this class is a handler by using the #[AsMessageHandler] attribute. Symfony automatically looks at the type hint of the __invoke method (SendWelcomeEmail $message) to know which message this handler belongs to.

php
// src/MessageHandler/SendWelcomeEmailHandler.php
namespace App\MessageHandler;

use App\Message\SendWelcomeEmail;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
// ... other imports like MailerInterface, UserRepository

#[AsMessageHandler]
class SendWelcomeEmailHandler
{
    public function __invoke(SendWelcomeEmail $message)
    {
        $userId = $message->getUserId();
        
        // 1. Fetch the fresh user from the database using $userId
        // 2. Build the email
        // 3. Send the email via Mailer
        
        // If this takes 5 seconds, the user won't feel it!
    }
}

Step 3: Dispatching the Message

Anywhere in your code (like a Controller), you can dispatch the message into the bus:

php
use App\Message\SendWelcomeEmail;
use Symfony\Component\Messenger\MessageBusInterface;

public function register(MessageBusInterface $bus)
{
    // ... logic to save user to database (assume user ID is 42)
    
    // Toss the ticket onto the rail!
    $bus->dispatch(new SendWelcomeEmail(42));
    
    return $this->render('success.html.twig');
}

3. Configuring Transports: Routing Messages to RabbitMQ or Redis 🛤️

Definition

  • Transport: The physical storage system (database, Redis, RabbitMQ, Amazon SQS) where messages wait in a queue.
  • Routing: The configuration rules telling Symfony which messages belong to which transport.

The Problem

By default, if you just run the code above, Symfony will execute the handler synchronously during the web request. Why? Because we haven't told Symfony where to store the queue! It defaults to running it immediately in memory.

The Solution

We define a transport and route our message to it inside config/packages/messenger.yaml.

yaml
# config/packages/messenger.yaml
framework:
    messenger:
        # 1. Define where the queues actually live
        transports:
            # We name this transport "async"
            async: '%env(MESSENGER_TRANSPORT_DSN)%'

        # 2. Tell Symfony which messages go to which transport
        routing:
            'App\Message\SendWelcomeEmail': async

Next, open your .env file to set the MESSENGER_TRANSPORT_DSN.

Industry Practices for Transports:

  • Doctrine (Database): MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=true
    • Pros: Zero extra infrastructure. Uses your existing MySQL/PostgreSQL database. Perfect for getting started or low-traffic apps.
  • Redis: MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
    • Pros: Extremely fast, in-memory. Great for high throughput.
  • RabbitMQ (AMQP): MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
    • Pros: The absolute industry standard for enterprise message brokering. Highly durable with advanced routing capabilities.

(Fun fact: As of Symfony 7.2, you can actually skip the YAML routing entirely and just add #[AsMessage('async')] directly above your SendWelcomeEmail class!)


4. Running Workers and Handling Failed Messages 👷‍♂️

Definition

A Worker is a continuously running PHP script operating in the command line interface (CLI). It constantly monitors the Transport, picks up new messages, and feeds them to your Handlers.

The Problem

You routed your messages to Redis. You clicked "Register" on your website. The page loaded instantly! 🎉 ...But the email never arrived.
Why? Because writing a ticket and putting it on the rail doesn't magically bake the pizza. You need to hire a chef.

The Solution

Start a worker to consume the messages from the transport.

Open your terminal and run:

bash
php bin/console messenger:consume async -vv

(The -vv flag is for verbose output, which is highly recommended so you can see the worker picking up and processing messages in real-time).

The terminal will hang and say [OK] Consuming messages from transports "async". It is now waiting. If you trigger the controller again, you will see the worker instantly grab the message and execute the handler!

Dealing with Failure (The Burnt Pizza) 💥

What happens if the third-party email API goes down? The worker will try to process the message, throw an Exception, and the message will fail.

By default, Symfony Messenger is smart. If a message fails, it will retry it 3 times (with a delay between each attempt, just in case it was a temporary network glitch).

If it fails all retries, the message is permanently deleted... unless you configure a Failure Transport (a Dead Letter Queue).

Update your messenger.yaml:

yaml
framework:
    messenger:
        # Tell Symfony where to send completely failed messages
        failure_transport: failed

        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
            # Define the failure transport (usually the database for easy viewing)
            failed: 'doctrine://default?queue_name=failed'

Now, if a message repeatedly fails, it is safely stored in the failed queue. You can inspect and retry them manually once you fix the bug or the API comes back online!

Lifesaver CLI Commands:

  • View failed messages: php bin/console messenger:failed:show
  • Retry failed messages: php bin/console messenger:failed:retry
  • Delete a failed message: php bin/console messenger:failed:remove

💡 Industry Standard: Supervisor

Running messenger:consume in your local terminal is fine, but in production, if the server restarts or the worker crashes due to a memory limit, your queues will stop processing.

In real-world applications, DevOps engineers use a process monitor like Supervisor or Systemd to run php bin/console messenger:consume. These tools run the worker in the background forever and automatically restart it if it ever fails.

Additionally, PHP is not designed to run forever without leaking memory. A standard production flag looks like this:

bash
php bin/console messenger:consume async --memory-limit=128M

When the worker hits 128MB of memory, it gracefully kills itself, and Supervisor instantly starts a fresh, clean worker in its place.


Further Reading & Official Documentation

To dive deeper into the under-the-hood mechanics or explore advanced middleware and CQRS patterns, check out the official resources:

Challenge

Symfony Messenger Configuration Challenge

Your task is to implement an asynchronous message processing system for handling new user registrations in a Symfony application. You will need to create a message class, a handler for that message, and provide the YAML configuration to route it through an asynchronous transport with failure handling.

Requirements:

  1. Create the Message Class:

    • In a file conceptually located at src/Message/ProcessNewUserRegistration.php, define a final class named ProcessNewUserRegistration.
    • This class must act as a Data Transfer Object (DTO) and should contain a single public integer property, userId.
    • Implement a constructor that accepts the userId and assigns it to the property.
  2. Create the Message Handler:

    • In a file conceptually located at src/MessageHandler/ProcessNewUserRegistrationHandler.php, define a final class named ProcessNewUserRegistrationHandler.
    • This class must be designated as a message handler for the ProcessNewUserRegistration message using the appropriate PHP attribute.
    • Implement an __invoke method that takes an instance of ProcessNewUserRegistration as its only argument. The body of the method can be left empty.
  3. Configure the Messenger Component:

    • In a file conceptually located at config/packages/messenger.yaml, configure the Symfony Messenger component.
    • Define a transport named async_users. This transport should use the Doctrine DSN (doctrine://default).
    • Define a failure transport named failed_users, which also uses the Doctrine DSN (doctrine://default).
    • Configure the async_users transport to use failed_users as its failure transport.
    • Set up routing so that any message of type App\Message\ProcessNewUserRegistration is sent to the async_users transport.

Expected result

Your final code should consist of three parts: a PHP message class, a PHP message handler class, and a YAML configuration block.

  1. ProcessNewUserRegistration.php:

    • A final class named ProcessNewUserRegistration.
    • A public constructor __construct(public readonly int $userId) or an equivalent implementation that initializes a public int $userId property.
  2. ProcessNewUserRegistrationHandler.php:

    • A final class named ProcessNewUserRegistrationHandler.
    • The class must be decorated with the #[AsMessageHandler] attribute.
    • It must contain a public method __invoke(ProcessNewUserRegistration $message).
  3. messenger.yaml:

    • Under the framework.messenger key, there should be a transports key.
    • The transports section must define async_users with a dsn of doctrine://default and a failure_transport key pointing to failed_users.
    • It must also define failed_users with a dsn of doctrine://default.
    • There should be a routing key that maps the 'App\Message\ProcessNewUserRegistration' class to the async_users transport.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.