Editorial illustration; the queue, worker and labels are representative, not a live Drupal administration screen.
A Drupal page request is a terrible place to run slow external work. If a user submits a form and your hook immediately tries to resize twenty images, send a batch of webhook notifications, or call a sluggish partner API, you are asking for trouble. Behind Nginx or Cloudflare (which enforces a 100-second origin timeout on standard plans), one slow third-party endpoint turns into a 504 Gateway Timeout for the visitor—and leaves you guessing which half of the operation actually succeeded.
Drupal’s Queue API exists to decouple that slow work from the HTTP response. Putting an item in a queue is easy; the real engineering work is keeping payloads small, handling retries without duplicating side effects, and making sure production actually drains the queue.
Deciding What Belongs in a Queue
Use a queue when the visitor does not need the final outcome before the next page renders. Good fits include:
- Syncing updated nodes or user profiles to an external CRM or search index.
- Processing a 5,000-row CSV/JSON product import uploaded by an admin.
- Sending outbound email digests or webhook notifications.
- Generating heavy media derivatives or PDF reports.
Do not use a queue to hide a slow SQL query or a missing cache tag on a page that visitors expect to see immediately. If a checkout flow must verify live inventory before accepting payment, pushing that check into a background queue breaks the business logic. For output that varies by user or context, look at Drupal cache contexts rather than queuing.
Enqueue Small, Stable References
Store the minimum data the worker needs to do its job later—typically an entity ID, an operation name, and maybe a timestamp or revision ID. Avoid serializing an entire node object or a massive JSON blob into the queue table. By the time the worker picks up the item, that node might have been edited again or deleted.
Enqueue the item only after the primary database save has succeeded, so a failed validation does not leave ghost work in the queue:
/**
* Implements hook_entity_insert().
*/
function my_module_entity_insert(\Drupal\Core\Entity\EntityInterface $entity): void {
if ($entity->getEntityTypeId() !== 'node' || $entity->bundle() !== 'product') {
return;
}
$queue = \Drupal::queue('my_module_erp_sync');
$queue->createItem([
'nid' => (int) $entity->id(),
'op' => 'upsert',
'queued_at' => \Drupal::time()->getRequestTime(),
]);
}
Writing a Retry-Safe QueueWorker
Drupal discovers queue workers via QueueWorker plugins inside src/Plugin/QueueWorker/. Notice that when you define cron = {"time" = 30}, you are telling Drupal’s cron runner to spend up to 30 seconds per run on this queue—not giving each individual item 30 seconds.
Your processItem() method should load fresh data, guard against deleted entities, and distinguish between transient failures (worth retrying) and permanent failures (bad data or missing entity that should be logged and dropped):
<?php
namespace Drupal\my_module\Plugin\QueueWorker;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\Queue\RequeueException;
use Drupal\Core\Queue\SuspendQueueException;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Syncs product nodes to the external ERP API.
*
* @QueueWorker(
* id = "my_module_erp_sync",
* title = @Translation("ERP Product Sync"),
* cron = {"time" = 30}
* )
*/
final class ErpSyncWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly EntityTypeManagerInterface $entityTypeManager,
private readonly ClientInterface $httpClient,
private readonly LoggerInterface $logger,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
return new self(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('http_client'),
$container->get('logger.channel.my_module'),
);
}
public function processItem($data): void {
$node = $this->entityTypeManager->getStorage('node')->load($data['nid'] ?? 0);
if (!$node) {
// Entity was deleted before the worker ran; drop the item cleanly.
return;
}
try {
$this->httpClient->request('POST', 'https://erp.example.com/api/products', [
'timeout' => 10,
'headers' => [
'Idempotency-Key' => 'node-' . $node->id() . '-' . $node->getChangedTime(),
],
'json' => [
'sku' => $node->get('field_sku')->value,
'title' => $node->label(),
],
]);
}
catch (GuzzleException $e) {
$code = method_exists($e, 'getResponse') && $e->getResponse()
? $e->getResponse()->getStatusCode()
: 0;
if ($code === 429 || $code >= 500 || $code === 0) {
// Transient network/upstream issue: release item back to the queue.
throw new RequeueException($e->getMessage(), 0, $e);
}
// 4xx validation error: retrying won't fix bad data. Log and let it clear.
$this->logger->error('ERP sync rejected node @nid with HTTP @code: @msg', [
'@nid' => $node->id(),
'@code' => $code,
'@msg' => $e->getMessage(),
]);
}
}
}
Two details here save hours of debugging later:
- Idempotency keys. If the remote API receives your request, creates the record, and the TCP connection drops before the response arrives,
RequeueExceptionwill run the item again. Passing an idempotency key (or checking a local sync state field) prevents duplicate invoices or double notifications. - Exception discipline. Throwing
SuspendQueueExceptionpauses the entire queue for the rest of the cron run—useful if the remote API is completely down (503) and you do not want to hammer it 500 times in a row. Throwing a generic\Exceptionleaves the item in the queue until its lease expires (expiretimestamp in thequeuetable), which looks like a silent stall unless you check logs.
Do Not Rely on Automated Cron in Production
Drupal’s built-in “Automated Cron” module triggers cron at the end of a random visitor’s page request. On a low-traffic site, queues sit idle for hours. On a high-traffic site, one unlucky visitor’s browser waits while PHP drains 30 seconds of queue items.
Disable Automated Cron in production and run queues from a real system crontab or systemd timer using Drush:
# Inspect current queue depth
drush queue:list
# Drain a specific queue with a bounded execution window
drush queue:run my_module_erp_sync --time-limit=45
If you process high-volume imports, keep an eye on the queue database table size and item age. A queue that grows faster than your cron interval drains it is a production backlog, even if your site’s TTFB looks fast. Give your support or ops team a Drush command or simple status report entry so they can see stuck items instead of assuming “cron ran” means “all work finished.”