When a PHP application starts to grow, one of the first performance bottlenecks usually surfaces in the worst possible place: the user experience.
A registration that takes too long.
A checkout that stalls for several seconds.
An API that seems to “freeze” before sending a response.
In many cases, the problem isn’t PHP itself. The problem is executing too many tasks within a single HTTP request. And that problem has a clear solution.
The Problem: Blocking Tasks in the Request Cycle
Imagine a typical user registration flow:
- The user submits the form
- The application creates the user in the database
- A welcome email is sent
- A confirmation PDF is generated
- An external webhook is notified
- Finally, an
HTTP 200response is returned
The issue is that all these operations happen sequentially inside the same request:
Usuario espera...
├── Guardar usuario
├── Enviar email
├── Generar PDF
├── Llamar webhook
└── Respuesta HTTP
Even if each task takes “only” a few hundred milliseconds, total response time accumulates rapidly. And what’s worse: you depend on external systems. Slow SMTP servers, flaky third-party APIs, network timeouts… all of that directly degrades the response time experienced by the end user.
The Solution: Decouple Heavy Tasks from the HTTP Cycle
The modern approach consists of decoupling heavy tasks from the request lifecycle. Instead of executing everything immediately, the application:
- Persists the bare minimum necessary data
- Publishes a message to a queue
- Returns the HTTP response as quickly as possible
- Lets a background worker process the job asynchronously
HTTP Request
↓
Controller → dispatch()
↓
Cola / Transport
↓
Respuesta HTTP inmediata
(En paralelo)
Worker consume la cola
↓
Handler ejecuta la lógica
This pattern goes by several names—background jobs, message queues, asynchronous processing—but they all share the exact same core concept: the user shouldn’t have to wait while the server generates a PDF or communicates with an external API.
In the Symfony ecosystem, the standard component to implement this architecture is Symfony Messenger.
Core Concepts
Messenger is built on four fundamental concepts that are worth understanding before writing a single line of configuration.
Message
A message is a plain PHP object containing exclusively the data needed to perform a task. Nothing more.
// src/Message/SendWelcomeEmail.php
namespace App\Message;
final class SendWelcomeEmail
{
public function __construct(
public readonly int $userId,
) {}
}
An essential rule: messages should carry IDs and minimal data, never full Doctrine entities or injected services. Why? Because messages are serialized to be stored in the queue. Passing a full entity implies serializing the entire object graph, resulting in bloated, fragile messages that are hard to version. A simple $userId is enough: the handler will fetch fresh data from the database when it processes the job.
Message Bus
The bus receives the message and dispatches it according to your routing configuration.
$bus->dispatch(new SendWelcomeEmail($userId));
The controller dispatching this line doesn’t know where, when, or how the message will be processed. That decoupling is precisely what we want.
Message Handler
The handler contains the actual business logic. Symfony automatically discovers and maps it to the corresponding message using the #[AsMessageHandler] attribute and the argument type in __invoke.
// src/MessageHandler/SendWelcomeEmailHandler.php
namespace App\MessageHandler;
use App\Message\SendWelcomeEmail;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class SendWelcomeEmailHandler
{
public function __invoke(SendWelcomeEmail $message): void
{
// Aquí va la lógica: recuperar el usuario y enviar el email
}
}
Transport
The transport defines where messages are stored while waiting to be processed. This is the piece that decides whether execution is synchronous or asynchronous, and which queuing backend is used underneath.
Installation
composer require symfony/messenger
Configuring the Transport
Synchronous vs. Asynchronous Execution
By default, without configuring any transport routing, Messenger executes handlers immediately within the same HTTP request. This is handy for local development and debugging, but it does not eliminate blocking operations.
In asynchronous mode, the message is first persisted to the transport, and a separate worker consumes it later, completely independent of the original request.
Starting with Doctrine
To get started, Doctrine is often the best choice: it doesn’t require RabbitMQ, Redis, or any extra infrastructure. You only need the relational database you are already running.
# config/packages/messenger.yaml
framework:
messenger:
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
routing:
'App\Message\SendWelcomeEmail': async
MESSENGER_TRANSPORT_DSN=doctrine://default
Next, generate the database table where pending messages will be stored:
php bin/console messenger:setup-transports
This creates the messenger_messages table in your database. Every queued message will remain there until a worker consumes it.
Dispatching from a Controller
namespace App\Controller;
use App\Message\SendWelcomeEmail;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
final class RegisterController
{
public function __invoke(MessageBusInterface $bus): Response
{
$userId = 42;
$bus->dispatch(new SendWelcomeEmail($userId));
return new Response('Usuario registrado');
}
}
From the user’s perspective, the response is immediate. The email will be sent later in the background.
Running the Worker
The worker is a long-running process that consumes messages from the queue and invokes their handlers:
php bin/console messenger:consume async
In production, this command must run continuously. To ensure it restarts automatically upon failures or memory limits, you should use a process manager like Supervisor, systemd, or container orchestrators like Docker or Kubernetes.
Resilience and Failure Handling
Automatic Retries
One of Messenger’s greatest strengths is its built-in retry strategy. If a handler throws an unhandled exception—because the SMTP server timed out, an external API is down, or a transient network glitch occurred—Symfony can automatically retry the message with a configurable backoff interval.
This turns temporary failures into recoverable events instead of permanently lost jobs.
Failed Transport: Never Lose Critical Messages
What happens if a message fails permanently, even after all retries have been exhausted? Symfony allows you to route it to a designated dead-letter queue (failed transport):
framework:
messenger:
failure_transport: failed
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
failed: 'doctrine://default?queue_name=failed'
From there, you can inspect failed messages and retry them manually once the underlying problem is fixed:
php bin/console messenger:failed:show
php bin/console messenger:failed:retry
This prevents silent data loss. An async architecture that lacks failure handling is not production-ready.
Idempotency: The Crucial Detail
When working with retries, you must assume a message might be processed more than once. An email could be sent twice. An API might receive duplicate requests. A webhook payload could be processed redundantly.
Because of this, handlers should be designed to be idempotent whenever possible: running the same message twice must not corrupt state or trigger unwanted side effects.
This principle separates toy async setups from production-grade systems.
What Tasks Are Good Candidates?
Messenger is an ideal fit for:
- Sending emails and push notifications
- Generating PDFs or processing images
- Dispatching webhooks and third-party API calls
- Running batch data exports
- Syncing data with external platforms
As a rule of thumb, any task that depends on network I/O, takes significant processing time, or isn’t required to formulate an immediate response to the client belongs in a background queue.
What you shouldn’t move to a queue: critical pre-persistence validation, business rules that directly determine the HTTP response payload, or tasks so lightweight that the serialization and queuing overhead outweighs any benefits. The goal isn’t to “make everything async.” The goal is to decouple wisely.
Observability: What Nobody Considers Until It Breaks
Introducing background workers also introduces new failure modes. A classic scenario: the worker crashes in production at 3:00 AM, messages pile up silently in the queue, and nobody notices until an angry user asks why their confirmation email hasn’t arrived six hours later.
You should actively monitor:
- Workers that have stopped running or become unresponsive
- Queues growing indefinitely
- Accumulating failed messages
- Abnormal execution times
- Excessive retry spikes indicating systemic downstream issues
A silently stalled queue can turn into a serious operational incident very quickly.
Embracing Asynchronous Architecture
Symfony Messenger offers an elegant, battle-tested way to bring asynchronous processing to modern PHP applications. Its main benefit isn’t just raw performance gains—it is cleaner software architecture: clear separation of concerns, reduced coupling, and eliminating unnecessary delays from HTTP requests.
Best of all, you can start small with Doctrine without provisioning complex infrastructure on day one. When your traffic grows, migrating to Redis, RabbitMQ, or Amazon SQS won’t require modifying a single line of your domain handlers. That level of decoupling is what makes Messenger such a compelling tool in the Symfony ecosystem.