Skip to main content
FreeAn audit of your Drupal siteA written audit of your Drupal site, within three business days
All articles

Backend & EngineeringNov 10, 20269 min read

Zero-downtime deploys, the Drupal backend side

Valentin ZsigmondFounder & Lead Engineer

A zero-downtime deploy is mostly an infrastructure promise. The new release is built next to the one that is serving, and an atomic switch, usually a symlink flip, makes it live. Visitors never see a half-copied tree. We wrote about the calm this brings in the case for boring deployments.

The promise has a condition, though, and it lands on the developer. For a short stretch, two releases share one database. Code that assumes it is alone can still break a deploy that the platform did everything right for. This article is the backend side: the habits that make Drupal code safe to ship this way, with the code for each. The examples use Drupal 11.4 and Drush 13.

What changes when the old release keeps running

A typical zero-downtime deploy of a Drupal site runs in this order:

  1. Build the new release in its own directory: Composer, front-end assets, and often a cache rebuild.
  2. Run drush updatedb against the shared database.
  3. Run drush config:import.
  4. Switch to the new release.
  5. Rebuild caches and run anything that must happen once the new code serves.

Until step 4, the previous release is still running against the database that steps 2 and 3 are changing. Where a platform shows a maintenance page during schema updates, the old code still runs behind it, and its cron keeps running unless the deploy pauses it. Every rule below follows from that overlap. The new schema must not break the old code, and the old code must not undo the work of the new one.

Schema in hook_update_N, data in post_update

Drupal has two kinds of update functions, and on a zero-downtime platform the choice matters. hook_update_N() lives in my_module.install and is for schema. hook_post_update_NAME() lives in my_module.post_update.php, runs after every hook_update_N() has finished, and has a fully bootstrapped Drupal. It is for data.

// my_module.install
function my_module_update_11001(): void {
  $schema = \Drupal::database()->schema();
  if (!$schema->fieldExists('my_module_subscription', 'source')) {
    $schema->addField('my_module_subscription', 'source', [
      'type' => 'varchar',
      'length' => 32,
      'not null' => FALSE,
    ]);
  }
}

// my_module.post_update.php
function my_module_post_update_subscription_source(array &$sandbox): void {
  \Drupal::database()->update('my_module_subscription')
    ->fields(['source' => 'web'])
    ->isNull('source')
    ->execute();
}

Notice that the new column is nullable. The old release does not know it exists and keeps inserting rows without it, so a column that required a value would break the old code's inserts. Notice also that the back-fill cannot be complete. The old release can add rows between the post-update and the switch, so the new code must still read NULL as 'web'.

The split pays off in another way. A pending list made only of post-updates is data work the old release can serve through, and drush updatedb:status shows the type of every pending entry. On the platform we run, such a deploy needs no maintenance page; only a release that carries a hook_update_N() gets a short window. Put data fixes in post-updates and most releases never pause.

Removing a column takes two releases

Dropping a column is where the overlap hurts most. If an update hook drops a column, the previous release is still serving for the seconds before the switch, and every query of it that names that column fails. The result is a burst of errors on a deploy that otherwise went fine.

For a column in your own table, the fix is to split the removal. Release 1 stops reading and writing the column, and leaves the schema alone:

 $this->database->insert('my_module_subscription')
   ->fields([
     'email_hash' => $hash,
     'source' => $source,
-    'legacy_code' => $code,
   ])
   ->execute();

This only works if the column is nullable or has a default, so inserts that leave it out still succeed. If it is NOT NULL without a default, release 1 also relaxes it. Release 2, shipped later, drops it with $schema->dropField() in an update hook, guarded by fieldExists() like the first example, and updates hook_schema() so fresh installs match. By then no running code mentions the column. Adding a column, by contrast, is normally compatible with old code in a single release; check constraints and defaults before you assume so.

An entity base field needs a short window

For an entity base field, the split protects your code but not core's. Drupal's entity storage builds every load and save from the installed field definitions, so it names every installed column, whether your code uses the field or not. The old release notices that a field is gone only when its cached copy of those definitions is cleared.

The first release still does useful work: it removes everything of yours that touches the field (code, entity queries, views, form and display settings) and keeps the definition installed. The second release removes the field from baseFieldDefinitions() and uninstalls its storage through the entity definition update manager. Never use a plain dropField() here; core would still believe the field exists.

// my_module.install, in the second release.
function my_module_update_11002(): void {
  $manager = \Drupal::entityDefinitionUpdateManager();
  $definition = $manager->getFieldStorageDefinition('legacy_code', 'acme_ticket');
  if ($definition) {
    $manager->uninstallFieldStorageDefinition($definition);
  }
}

What the old release does while this runs depends on the field and the cache:

  • A single-value field is a column in the entity's shared table. If the update and the old release share one cache, the update clears the cached definitions and only requests already in progress fail.
  • If the update runs with caches of its own, such as an isolated build step or cache keys per release, the old release keeps selecting that column until the switch.
  • A multi-value field has its own table, which the uninstall renames. The old release still declares the field and keeps reading the old table until the switch, whatever the cache.

So plan the release that uninstalls a base field as a schema change with a short maintenance window, not a serve-through deploy. On the platform we run, any hook_update_N() gets that window. The old release's cron still runs behind the page, so a cron job that loads the entity type can log errors for those seconds. If the field holds data, core first copies the values into a holding table that cron purges later, so the update takes longer on a large table.

Soft references to a module that is not enabled yet

A new module usually arrives through the exported core.extension.yml, so it is enabled during the configuration import. But many pipelines rebuild caches during the build, which happens first. That rebuild compiles the service container from the new code against the live database, where the new module is still off. If an enabled module has a hard reference to one of its services, the compile fails and the release never lands. The old release keeps serving, so there is no outage, but the deploy is stuck.

The answer is an optional reference. In services.yml, @? injects the service when it exists and NULL when it does not:

services:
  my_module.signup_handler:
    class: Drupal\my_module\SignupHandler
    arguments:
      - '@entity_type.manager'
      - '@?acme_crm.client'

The constructor takes a nullable parameter and the code checks for it:

namespace Drupal\my_module;

use Drupal\acme_crm\CrmClientInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

final class SignupHandler {

  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly ?CrmClientInterface $crmClient = NULL,
  ) {}

  public function pushToCrm(array $values): void {
    // NULL until a release with acme_crm enabled has shipped.
    $this->crmClient?->push($values);
  }

}

Procedural code has no constructor, so it asks the container instead:

use Drupal\user\UserInterface;

/**
 * Implements hook_user_login().
 */
function my_module_user_login(UserInterface $account): void {
  if (!\Drupal::hasService('acme_crm.client')) {
    return;
  }
  \Drupal::service('acme_crm.client')->recordLogin((int) $account->id());
}

Keep the soft form until at least one release with the module enabled has shipped. You can replay the failing order locally: uninstall the new module, run drush cache:rebuild, then drush config:import. The rebuild in the middle is the step that fails in a deploy.

settings.php has no soft form. A line such as $settings['cache']['default'] = 'cache.backend.redis'; runs before the container exists, so nothing can check whether the module is enabled. Ship it in two releases: first add the module and enable it, then add the settings line.

Copying live data: seed lazily instead

Moving live data, such as a counter, a queue or a state value, into a new structure looks like a job for an update hook. On a zero-downtime platform it is a race. The hook takes a snapshot, then the old release and its cron keep writing to the old location until the switch. Those writes are lost, and if the value is a counter, the new code hands out numbers that were already used.

Split the job instead. The update hook only creates the new structure:

function my_module_update_11003(): void {
  $schema = \Drupal::database()->schema();
  if (!$schema->tableExists('my_module_sequence')) {
    $schema->createTable('my_module_sequence', [
      'fields' => [
        'series' => ['type' => 'varchar_ascii', 'length' => 64, 'not null' => TRUE],
        'value' => ['type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0],
      ],
      'primary key' => ['series'],
    ]);
  }
}

The new code seeds each row from the old location the first time it needs it. It runs only after the switch, so the seed sees every write the old release made. Here the old location is a key/value collection:

namespace Drupal\my_module;

use Drupal\Core\Database\Connection;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;

final class NumberSequence {

  public function __construct(
    private readonly Connection $database,
    private readonly KeyValueFactoryInterface $keyValue,
  ) {}

  public function next(string $series): int {
    $legacy = $this->keyValue->get('my_module.sequence');

    // Insert-if-missing: the first call after the switch seeds the row.
    $this->database->merge('my_module_sequence')
      ->keys(['series' => $series])
      ->insertFields(['series' => $series, 'value' => (int) $legacy->get($series, 0)])
      ->execute();

    $transaction = $this->database->startTransaction();
    $next = 1 + (int) $this->database->select('my_module_sequence', 's')
      ->fields('s', ['value'])
      ->condition('series', $series)
      ->forUpdate()
      ->execute()
      ->fetchField();
    $this->database->update('my_module_sequence')
      ->fields(['value' => $next])
      ->condition('series', $series)
      ->execute();

    // For one release, mirror the value so a rollback continues correctly.
    $legacy->set($series, $next);
    $transaction->commitOrRelease();

    return $next;
  }

}

Notice three things. The merge only inserts, so concurrent first calls do not overwrite each other. The row lock from forUpdate() keeps two requests from taking the same number. And the mirror write keeps the old location current, and with core's default database-backed key/value store it goes through the same connection, so it commits in the same transaction. If you roll back to the previous release, it carries on from the right number. A later release copies any leftovers, removes the mirror and drops the old location, once the old code can no longer run.

Config, failed updates and other edges

Two more traps come from the deploy order itself.

Update hooks cannot back-fill exported configuration. drush updatedb runs before drush config:import, and the import is authoritative. A hook that changes a config object you also export runs, records itself as done and is then overwritten by the export in the same deploy. Put the new values in the exported YAML file. Keep the hook only for sites that do not carry the export. Check the result by reading the value, not the schema version.

An aborted update run can leave the site in maintenance mode. Drush turns maintenance mode on for the batch and queues a final step that turns it off again. When an update throws an exception, Drush records the failure, skips the post-updates and still runs that step. When the batch process itself dies, on a fatal error, a memory limit or a PHP Error thrown from a post-update, the step never runs. After a failed drush updatedb, check drush maint:get before you look for the cause of the 503s elsewhere, and clear it with drush maint:set 0 once the update is fixed.

Failing on purpose is useful too: when a precondition must hold before an update can run, throw \Drupal\Core\Utility\UpdateException with the fix in its message. Drush prints the message, exits with an error, and the update stays pending until it passes.

Trade-offs

None of this is free. A column removal or a data move becomes two or three releases instead of one, a base field removal still ends in a short window, and someone has to remember the follow-up. Soft references add a null check that you will delete later. Lazy seeding moves migration logic into runtime code, where it has to be tested like any other code path.

For a small site where a short maintenance window is acceptable, a single release with a planned window can be the simpler choice. Make it a decision someone signs off on, not a default. A destructive schema change should never rely on a few errors during the switch being acceptable. The habits above cost a little planning and give back deploys that nobody notices.

If you want help applying this to an existing codebase, or a second opinion on an update hook before it ships, our support team can help, and we are happy to talk.

Written by

Valentin Zsigmond

Founder & Lead Engineer

Full-stack Drupal architect with almost two decades of experience leading large teams in enterprise environments. Founded Tilizy Digital to bring senior-level expertise directly to the organizations that need it. Mentor to dozens of Drupal developers and creator of SDX — a Drupal extension for building modern frontends with React and Vue.

Enjoyed this article?

If this resonated, imagine what we could do working together on your Drupal site.