Drupal Lock API: stop cron jobs running twice
Last month a client's nightly product sync ran twice at once. Cron fired it, then someone clicked "run now" in the admin while the first run was still chewing through a slow supplier API. Two workers, one set of nodes, and a pile of duplicate-key errors and half-updated prices. The fix is not clever: take a lock. Drupal ships a lock service for exactly this, and it is easy to use wrongly.
The API in four methods
The service is lock, implementing \Drupal\Core\Lock\LockBackendInterface. According to the API docs, the ones that matter are:
acquire($name, $timeout = 30.0)returns TRUE if you got the lock. The timeout is the lock's lifetime in seconds, not how long you wait for it.release($name)frees it.lockMayBeAvailable($name)is a cheap check that does not take the lock.wait($name, $delay = 30)blocks up to$delayseconds. It returns TRUE if the lock is still held, FALSE if it may be free, and you still have to callacquire()afterwards because that can fail again.
That lifetime is the part people miss. If your process dies, the lock expires on its own, so a crash cannot wedge the job forever. The flip side: if your job legitimately runs longer than the lifetime, the lock lapses under it and a second worker walks in.
A guarded sync service
Here is the pattern I use, with the lock injected rather than pulled from \Drupal::lock() so it can be tested.
<?php
namespace Drupal\my_sync;
use Drupal\Core\Lock\LockBackendInterface;
use Psr\Log\LoggerInterface;
/**
* Runs the product sync, but never two copies at once.
*/
final class GuardedSync {
private const LOCK_NAME = 'my_sync:products';
// Lifetime in seconds. Must exceed the worst-case run time.
private const LOCK_LIFETIME = 900.0;
public function __construct(
private readonly LockBackendInterface $lock,
private readonly ProductSync $sync,
private readonly LoggerInterface $logger,
) {}
public function run(): bool {
if (!$this->lock->acquire(self::LOCK_NAME, self::LOCK_LIFETIME)) {
$this->logger->notice('Product sync already running, skipping.');
return FALSE;
}
try {
$this->sync->execute();
return TRUE;
}
finally {
$this->lock->release(self::LOCK_NAME);
}
}
}
The finally block matters: an exception from the sync would otherwise leave the lock held until it expires, and the next cron run would skip for up to 15 minutes for no reason.
Skip, or wait your turn?
For cron, skipping is right: the other run is already doing the work. For a user-triggered action you may prefer to wait briefly instead:
if (!$this->lock->acquire($name, 60.0)) {
// Block for up to 10 seconds, then try once more.
$this->lock->wait($name, 10);
if (!$this->lock->acquire($name, 60.0)) {
throw new \RuntimeException('Another sync is in progress.');
}
}
Notice the second acquire(). Skipping it and assuming wait() returning FALSE means "yours now" is the classic bug.
Gotchas
Locks are stored in the database by default (a semaphore table), so they work across web workers on one site but only as well as your database does. That is fine for most sites, and if you run Redis or similar you can swap the backend through the service definition. Also remember that Drupal wipes locks held by a request at its end via releaseAll(), so the lock is tied to the request that took it, which is what you want for cron and drush but not for a job split across several HTTP requests such as Batch API steps. For those, pick a lifetime that covers the whole thing and release it in the batch finished callback, or reconsider whether a queue worker fits better.
My rule of thumb: lifetime is roughly three times the longest run I have ever seen, always release in finally, and log the skip so a permanently stuck lock shows up in the logs rather than as silent missing data.