# How to write and run a Magento 2 queue consumer in Adobe Commerce

**By Oleg Snegov.** Read time 18 minutes. Published Thursday, May 22, 2025.

**Tags:** Message Queues, Adobe Commerce, Magento, Mage-OS, RabbitMQ, Cron

---

A Magento 2 queue consumer needs four XML files in your module's `etc` directory (`communication.xml`, `queue_topology.xml`, `queue_publisher.xml` and `queue_consumer.xml`), a handler class, and a `publish()` call that puts messages on the queue. You run it with `bin/magento queue:consumers:start <consumer>`, and in production the `consumers_runner` cron job starts it every minute, controlled by `cron_consumers_runner` in `app/etc/env.php` (on Adobe Commerce Cloud, by the `CRON_CONSUMERS_RUNNER` variable, which is off by default). The framework is the same on Adobe Commerce, Magento Open Source and Mage-OS, 2.4.4 through 2.4.9.

---

## Should I use a queue or a cron job?

| | Queue | Cron job |
|---|---|---|
| Starts when | A message is published | The schedule says so |
| Good for | Work triggered by an event: an order to export, a stock change to apply | Work tied to the clock: a nightly feed, a cleanup |
| Who waits | Nobody: `publish()` returns right away | Nobody, but the work waits for the next run |
| Spreading the load | More consumer processes (`multiple_processes`, 2.4.4 and later) on RabbitMQ or ActiveMQ Artemis | One run of a job at a time |
| When it fails | The message is marked failed (MySQL) or dropped (RabbitMQ); retrying is code you write | The run fails and the next one starts fresh |

Use a queue for event-driven work that shouldn't happen inside the request. Use cron for work that belongs to the clock. They aren't rivals — cron is what starts your consumers out of the box.

---

## What XML files do I need for a Magento 2 queue?

Four files in your module's `etc` directory:

- `communication.xml` — declares the topic and the type of message it carries.
- `queue_topology.xml` — binds the topic to a queue through an exchange.
- `queue_publisher.xml` — lets code publish to the topic.
- `queue_consumer.xml` — names the consumer, its queue and its handler.

The examples use an order export to an ERP, topic `vendor.erp.order.export`.

### communication.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Communication/etc/communication.xsd">
    <topic name="vendor.erp.order.export" request="string"/>
</config>
```

The topic name is dot-separated and has to be unique. `request="string"` means each message is a string; send JSON in it.

### queue_topology.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/topology.xsd">
    <exchange name="magento" type="topic">
        <binding id="vendorErpOrderExport"
                 topic="vendor.erp.order.export"
                 destinationType="queue"
                 destination="vendor.erp.order.export"/>
    </exchange>
</config>
```

### queue_publisher.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/publisher.xsd">
    <publisher topic="vendor.erp.order.export"/>
</config>
```

### queue_consumer.xml

```xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/consumer.xsd">
    <consumer name="vendor.erp.order.export"
              queue="vendor.erp.order.export"
              handler="Vendor\Erp\Model\Queue\OrderExportConsumer::process"
              maxMessages="1000"/>
</config>
```

`maxMessages` is this consumer's own limit on how many messages one process handles before it exits. `consumerInstance` defaults to `Magento\Framework\MessageQueue\Consumer`.

### Which connection does the queue use?

None of the files above sets `connection`, and that's deliberate. From 2.4.5, Commerce uses `queue/default_connection` in `env.php` if set, otherwise RabbitMQ if configured, otherwise MySQL. Setting `queue/default_connection` yourself takes the guessing out of it.

On 2.4.4, set it explicitly: `connection="db"` (MySQL) or `connection="amqp"` (RabbitMQ).

After adding or changing these files, run `bin/magento setup:upgrade`.

---

## How do I write the consumer class?

```php
<?php
declare(strict_types=1);

namespace Vendor\Erp\Model\Queue;

use Vendor\Erp\Model\OrderExporter;

class OrderExportConsumer
{
    public function __construct(
        private readonly OrderExporter $exporter
    ) {
    }

    public function process(string $message): void
    {
        $data = json_decode($message, true, 512, JSON_THROW_ON_ERROR);
        $orderId = (int) $data['order_id'];

        // Safe to see the same message twice.
        if ($this->exporter->isExported($orderId)) {
            return;
        }

        $this->exporter->export($orderId);
    }
}
```

**Two things decide whether this survives production:**

**What happens when `process()` throws an exception.** With the default consumer class, the message is rejected and not put back on the queue. On MySQL it's marked as an error (status `6` in `queue_message_status`). On RabbitMQ the broker drops it, unless you've given the queue a dead-letter exchange. If a failure is worth retrying, build that yourself.

**Why the handler checks first.** A message can still arrive twice. On RabbitMQ, a message that was delivered but not acknowledged goes back on the queue when the consumer's connection drops. On MySQL, a message left "in progress" by a killed consumer is put back for retry by the `mysqlmq_clean_messages` cron job. Make the second run a no-op.

---

## How do I publish messages to the queue?

Inject `Magento\Framework\MessageQueue\PublisherInterface`:

```php
<?php
declare(strict_types=1);

namespace Vendor\Erp\Model;

use Magento\Framework\MessageQueue\PublisherInterface;

class OrderExportQueue
{
    public function __construct(
        private readonly PublisherInterface $publisher
    ) {
    }

    public function add(int $orderId): void
    {
        $this->publisher->publish(
            'vendor.erp.order.export',
            json_encode(['order_id' => $orderId], JSON_THROW_ON_ERROR)
        );
    }
}
```

Publish once the data the consumer needs is saved, so it never goes looking for an order that isn't there yet.

---

## How do I run a Magento 2 queue consumer?

```bash
# Every consumer Commerce knows about, core ones included
bin/magento queue:consumers:list

# Start one
bin/magento queue:consumers:start vendor.erp.order.export --max-messages=1000 --single-thread
```

Useful options:

- `--max-messages=<n>` — exits after that many messages.
- `--single-thread` — takes a lock so a second copy can't start.
- `--area-code` — sets the area (`global` by default) for handlers that need `adminhtml` or `frontend`.
- `--batch-size` — for batch consumers only.
- `--multi-process` — Adobe says parallel processes only work when `multiple_processes` is configured in `env.php`.

---

## How do I run queue consumers in production?

By default, cron does it. The `consumers_runner` job (cron group `consumers`) runs every minute and starts each consumer that isn't already running. Adobe's defaults: the job is on, it runs all consumers, each processes 10,000 messages and exits.

Control it in `app/etc/env.php`:

```php
'cron_consumers_runner' => [
    'cron_run' => true,
    'max_messages' => 10000,
    'consumers' => [],
    'multiple_processes' => [
        'vendor.erp.order.export' => 2,
    ],
],
'queue' => [
    'consumers_wait_for_messages' => 1,
    'only_spawn_when_message_available' => 1,
],
```

- `cron_run` — turns the `consumers_runner` job on or off (default `true`).
- `max_messages` — how many messages each consumer handles before exiting (default `10000`). On 2.4.9+, a consumer's own `maxMessages` wins.
- `consumers` — allow-list; empty array runs all.
- `multiple_processes` (2.4.4+) — run more than one process per consumer; use with RabbitMQ or ActiveMQ Artemis.
- `consumers_wait_for_messages` — `1` waits for more messages (recommended for constant flow); `0` exits when queue is empty (smaller sites).
- `only_spawn_when_message_available` — cron doesn't start a consumer when its queue is empty.

**Never set `max_messages` to `0` in production** — the process never exits and PHP memory grows until something falls over.

### What changes on Adobe Commerce Cloud?

On Cloud, set options in `.magento.env.yaml`:

- `CRON_CONSUMERS_RUNNER` defaults to `cron_run: false` and `max_messages: 1000`. Until you turn it on, cron doesn't start your consumers.
- `CONSUMERS_WAIT_FOR_MAX_MESSAGES` defaults to `false`.

```yaml
stage:
  deploy:
    CRON_CONSUMERS_RUNNER:
      cron_run: true
      max_messages: 1000
      consumers: []
    CONSUMERS_WAIT_FOR_MAX_MESSAGES: false
```

### Should I use Supervisor instead of cron?

For a high-volume queue, Supervisor restarts a consumer the moment it exits, not up to a minute later.

```ini
[program:magento-consumer-erp-order-export]
command=/usr/bin/php /var/www/html/bin/magento queue:consumers:start vendor.erp.order.export --max-messages=1000 --single-thread
directory=/var/www/html
autostart=true
autorestart=true
user=www-data
numprocs=1
stopasgroup=true
killasgroup=true
stdout_logfile=/var/log/supervisor/magento-consumer-erp-order-export.log
```

Three things to line up:

- **Keep cron off that consumer.** Use `consumers` allow-list or turn off `cron_run` entirely.
- **Let it wait for messages.** Keep `consumers_wait_for_messages` at `1` for Supervisor-managed consumers.
- **Keep `--max-messages`.** It makes the process exit and restart with fresh memory.

### How do I restart consumers after a deploy?

```bash
bin/magento queue:consumers:restart
```

This leaves a "poison pill". The next time a consumer picks up a message, it sees the pill, puts the message back and exits, and cron or Supervisor starts it again on the new code.

---

## Should I use MySQL, RabbitMQ or ActiveMQ Artemis?

Out of the box, messages live in MySQL (`queue`, `queue_message`, `queue_message_status`). Adobe is clear this is a fallback: "This solution is not very scalable. External message brokers like RabbitMQ or Apache ActiveMQ Artemis should be used whenever possible for production environments." The bulk API requires RabbitMQ.

To connect RabbitMQ:

```bash
bin/magento setup:config:set --amqp-host="rabbitmq.internal" --amqp-port="5672" \
  --amqp-user="magento" --amqp-password="********" --amqp-virtualhost="/"
```

To connect ActiveMQ Artemis over STOMP (remove AMQP config from `env.php` first):

```bash
bin/magento setup:config:set --stomp-host="activemq.internal" --stomp-port="61613" \
  --stomp-user="magento" --stomp-password="********"
```

### Broker support by release (as of November 2026)

| Release line | RabbitMQ | ActiveMQ Artemis |
|---|---|---|
| 2.4.9 | 4.3 | 2 |
| 2.4.8 | 4.1; 4.3 at 2.4.8-p5 | 2, from p3 |
| 2.4.7 | 3.13; 4.1 from p5; 4.3 at p10 | 2, from p8 |
| 2.4.6 | 3.9 and 3.11 at release; 4.1 from p10; 4.3 at p15 | 2, from p13 |
| 2.4.5 | 3.9 at release; 4.1 from p12; 4.3 at p17 | 2, from p16 |
| 2.4.4 | 3.9; 3.13 added at p18 | Not listed |

RabbitMQ 4 requires moving from classic mirrored queues to quorum queues before upgrading the broker. In the 2.4.9 notes, Adobe recommends ActiveMQ Artemis as the long-term broker.

---

## Which core consumers does a B2B site need running?

| Consumer | Edition | What stalls when it isn't running |
|---|---|---|
| `async.operations.all` | All | Admin bulk actions set to run asynchronously, and async/bulk REST endpoints |
| `product_action_attribute.update` | All | Mass attribute updates from the product grid |
| `inventory.reservations.updateSalabilityStatus` | All | Salable quantity; should always be running if using Inventory Management |
| `sales.rule.update.coupon.usage` | All | Coupon usage counts (stops single-use coupons being used twice) |
| `placeOrderProcessor` | Adobe Commerce | Orders placed with asynchronous order placement |
| `sharedCatalogUpdatePrice` | Adobe Commerce with B2B | Shared catalog price changes |
| `negotiableQuotePriceUpdate` | Adobe Commerce with B2B | Prices on negotiable quotes |
| `purchaseorder.toorder`, `purchaseorder.validation` | Adobe Commerce with B2B | Purchase orders becoming orders and approval rules being checked |

---

## Why is my queue consumer not processing messages?

Check these failure modes in order:

**1. Cron isn't running, or isn't starting consumers.**

```sql
SELECT job_code, status, scheduled_at, executed_at, messages
FROM cron_schedule
WHERE job_code = 'consumers_runner'
ORDER BY scheduled_at DESC
LIMIT 5;
```

Check `cron_run` (on Cloud, `CRON_CONSUMERS_RUNNER` is off by default) and whether `consumers` is an allow-list that leaves yours out.

**2. The consumer is skipped for a missing connection.** If its connection isn't configured (e.g. `amqp` on a site with no RabbitMQ), cron skips it and logs `Consumer "<name>" skipped as required connection "<connection>" is not configured.`

**3. Messages failed and nobody noticed.** On MySQL:

```sql
SELECT q.name, s.status, COUNT(*) AS messages
FROM queue_message_status s
JOIN queue q ON q.id = s.queue_id
GROUP BY q.name, s.status;
```

Statuses: `2` new, `3` in progress, `4` complete, `5` retry required, `6` error, `7` to be deleted. A growing pile of `6` means your handler is throwing. Use `grep -r "Message has been rejected" var/log/` to find why.

**4. Messages stuck "in progress".** Usually a consumer killed mid-message. Commerce puts them back for retry once **Retry Messages In Progress After** has passed (1440 minutes by default; Stores > Settings > Configuration > Advanced > System > MySQL Message Queue Cleanup). Lower that setting if a day is too long — but keep it above the time your slowest message takes.

**5. A poison message.** A payload that causes a PHP error (e.g. `TypeError`, out of memory) rather than an exception kills the process entirely. On RabbitMQ the message goes back on the queue and takes down the next consumer too; on MySQL it sits "in progress" until retry, then does it again. Validate payloads before publishing, and turn errors you can catch into exceptions in the handler.

**6. Everything broke after the last deploy.** Stale code in a long-running consumer. Run `bin/magento queue:consumers:restart` and make it part of every deploy.

**7. Admin mass actions sit at pending.** Those run through `async.operations.all` and `product_action_attribute.update` — apply this same checklist.

---

## Which versions does this apply to?

Everything here works on Adobe Commerce, Magento Open Source and Mage-OS from 2.4.4 through 2.4.9, with these notes:

- `multiple_processes` needs 2.4.4 or later.
- Automatic connection choice needs 2.4.5 or later.
- RabbitMQ 4 needs 2.4.8, or the 2.4.5–2.4.7 patches listed in the table above.
- 2.4.9 changed how cron picks a consumer's message limit.
- Mage-OS 3.x and 4.0 are built on Magento Open Source 2.4.9; Mage-OS 2.x on 2.4.8.

Standard support for 2.4.6 ended on August 11, 2026; Adobe Commerce 2.4.6 has extended support until August 31, 2027. Adobe Commerce 2.4.4 and 2.4.5 are down to security-only fixes until May 31, 2027.

---

## Frequently asked questions

### How do I run a queue consumer in Magento 2?

`bin/magento queue:consumers:start <consumer-name>`, from the Commerce root as the file system owner. Add `--max-messages` so it exits after a batch, and `--single-thread` so only one copy runs. In production, let the `consumers_runner` cron job or a process manager start it for you.

### How do I see which queue consumers exist?

`bin/magento queue:consumers:list` lists every consumer Commerce knows about, core and custom. On Cloud, run it in the remote environment.

### How do I restart queue consumers?

`bin/magento queue:consumers:restart`. Consumers started with a message limit exit the next time they pick up a message, and cron or your process manager starts them again with the current code. Run it on every deploy.

### Why does my consumer never exit when I start it by hand?

With `--max-messages`, the consumer exits after that many messages, or as soon as the queue is empty if `consumers_wait_for_messages` is `0`.

### Does Magento send order emails through the message queue?

No. With **Asynchronous sending** turned on (Stores > Settings > Configuration > Sales > Sales Emails > General Settings), sales emails go out from cron jobs such as `sales_send_order_emails` instead of during checkout. If you want your own emails off the request path, publish them to a topic of your own and send them from a consumer.

### Do I need RabbitMQ for Magento 2 queues?

Not to start. The MySQL adapter works out of the box, and the XML above runs on it unchanged. For production volumes Adobe recommends RabbitMQ or ActiveMQ Artemis, and it requires RabbitMQ for the bulk REST endpoints.
