Skip to main content
CakeDC Blog

Two Workers, One Cache Entry: Fixing a Race Condition with Cake\Lock in CakePHP 5.4

Two Workers, One Cache Entry: Fixing a Race Condition with Cake\Lock in CakePHP 5.4

On an application I work on, an admin page shows the items processed in the last few days, in near real time. Behind it there is a single cache entry per queue type, a small map of item IDs and timestamps that every queue worker updates when it finishes processing an item. On a quiet day this works perfectly. On a busy day, with several workers finishing items within milliseconds of each other, items quietly went missing from the page. Nothing was lost in the database, nothing was logged, the cache simply forgot some of them.

The cause was a textbook race condition, and during our CakePHP 5 upgrade my teammate Evgeny fixed it with a feature that only arrived in CakePHP 5.4: the Cake\Lock package. This article covers the bug, Evgeny's fix, and the two mistakes in the first version of that fix that only showed up under real load.

The problem: read, modify, write, from several processes at once

This is a simplified version of the original code, from the CakePHP 4 branch:

// src/Model/Table/ProcessingQueuesTable.php (CakePHP 4)
public function updateRecentItemsCache(EntityInterface $item, string $queueType): void
{
    $itemId = $item->get('uid');
    if (empty($itemId)) {
        return;
    }

    $items = $this->readRecentItemsCache($queueType);
    $items = [$itemId => ['uid' => $itemId, 'modified' => time()]] + $items;

    Cache::write($queueType, $items, 'processing_queue');
}

Read the map, add one entry, write the whole map back. Each call is correct on its own. The problem shows up when two workers interleave:

  1. Worker A reads the map: {1, 2, 3}.
  2. Worker B reads the map: {1, 2, 3}.
  3. Worker A writes {A, 1, 2, 3}.
  4. Worker B writes {B, 1, 2, 3}, overwriting A's write.

Item A is in the database and fully processed, but it never shows on the page. To make it worse, the admin page also writes to the same entry: readRecentItemsCache() prunes expired items and rebuilds the map from the database when the cache is empty, so the reader can overwrite a worker's update too.

Switching cache engines doesn't help. Cache::write() is atomic for a single key, but the read-modify-write sequence around it isn't, whatever the engine. What we needed was mutual exclusion: only one process at a time between the read and the write.

What CakePHP 5.4 adds: Cake\Lock

Before 5.4, the options were writing flock() calls by hand, pulling in a third-party lock library, or building something on top of Redis SET NX. CakePHP 5.4 ships a Lock registry that follows the same pattern as Cache and Log: you configure named engines once, then use a static facade anywhere. The 5.4 release includes engines for Redis, Memcached, files and testing.

The configuration can go in config/bootstrap.php:

// config/bootstrap.php
use Cake\Lock\Engine\FileLockEngine;
use Cake\Lock\Lock;

Lock::setConfig('default', [
    'className' => FileLockEngine::class,
    'path' => CACHE . 'processing_queue',
    'prefix' => 'app_lock_',
    'ttl' => 60,
]);

FileLockEngine is built on flock(). Each lock name becomes a file under path, and ttl is how old a lock file must be before the engine treats it as stale and cleans it up. I'll come back to why that matters.

The API ended up using is a single method, Lock::synchronized(): it acquires the lock, runs a closure, releases the lock (also when the closure throws), and returns the closure's result. If the lock can't be acquired within timeout seconds, it returns null and the closure never runs.

$result = Lock::synchronized(
    'processing_queue_' . $queueType,
    function () use ($queueType, $itemId, $itemData) {
        $items = Cache::read($queueType, 'processing_queue') ?? [];
        $items = [$itemId => $itemData] + $items;
        Cache::write($queueType, $items, 'processing_queue');

        return 'ok';
    },
    ttl: 60,
    timeout: 10,
);

The lock name includes the queue type, so workers on different queues never block each other. They write different cache entries, so they don't need to.

Mistake one: treating a timeout as "skip it"

The first version of the fix read null as "someone else is busy, skip this update". It's the obvious reading of the return value, and it's wrong for this use case. Under exactly the load that caused the original bug, workers started timing out on the lock, skipping their update, and the page lost items again, just less often, which made it harder to notice.

An item that was processed must reach the cache. So the final version retries a few times with a short timeout, logs each retry, and then switches to a blocking wait with a longer timeout until the write succeeds:

// src/Model/Table/ProcessingQueuesTable.php
public function updateRecentItemsCache(EntityInterface $item, string $queueType): void
{
    $itemId = $item->get('uid');
    if (empty($itemId)) {
        return;
    }

    $itemData = ['uid' => $itemId, 'modified' => time()];

    for ($attempt = 1; $attempt <= 5; $attempt++) {
        if ($this->tryUpdateRecentItemsCache($queueType, $itemId, $itemData, 10)) {
            return;
        }
        Log::warning("Retrying recent items cache update for {$itemId} (attempt {$attempt}/5)");
    }

    while (!$this->tryUpdateRecentItemsCache($queueType, $itemId, $itemData, 30)) {
        Log::warning("Waiting for recent items cache lock for {$itemId}");
    }
}

The retry warnings matter as much as the loop: if they show up in the logs, the critical section is too slow or something is holding the lock, and you want to know before anyone reports missing items. In the real code the attempt counts and timeouts come from the Lock config array.

Mistake two: doing slow work while holding the lock

The second problem was subtler. When the cache entry didn't exist yet (after a cache clear, or on the first item of the day), the closure rebuilt the map from the database. That query was the slowest thing in the whole method, and it ran while every other worker waited for the lock, which was exactly what made them time out in the first place.

The fix was to keep the critical section limited to cache reads and writes, and move the rebuild outside the lock:

// src/Model/Table/ProcessingQueuesTable.php
protected function tryUpdateRecentItemsCache(
    string $queueType,
    string $itemId,
    array $itemData,
    int $timeout,
): bool {
    $status = $this->mergeItem($queueType, $itemId, $itemData, $timeout);
    if ($status === 'miss') {
        // Slow DB query, deliberately outside the lock.
        $rebuilt = $this->rebuildRecentItemsCacheFromDb($queueType);
        $status = $this->mergeItem($queueType, $itemId, $itemData, $timeout, $rebuilt);
    }

    return $status === 'ok';
}

protected function mergeItem(
    string $queueType,
    string $itemId,
    array $itemData,
    int $timeout,
    ?array $rebuilt = null,
): string {
    $status = Lock::synchronized(
        'processing_queue_' . $queueType,
        function () use ($queueType, $itemId, $itemData, $rebuilt) {
            $items = Cache::read($queueType, 'processing_queue') ?? $rebuilt;
            if ($items === null) {
                return 'miss';
            }

            $items = [$itemId => $itemData] + $items;
            Cache::write($queueType, $items, 'processing_queue');

            return 'ok';
        },
        ttl: 60,
        timeout: $timeout,
    );

    return $status ?? 'locked';
}

The second mergeItem() call still reads the cache first and only falls back to the rebuilt map if the entry is still missing. If another worker rebuilt it in the meantime, its version wins and ours is merged into it, so nothing gets overwritten. Two workers might both run the rebuild query on a cold cache, which is a little wasted work but never wrong, and it's a far better trade than holding the lock during a database query.

The admin page's read path uses the same lock around its read and prune, with the same rule: if the lock can't be acquired after retries, it rebuilds from the database instead of serving an unlocked, possibly stale map.

Know what your lock engine can and can't do

Evgeny picked FileLockEngine for this application because each installation runs on a single server, and web requests and queue workers share the same filesystem. Two things to keep in mind before you copy that choice:

  • flock() only coordinates processes on one host. Two web nodes behind a load balancer, each with its own CACHE directory, will each happily grant the same lock. A shared network filesystem doesn't reliably fix this either. As soon as you have more than one node, configure a Redis or Memcached lock engine that every node talks to, and keep the same Lock::synchronized() calls.
  • A killed process can leave a lock file behind. That's what ttl is for: the engine treats lock files older than ttl as stale. Set it comfortably above the longest your critical section can take, but low enough that a wedged lock clears itself before anyone notices. If you need to recover by hand, the lock files are in the configured path, named with the configured prefix.

Testing it

Because Lock is a registry like Cache, tests can drop the app's configuration and point the engine at a temporary directory, so test runs never touch real lock files:

// tests/TestCase/Model/Table/ProcessingQueuesTableRecentItemsCacheTest.php
protected function setUp(): void
{
    parent::setUp();

    Lock::drop('default');
    Lock::setConfig('default', [
        'className' => FileLockEngine::class,
        'path' => TMP . 'tests' . DS . 'locks',
        'prefix' => 'test_lock_',
        'ttl' => 5,
    ]);
}

From there, the most useful test acquires the lock from outside, calls updateRecentItemsCache() with a short timeout, releases the lock, and asserts the item still made it into the cache. That's the test that would have caught the first version.

What can you do in your application?

  1. Grep for Cache::read() followed by Cache::write() on the same key, especially in code that runs from queue workers or commands. Any of those can lose writes under concurrency.
  2. If you're on CakePHP 5.4, wrap each one in Lock::synchronized() with a lock name scoped to the data it protects, not one global lock.
  3. Decide explicitly what a lock timeout means for each call site. "Skip" is only acceptable when losing the update is acceptable.
  4. Keep the critical section limited to the read-modify-write. Database queries, HTTP calls and file processing belong outside the lock.
  5. Use FileLockEngine only on single-server deploys. With more than one node, use a shared Redis or Memcached lock engine.

If your CakePHP application has this kind of concurrency bug hiding in it, or you're planning the move to CakePHP 5 to get features like this one, this is exactly the kind of work CakeDC does. Get in touch and let's talk about where your project stands and how to move it forward.

Further reading

Need help with this in your own CakePHP app?

Talk to a CakePHP expert

Get the CakeDC newsletter

One email a month: releases, security advisories and one article worth reading.

Back to all articles
We Bake with CakePHP