All articles

Purge a Next.js front end after a Drupal entity save commits

If a Drupal entity hook or event tells a decoupled Next.js front end to re-fetch data, it can fire before the entity save has committed, so the front end reads and caches the old values. The fix is to defer the purge until the end of the request with drupal_register_shutdown_function(), and to keep a per-request set of sites already queued so several saves in one request trigger one purge per site.

This is a small change, but the bug it fixes looks random from the outside, which made it worth writing down.

The setup: a decoupled front end caching global data

On a decoupled Drupal site I work on, the Next.js front end caches "global data": the main menu, footer links, site settings and similar things every page needs. It is fetched once and kept in a shared cache so each page render doesn't have to ask Drupal for the menu again.

When an editor saves a page or a landing page, the menu can change with it: a new title, a new path alias, a menu link added or moved. So Drupal calls an authenticated route on the front end that clears the cached global data. The next request to the front end fetches it fresh from Drupal.

The first version made that call from an event subscriber reacting to the entity update. It worked most of the time. Occasionally an editor would change a page title, save, and the menu on the live site would keep the old title until something else cleared the cache.

Why the front end cached the old title

Drupal's SQL entity storage wraps save() in a database transaction. The insert and update hooks, and any events dispatched from them, run inside that transaction. From the point of view of code in the same request, the new title is already there. From the point of view of any other database connection, it isn't yet: the change only becomes visible when the transaction commits, after all the hooks have returned.

The purge call is an HTTP request to another process. That process turns around and asks Drupal for the global data over a different connection. When that happens quickly enough, the front end reads the pre-save values, caches them, and the purge has achieved nothing except replacing old data with the same old data. Whether you hit this depends on network latency and how long the rest of the save takes, which is why it looked intermittent.

This is the same family of problem as purging a CDN before the origin has regenerated a page: an invalidation that arrives before the new data exists is just a cache refill with stale content.

How to run the purge after the commit

The fix is to stop doing the work inside the event and instead register it to run at the end of the request. drupal_register_shutdown_function() queues a callback that Drupal runs when the request shuts down, by which point the save transaction has long since committed.

The second half of the fix is deduplication. One editor action often saves several entities: a node and its menu link content, or a landing page plus a couple of referenced paragraphs. Each save fires the subscriber. Without a guard, that becomes several identical purge calls for the same site. A service is shared for the whole request, so it can keep a simple set of site ids it has already queued.

A minimal version of the service:

<?php

namespace Drupal\example_decoupled;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;

final class FrontendPurger {

  /** @var array<string, true> Sites already queued in this request. */
  private array $queued = [];

  public function __construct(
    private readonly ClientInterface $httpClient,
    private readonly LoggerInterface $logger,
  ) {}

  public function purgeAfterSave(string $siteId, string $purgeUrl): void {
    if (isset($this->queued[$siteId])) {
      return;
    }
    $this->queued[$siteId] = TRUE;
    drupal_register_shutdown_function([$this, 'purge'], $purgeUrl);
  }

  public function purge(string $purgeUrl): void {
    try {
      $this->httpClient->request('POST', $purgeUrl, ['timeout' => 5]);
    }
    catch (GuzzleException $e) {
      $this->logger->error('Front end purge failed: @message', [
        '@message' => $e->getMessage(),
      ]);
    }
  }

}

The subscriber then calls purgeAfterSave() instead of making the HTTP request itself. Nothing else about the event handling needs to change.

What you give up by running at shutdown

Moving work to shutdown is not free, and it's worth being clear about the trade-offs before reaching for it.

  • The editor never sees a failure. When the purge ran inside the save, a failing call could surface as an error. At shutdown, the response may already be on its way to the browser, so there is nobody to show the error to. Logging becomes the only signal, so log at a level someone will actually notice.
  • It still costs PHP worker time. Under PHP-FPM, Symfony's response handling finishes the request with fastcgi_finish_request(), so the editor's browser doesn't wait for the purge. The worker does, though. Keep a short timeout on the HTTP client so a slow front end can't tie up workers.
  • It runs once per request, not once per transaction. If a single request saves, commits, then saves again and depends on the purge happening between the two, shutdown is too late. That isn't the case for an editor saving a form, which is what this purge is for.

Shutdown functions versus a post-transaction callback

The more precise tool is a callback tied to the transaction itself. Recent Drupal core versions expose a transaction manager on the database connection with a way to register a callback that runs when the root transaction ends, and tells you whether it committed or rolled back. That is attractive, because a rolled-back save shouldn't purge anything.

A shutdown function is the simpler choice when an unnecessary purge after a rollback is harmless, as it is here: the front end simply re-fetches data that didn't change. It also reads plainly to anyone who opens the service later. If the side effect were something that must not happen on rollback, such as sending an email or calling a payment API, I would use the post-transaction callback instead.

Why dedupe by site and not by entity

It is tempting to dedupe by entity id, since that's what the event hands you. But the thing being purged is the site's global data, not the entity. Two different entities saved in one request still need only one purge for their site, and on a multi-site setup with several front ends, two saves for different sites must each get their own. Keying the set by site id matches the cache you are actually clearing.

Key takeaways

  • Drupal entity hooks and events run inside the save transaction, so any external system you notify from them can read the data before it is committed.
  • Deferring the notification with drupal_register_shutdown_function() makes it run after the commit, which removes the race between the purge and the re-fetch.
  • Keep a per-request set keyed by whatever you are purging, such as a site id, so several saves in one request produce one purge.
  • Work moved to shutdown can no longer report errors to the user, so log failures where someone will see them and keep HTTP timeouts short.
  • Reach for a post-transaction callback instead when the side effect must not happen if the save rolls back.