TYPO3

Background jobs in TYPO3 with the message bus

6 min read

Queue it, don't wait

I’d a requirement in one of my projects: when a visitor submits a contact form, the data has to go into an external CRM as well. Simple enough. The CRM’s API, though, sometimes needs several seconds to answer, and sometimes doesn’t answer at all.

So the visitor was sitting in front of a spinning button, waiting for a system they had never heard of. That’s not nice. The work had to move out of the request.

What I tried first

My first idea was the classic one I have used since TYPO3 6.2 days: write the job into a custom table with a status field, and let a Scheduler task pick up open rows every few minutes. It works. I have built it more than once. But every time I end up writing the same things again: locking so two runs don’t take the same row, a retry counter, cleanup of old rows, logging.

Then I remembered that TYPO3 has shipped a message bus since v12, built on Symfony Messenger. I had read the changelog back then and never used it. This was the first time, and honestly, I should have tried it earlier.

How it fits together

Messenger has three parts. A message is a small object that says what should happen. A handler does the work. A transport decides when and where: right now in the same process, or later from a queue.

In TYPO3 the default routing sends every message to the default transport, which is synchronous. So out of the box, your handler simply runs immediately. That surprised me at first, because I dispatched a message and the request was exactly as slow as before. The fix is one line of routing, see Step 4.

Solution

The examples are for TYPO3 13.4 and 14.3 in Composer mode. I checked the classes against the v14 core installed in my project.

Step 1: Create the message

Keep it small and only put scalar values in it. Messages are serialized into the database, so an Extbase model or a request object inside it is asking for trouble.

<?php

declare(strict_types=1);

namespace HojaContactsMessage;

final readonly class SyncContactToCrm
{
    public function __construct(
        public int $contactUid,
    ) {}
}

Step 2: Write the handler

Our hero here is the #[AsMessageHandler] attribute from Symfony. TYPO3 picks it up through autoconfiguration, so with the usual Services.yaml (autowire and autoconfigure on) there is nothing else to register. The type of the __invoke() parameter tells Messenger which message this handler is for.

<?php

declare(strict_types=1);

namespace HojaContactsMessageHandler;

use HojaContactsDomainRepositoryContactRepository;
use HojaContactsMessageSyncContactToCrm;
use HojaContactsServiceCrmClient;
use PsrLogLoggerInterface;
use SymfonyComponentMessengerAttributeAsMessageHandler;

#[AsMessageHandler]
final readonly class SyncContactToCrmHandler
{
    public function __construct(
        private ContactRepository $contactRepository,
        private CrmClient $crmClient,
        private LoggerInterface $logger,
    ) {}

    public function __invoke(SyncContactToCrm $message): void
    {
        $contact = $this->contactRepository->findByUid($message->contactUid);
        if ($contact === null) {
            // Deleted in the meantime: nothing to do, and no reason to fail
            $this->logger->info('Contact {uid} is gone, skipping CRM sync', ['uid' => $message->contactUid]);
            return;
        }
        $this->crmClient->upsert($contact);
    }
}

Notice the early return. When the worker gets to the message, the world may have changed. A handler should cope with that quietly instead of throwing an exception and getting retried for nothing.

Step 3: Dispatch from the controller

Inject MessageBusInterface and call dispatch(). TYPO3 aliases it to its default bus.

<?php

declare(strict_types=1);

namespace HojaContactsController;

use HojaContactsDomainModelContact;
use HojaContactsDomainRepositoryContactRepository;
use HojaContactsMessageSyncContactToCrm;
use PsrHttpMessageResponseInterface;
use SymfonyComponentMessengerMessageBusInterface;
use TYPO3CMSExtbaseMvcControllerActionController;
use TYPO3CMSExtbasePersistenceGenericPersistenceManager;

final class ContactController extends ActionController
{
    public function __construct(
        private readonly ContactRepository $contactRepository,
        private readonly PersistenceManager $persistenceManager,
        private readonly MessageBusInterface $bus,
    ) {}

    public function createAction(Contact $contact): ResponseInterface
    {
        $this->contactRepository->add($contact);
        // Persist first, otherwise the new record has no uid yet
        $this->persistenceManager->persistAll();
        $this->bus->dispatch(new SyncContactToCrm($contact->getUid()));

        return $this->redirect('thanks');
    }
}

Step 4: Route the message to the Doctrine transport

This is the line that makes it asynchronous. TYPO3 ships a preconfigured Doctrine transport that stores messages in the table sys_messenger_messages of the default connection. Run the database schema update once so the table exists.

<?php

// config/system/additional.php
use HojaContactsMessageSyncContactToCrm;

$GLOBALS['TYPO3_CONF_VARS']['SYS']['messenger']['routing'][SyncContactToCrm::class] = 'doctrine';

You could also route everything with '*', but I prefer naming each message. Then the core and other extensions keep their own behaviour.

Step 5: Run a worker

Now the messages wait in the table until somebody consumes them. Locally you can do it by hand:

ddev exec vendor/bin/typo3 messenger:consume doctrine -vv

That gets boring after the second time, so in DDEV I let the web container run it as an extra daemon. DDEV keeps it running, and --time-limit makes the worker exit every hour so it picks up code changes when it is started again.

# .ddev/config.yaml
web_extra_daemons:
  - name: "messenger"
    command: "/var/www/html/vendor/bin/typo3 messenger:consume doctrine --time-limit=3600 -vv"
    directory: /var/www/html

On a server with systemd, the TYPO3 documentation recommends a service unit with a restart policy. The worker exits cleanly when it hits a limit, and systemd starts a fresh one.

# /etc/systemd/system/typo3-messenger.service
[Unit]
Description=TYPO3 message consumer

[Service]
User=www-data
WorkingDirectory=/var/www/site/current
ExecStart=/usr/bin/php vendor/bin/typo3 messenger:consume doctrine --time-limit=3600 --memory-limit=128M
Restart=always
RestartSec=1

[Install]
WantedBy=multi-user.target

On shared hosting without a service manager, you can run messenger:consume from the Scheduler instead. Then keep --time-limit below the cron interval, for example 240 seconds for a five-minute cron, so two workers never overlap.

Things I learned on the way

  • Persist before you dispatch. A new Extbase object has no uid until the persistence manager has written it, and a message with uid 0 is useless.
  • Handlers run on the CLI. There is no frontend request, no site and no language from the request. If the handler needs them, put the identifiers into the message and build what you need from them.
  • Long-running PHP processes keep their memory. Use --memory-limit and --time-limit, and don’t keep big caches in static properties.
  • The worker runs the code it started with. After a deployment, restart it, otherwise it happily runs the old version.
  • Worker limit options changed in 14.2. If you come from v13, read the changelog before copying an old service file.

Was it worth it?

For this kind of job, yes. The form answers right away, the CRM call happens a few seconds later in the background, and I didn’t write a single line of locking code. One thing to know: as far as I can see in the v14 core code, TYPO3 doesn’t wire up Symfony’s automatic retry strategy. If the CRM is down and the handler throws, the message is not tried again by itself. So wrap the upsert() call in a try/catch, log the failure, and let a small command re-send failed contacts later. Not perfect, but honest.

I’m not saying every Scheduler task should become a message. A nightly import that runs once at 3 am is still a fine Scheduler task. But for “do this soon, not now” work, the message bus is now my first choice.

If this post helped you, I will be really happy. And if you run workers on a managed host in some clever way, please comment, I’d love to learn how.

Further reading

Leave a comment

Your email address will not be published.