How to write and run a Magento 2 queue consumer in Adobe Commerce
Home / Insights / How to write and run a Magento 2 queue consumer in Adobe Commerce
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.
A queue keeps a slow step from holding up everything before it. On one publisher's Magento Open Source site, the order API we built saves each incoming marketplace order and queues it, then places it as a Magento order within seconds, checking stock first. Orders that fail a check wait on their own admin screen, where the team can send them through again (the case study). The pieces below are how that kind of thing is built, including the production parts most tutorials skip.
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: a customer clicks "place order" while your ERP is having a slow afternoon, and the order export can wait two minutes but the customer can't. Use cron for work that belongs to the clock.
They aren't rivals, either. Out of the box, cron is what starts your consumers. Both need an owner: on one distributor's site, a production health check found 10 cron jobs doing nothing for the site, and six feed jobs running every minute for a payment service it had never signed up for (that case study). If the queue is part of an ERP integration, our ERP integration readiness checklist covers the decisions around it.
What XML files do I need for a Magento 2 queue?
Four files in your module's etc directory:
communication.xmldeclares the topic and the type of message it carries.queue_topology.xmlbinds the topic to a queue through an exchange.queue_publisher.xmllets code publish to the topic.queue_consumer.xmlnames the consumer, its queue and its handler.
The examples use an order export to an ERP, topic vendor.erp.order.export.
communication.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. You can also declare a handler here, but naming it on the consumer is enough.
queue_topology.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 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 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, which keeps memory in check. Cron uses it when it starts the consumer (more on that below); when you start a consumer by hand, --max-messages sets the limit instead. consumerInstance defaults to Magento\Framework\MessageQueue\Consumer, so you only set it for a batch or custom consumer.
Which connection does the queue use?
None of the files above sets connection, and that's deliberate. Adobe's configuration reference (opens in a new tab) says that when it's left out, the connection is resolved automatically, and the default exchange is magento. From 2.4.5, Commerce uses queue/default_connection in env.php if you set one, otherwise RabbitMQ if env.php configures it, otherwise MySQL; the releases that support ActiveMQ Artemis also pick it when it's configured. Magento's own modules have been written this way since 2.4.5, so the same module runs on whichever broker the site has. 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) on the exchange, the publisher's connection element and the consumer. The older style, with an exchange named magento-db for MySQL, still works on every version.
After adding or changing these files, run bin/magento setup:upgrade. That's when Commerce creates the queue: rows in the queue table for MySQL, or the exchange, queue and binding on RabbitMQ.
How do I write the consumer class?
<?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) and Commerce logs Message has been rejected: followed by your exception's message. On RabbitMQ the broker drops it, unless you've given the queue a dead-letter exchange. So throwing records the failure; it doesn't retry it. If a failure is worth retrying, build that yourself: catch it, and republish the message or park it in a table of your own with a resend action, like the marketplace orders in the case study above. A PHP error such as a TypeError is worse, because the consumer doesn't catch it at all; see poison messages in the troubleshooting section.
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 consumer that was killed halfway is put back for retry by the mysqlmq_clean_messages cron job once Retry Messages In Progress After has passed (1440 minutes, 24 hours, by default). Make the second run a no-op.
How do I publish messages to the queue?
Inject Magento\Framework\MessageQueue\PublisherInterface:
<?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)
);
}
}
Publishing is fast, which is the point: the slow work happens later, in the consumer. 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?
From the Commerce root, as the file system owner:
# 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
The options worth knowing:
--max-messages=<n>makes the process exit after that many messages.--single-threadtakes a lock so a second copy of the same consumer can't start. A second copy printsConsumer with the same name is runningand exits.--area-codesets the area (globalby default) for handlers that needadminhtmlorfrontend.--batch-sizeis for batch consumers only.--multi-processis listed, but Adobe says parallel processes only work when you configuremultiple_processesinenv.php; on its own the option runs a single thread.
That's fine on your machine. Production needs consumers running all the time, which is where most queue problems actually live.
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, with a lock and a message limit. Adobe's defaults: the job is on, it runs all consumers, and each one processes 10,000 messages and then exits, so the next cron run starts a fresh process. That exit and restart is deliberate: it keeps long-running PHP processes from piling up memory.
You control it in app/etc/env.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_runturns theconsumers_runnerjob on or off (defaulttrue).max_messagesis how many messages each consumer handles before it exits (default10000). On 2.4.8 and earlier, latest patches included, cron uses the smaller of this and the consumer's ownmaxMessages. From 2.4.9, a consumer's ownmaxMessageswins, and Commerce logs a warning when it's higher than this value.consumersis an allow-list. An empty array runs all of them; listing names runs only those.multiple_processes(2.4.4 and later) runs more than one process for a consumer. Adobe advises against several consumers on a MySQL queue, so use it with RabbitMQ or ActiveMQ Artemis.consumers_wait_for_messagesdecides what a consumer does when the queue runs dry beforemax_messages.1(the default) waits for more messages, which Adobe recommends for sites with a constant flow.0exits as soon as the queue is empty, which Adobe recommends for smaller sites without a constant flow.only_spawn_when_message_available(default1) means cron doesn't start a consumer at all when its queue is empty. A consumer can override it withonlySpawnWhenMessageAvailableinqueue_consumer.xml.
Never set max_messages to 0 in production. Adobe allows it but doesn't recommend it: 0 means the process never exits, and PHP memory grows until something falls over. Finite batches plus an automatic restart is the healthy pattern.
What changes on Adobe Commerce Cloud?
On Cloud, env.php is written at deploy time, so you set the same things in .magento.env.yaml. Read the defaults in Adobe's deploy variables reference (opens in a new tab) carefully, because they aren't the on-premises ones:
CRON_CONSUMERS_RUNNERdefaults tocron_run: falseandmax_messages: 1000. Until you turn it on, cron doesn't start your consumers.CONSUMERS_WAIT_FOR_MAX_MESSAGESdefaults tofalse: consumers process what's there and exit, whatevermax_messagessays. Adobe's warning: if you run consumers as workers instead of from cron, set it totrue.- The deploy overwrites the matching
env.phpsettings unless you use_merge.
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, a process manager such as Supervisor restarts a consumer the moment it exits, not up to a minute later. Adobe mentions Supervisor as an option alongside cron.
[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 when you do:
- Keep cron off that consumer.
cron_runis one switch for every consumer, so either turn it off and run everything you need under Supervisor, or keep cron and list inconsumersonly the ones cron should start.--single-threadstops the two from running the same consumer at once, but it's cleaner if only one of them owns it. - Let it wait for messages. With
consumers_wait_for_messagesat0, a consumer on an empty queue exits at once, and Supervisor either restarts it in a tight loop or, after a few quick exits, gives up on it. Keep it at1for consumers Supervisor manages (on Cloud, that'sCONSUMERS_WAIT_FOR_MAX_MESSAGES: true). - Keep
--max-messages. It's what makes the process exit and restart with fresh memory.
How do I restart consumers after a deploy?
A consumer is a long-running PHP process that holds the old code in memory. Until it restarts, it handles new messages with pre-deploy code, which produces some of the strangest bugs you'll chase. Add this to your deploy:
bin/magento queue:consumers:restart
It leaves what Commerce calls a poison pill. The next time a consumer started with a message limit picks up a message (every consumer cron starts, and the Supervisor one above), it sees the pill, puts the message back and exits, and cron or Supervisor starts it again on the new code. A consumer you started by hand without --max-messages doesn't check, so stop that one yourself. Saving configuration in the Admin leaves the same poison pill, so consumers also pick up config changes.
Should I use MySQL, RabbitMQ or ActiveMQ Artemis?
Out of the box, messages live in MySQL, in three tables: queue, queue_message and queue_message_status. It needs no extra infrastructure, but Adobe is clear that it's 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." Adobe's bulk API docs (opens in a new tab) go further: "Before using the Bulk API to process messages, you must install and configure RabbitMQ."
To connect RabbitMQ:
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, on the releases listed in the table below, Adobe says to remove any AMQP configuration from env.php first:
bin/magento setup:config:set --stomp-host="activemq.internal" --stomp-port="61613" \
--stomp-user="magento" --stomp-password="********"
Which broker your release supports, from Adobe's system requirements (opens in a new tab) for on-premises sites, 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 |
Two upgrade notes from Adobe's release notes. RabbitMQ 4 support arrived with 2.4.8 and the patches released alongside it, and you have to move from classic mirrored queues to quorum queues before you upgrade the broker, because RabbitMQ 4 doesn't support classic mirrored queues. And in the 2.4.9 notes Adobe calls RabbitMQ 4.2 support "a short-term compatibility path", recommends ActiveMQ Artemis as the long-term broker, and says Artemis is fully supported on 2.4.6 through 2.4.9. If you're replacing the broker anyway, that's the direction. The same releases moved the cache from Redis to Valkey; our full page cache vs Varnish vs Redis post covers that side.
Which core consumers does a B2B site need running?
Your custom consumer isn't the only one. Adobe's consumer list (opens in a new tab) says "To enable B2B functionality, you must start multiple consumers", and when one of these stops, the symptom shows up somewhere else entirely:
| Consumer | Edition | What stalls when it isn't running |
|---|---|---|
async.operations.all |
All | Admin bulk actions set to run asynchronously, and the async and bulk REST endpoints |
product_action_attribute.update |
All | Mass attribute updates from the product grid |
inventory.reservations.updateSalabilityStatus |
All | Salable quantity; Adobe says it should always be running if you use Inventory Management |
sales.rule.update.coupon.usage |
All | Coupon usage counts, which is what 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?
Stuck queues come with integration work. On a wholesale site synced with QuickBooks Desktop, part of the job was fixing a sync queue that had stuck (the case study). These are the failure modes in the order we'd check them:
1. Cron isn't running, or isn't starting consumers. Check that the Commerce crontab exists for the file system owner, then look at the job itself:
SELECT job_code, status, scheduled_at, executed_at, messages
FROM cron_schedule
WHERE job_code = 'consumers_runner'
ORDER BY scheduled_at DESC
LIMIT 5;
If it runs but your consumer never starts, check cron_run (on Cloud, CRON_CONSUMERS_RUNNER, which 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, for example an amqp consumer on a site with no RabbitMQ, cron skips it and logs Consumer "<name>" skipped as required connection "<connection>" is not configured. Search var/log for it.
3. Messages failed and nobody noticed. On MySQL, count messages by status:
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;
The statuses are 2 new, 3 in progress, 4 complete, 5 retry required, 6 error and 7 to be deleted. A growing pile of 6 means your handler is throwing, and grep -r "Message has been rejected" var/log/ shows why.
4. Messages stuck "in progress". Usually a consumer that was killed mid-message. Commerce puts them back for retry once Retry Messages In Progress After has passed (Stores > Settings > Configuration > Advanced > System > MySQL Message Queue Cleanup, 1440 minutes by default), when the cleanup cron runs, twice a day. If a day is too long to wait, lower that setting, keeping it above the time your slowest message takes, rather than editing rows by hand. On RabbitMQ, unacknowledged messages go back on the queue by themselves when the connection drops.
5. A poison message. An exception isn't the dangerous case: the default consumer rejects that message once, marks it as an error and moves on, so the queue keeps draining (but that message's work never happens). The dangerous case is a payload that causes a PHP error rather than an exception, such as a TypeError or running out of memory. The default consumer only catches exceptions, so the process dies mid-message. On RabbitMQ the message goes back on the queue and takes down the next consumer too; on MySQL it sits "in progress" until the retry, then does it again. Validate payloads before you publish them, and in the handler, turn errors you can catch into exceptions.
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, so apply this same checklist; core queues fail the same way custom ones do. Our post on what breaks between your ERP and your ecommerce on Black Friday covers watching queue depth before it turns into a support ticket.
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 version notes:
multiple_processesneeds 2.4.4 or later.- The automatic connection choice needs 2.4.5 or later, and ActiveMQ Artemis one of the releases in the broker table.
- RabbitMQ 4 needs 2.4.8, or the 2.4.5 to 2.4.7 patches listed in the table above.
- 2.4.9 changed how cron picks a consumer's message limit, as described above.
- Mage-OS 3.x and 4.0 are built on Magento Open Source 2.4.9, and Mage-OS 2.x on 2.4.8.
One planning note. Standard support for 2.4.6 ended on August 11, 2026; Adobe Commerce 2.4.6 has extended support until August 31, 2027, and Adobe Commerce 2.4.4 and 2.4.5 are down to security-only fixes until May 31, 2027. If your queues run on one of those, fold the upgrade into the same work. Our Adobe Commerce EOL checker has the dates for each version and edition.
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, and Adobe recommends turning it on. 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.
Most connections between an ecommerce site and an ERP have a queue underneath, and our integration guide covers the API side of the same work. If a queue on your site has stopped draining, or you're wiring the site to an ERP and want the queue side done right, tell us what you're seeing through Adobe Commerce development. This is a fun one for us.