Cache invalidation in microservices with PHP 8.2

Mehmet Akar 4 min read
Diagram of a Redis-based tagged cache architecture

PHP cache invalidation becomes unmanageable with key-based deletion as the number of services grows. Here is how to solve this using tag-based caching, an event queue, and a consistency window, complete with code examples.

The problem: key-based deletion doesn't scale

When a product's price changes, it's not just the product detail page that goes stale; category lists, search results, and promotional blocks become outdated too. Knowing each key individually creates hidden dependencies between services: the pricing service is forced to know the catalog service's cache keys. If a new list is added and the deletion code isn't updated, users see the old price.

Summarizing the differences between approaches to PHP cache invalidation makes the decision easier:

ApproachHow it worksStrengthWeakness
Key-based deletionKeys tied to changed data are deleted one by oneSimple and straightforwardServices must know each other's keys
TTL onlyValue refreshes automatically when it expiresRequires no extra codeStale data is served until expiration
Tag-basedValues are written with tags; clearing a tag deletes them allServices remain loosely coupledTag sets require maintenance
Versioned keysA version counter is added to the key name; incrementing it retires old keysNo deletion operation neededOld values remain in memory until their TTL expires

The solution: tag every entry

Every cached value is stored along with the tags of its related entities (e.g., product:48213, category:112). In Redis, a set holding the key names for each tag is all you need. When a change event arrives, only the tag is cleared, deleting all keys linked to that tag in a single operation.

src/Cache/TaggedCache.php
<?php

final class TaggedCache
{
    public function __construct(private Redis $redis) {}

    public function remember(string $key, array $tags, int $ttl, callable $fn): mixed
    {
        $hit = $this->redis->get($key);
        if ($hit !== false) {
            return unserialize($hit);
        }
        $value = $fn();
        $this->redis->setex($key, $ttl, serialize($value));
        foreach ($tags as $tag) {
            $this->redis->sAdd("tag:$tag", $key);
        }
        return $value;
    }

    public function invalidate(string ...$tags): void
    {
        foreach ($tags as $tag) {
            $keys = $this->redis->sMembers("tag:$tag");
            if ($keys) { $this->redis->del(...$keys); }
            $this->redis->del("tag:$tag");
        }
    }
}

Decoupling services with an event queue

The pricing service publishes the change to a queue as an event; the consumer only knows about the tags:

events/price.updated.json
{
  "event": "price.updated",
  "product_id": 48213,
  "tags": ["product:48213", "category:112", "campaign:autumn"]
}

In this setup, the pricing service has no idea which pages are cached. Adding a new list simply requires writing that list to the cache with the right tags.

NOTE

Set a TTL on tag sets equal to the longest TTL among their keys; otherwise, expired key names will accumulate in memory.

Alternative: invalidation via versioned keys

In some cases, changing part of the key name is simpler than deleting keys. A version counter is kept for each category; when the counter increments, the old keys are no longer read and are cleaned up automatically once their TTL expires.

invalidate-version.php
<?php

// Kategori listesi anahtarı: sürüm değişince yeni anahtar üretilir
$version = (int) $redis->get('ver:category:112');
$key = "category:112:v{$version}:page:1";

// Kategoride bir ürün değiştiğinde
$redis->incr('ver:category:112');

This method avoids deletion traffic, but old values stay in memory for a while. If memory is limited, plan your Redis eviction policy (e.g., allkeys-lru) and TTL values together.

Concurrent requests when the cache is cold

When a popular key is deleted, a surge of concurrent requests can hit the data source all at once (a cache stampede). Using a simple lock ensures that only the first request regenerates the value, while the others wait briefly and then read from the cache.

stampede-lock.php
<?php

// Yalnızca kilidi alan istek değeri yeniden üretir (10 saniyelik kilit)
if ($redis->set("lock:$key", 1, ['nx', 'ex' => 10])) {
    $value = $fn();
    $redis->setex($key, $ttl, serialize($value));
    $redis->del("lock:$key");
}

Accepting the consistency window

  • Stale data may be visible briefly until the event is processed from the queue; measure this window and align on expectations with the business side.
  • Bypass the cache and read directly from the source of truth for critical flows like checkout and inventory.
  • Ensure events aren't lost if a consumer crashes: use acknowledgments (ack) and retries in your queue.
  • For bulk updates, deduplicate tags and clear them in a single batch.

I use a similar decoupling pattern for structured AI outputs; see reliable JSON output from local LLMs. For an example of managing batch jobs with a queue, check out the Local AI Product Image Generation project.

The cache is a performance layer, not the source of truth. Critical decisions should always read from the primary source.

Conclusion

Tag-based PHP cache invalidation removes the need for services to know each other's keys and ensures changes are reflected consistently across all lists. To scale your PHP infrastructure, take a look at my AI-powered web development service.

More notes

All notes →