An article changed: which cached results are now stale?

Map detail, list, category and homepage dependencies: edits, movement and visibility in a local Symfony Cache exercise.

One change can affect several dependent views while leaving an unrelated cache untouched.
One change can affect several dependent views while leaving an unrelated cache untouched.

An imaginary journal displays one article in four places: its detail page, the general list, its category, and the homepage. After editing the title, the detail page is correct but the homepage card still shows the old wording. Persistence is working. The cache dependency model is incomplete.

Deleting the article's own key does not identify other results derived from its data. We need a map of meaningful dependencies, not merely an inventory of keys. The following is an independent teaching example, not a description of a particular platform implementation.

Start with reads, not a clear command

Article note-17 belongs to site journal-a, the Ukrainian locale, and category architecture. Its detail page reads the body and title. A list card reads the title, summary, publication date, and cover. A category list also depends on category membership. The homepage contains an editorial selection of cards.

These are four distinct projections. Changing a body paragraph may affect only the detail page. Changing the title affects all four. Withdrawing publication also changes list membership, counts, and which records occupy each page of a paginated collection.

Change Results to reconsider
Body only, with an unchanged summary Detail page
Title or cover Detail page and every card projection
Category A → B Detail page and both category lists
Visibility or ordering date Membership and ordering of relevant lists

This table describes our chosen model. When the summary is derived from the body, the first row is insufficient: cards must also depend on the body.

A key finds a result; a dependency explains its freshness

A key describes the request being cached. Site, locale, filter, and page number can produce different keys. A dependency label answers a different question: which change makes this result stale?

In our model, the detail page depends on article:note-17, the category list on collection category:architecture, and the homepage on homepage:selection. Every label needs site context. Locale context is needed where translations can change independently. A prefix alone is not an authorization check.

List dependencies cannot be built solely from the records already present in the response. A newly published article does not exist in the cached list, so its individual label cannot invalidate that list. Insertions, removals, and reordering require a collection dependency.

Symfony supports dependencies through tags: ItemInterface::tag() attaches a tag to a result, while TagAwareAdapter::invalidateTags() makes related entries stale. This provides a mechanism for our read map; it does not decide which fields matter to the homepage. See cache tags in Symfony 8.1.

One tag in an executable example

Continue the single Symfony 8.1 project, article_demo, on PHP 8.4+. Run commands from its root and preserve earlier routes, services and stores. The added modules use synthetic data and their own teaching context.

composer require symfony/cache:'8.1.*'

The module contains Identity, ArticleSnapshot, InvalidationPlan and TaggedViews. The app:cache-dependencies-demo command uses Identity and TaggedViews to invalidate one explicitly supplied tag sequentially. ArticleSnapshot and InvalidationPlan belong to a separate planning model; the command does not calculate that plan. Its temporary directory isolates the filesystem cache from earlier exercises. The command removes only that directory when it finishes.

src/Command/CacheDependenciesDemoCommand.php:

<?php

declare(strict_types=1);

namespace App\Command;

use App\CacheDependencies\Identity;
use App\CacheDependencies\TaggedViews;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

#[AsCommand(name: 'app:cache-dependencies-demo', description: 'Run isolated local Symfony tag invalidation')]
final class CacheDependenciesDemoCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $directory = sys_get_temp_dir().'/article-cache-dependencies-'.bin2hex(random_bytes(8));
        $cache = new TaggedViews($directory, 'dependencies');
        $tag = Identity::tag('journal-a', 'uk', 'category', 'architecture');
        $key = Identity::key('journal-a', 'uk', 'category', ['slug' => 'architecture', 'page' => 1]);
        $loads = 0;
        $load = static function () use (&$loads): int {
            return ++$loads;
        };

        try {
            $first = $cache->read($key, [$tag], $load);
            $repeat = $cache->read($key, [$tag], $load);
            $invalidated = $cache->invalidate([$tag]);
            $fresh = $cache->read($key, [$tag], $load);
            $result = ['first' => $first, 'repeat' => $repeat, 'fresh' => $fresh, 'loads' => $loads,
                'invalidation_succeeded' => $invalidated, 'scope' => 'local_sequential_filesystem'];
            $output->writeln(json_encode($result, JSON_THROW_ON_ERROR));

            return $invalidated && $first === $repeat && $fresh === 2 ? Command::SUCCESS : Command::FAILURE;
        } finally {
            (new Filesystem())->remove($directory);
        }
    }
}

The command’s result should contain first=1, repeat=1, fresh=2 and loads=2: a repeated read uses the cache, while invalidation permits the callback to run again. This is the verification criterion. TaggedViews uses the real TagAwareAdapter and disables early probabilistic recomputation for the sequential exercise.

In a real read, the callback would load the category from storage. Here, the counter makes recomputation visible without a real database. Caching and invalidation use one tag generator: similar strings with fields in another order do not become the same tag.

Old and new values both matter

Moving an article from architecture to practice affects both categories. Clearing only the new category leaves the old list displaying a record that no longer belongs there. A change event must expose enough information to identify both sides, or carry an already calculated dependency set.

It need not contain the whole article. For this scenario, identity, site, locale, old and new categories, and indicators of card, ordering, or visibility changes are enough. The event format should follow actual read requirements rather than an ambition to describe every possible change.

Tests should also protect unchanged results

Warm the four projections and a control page belonging to another site. Change the title, then verify both the new wording and that the control result was not rebuilt. Otherwise, clearing the entire store would pass while proving nothing about invalidation precision.

Separate cases should cover a body-only edit, category movement, first publication, withdrawal, and duplicate delivery of the same event. For pagination, include pages whose membership can shift after insertion or removal. Collection-level dependencies can deliberately invalidate more results; that is a trade-off, not automatically a defect.

In this exercise, the general list and homepage each have one collection tag per site and locale. This is deliberately conservative: changing a title may also refresh a list page that does not contain that article. A homepage with complex selection rules can have an explicit selection dependency, but first we must identify changes that affect its membership. Precision means satisfying the chosen contract, not promising the smallest possible number of invalidated keys.

Repeating invalidation after a rebuild may make the result stale again. That creates extra work, so “safe to repeat” does not mean “the callback runs exactly once.” It means the repeat does not corrupt data or escape the defined context.

What a dependency map does not solve

Correct labels do not prevent a reader from starting a rebuild before a change and writing a stale result after invalidation. Result versioning, a coordinated generation check, or another concurrency mechanism requires separate design. The timing of invalidation relative to the database transaction is a separate concern as well.

The goal of this map is an explicit answer for each change: which reads became stale, and why? Once that answer exists, cache-clearing commands implement a decision instead of replacing the model.

Add the module to the same application

The module contains Identity, ArticleSnapshot, InvalidationPlan and TaggedViews. The app:cache-dependencies-demo command uses Identity and TaggedViews to invalidate one explicitly supplied tag sequentially. ArticleSnapshot and InvalidationPlan belong to a separate planning model; the command does not calculate that plan. Its temporary directory isolates the filesystem cache from earlier exercises. The command removes only that directory when it finishes.

The following extends the existing services block in config/services.yaml. Preserve earlier registrations, imports and _defaults; keep the rest of the file.

services:
    App\Command\CacheDependenciesDemoCommand: ~
php bin/console app:cache-dependencies-demo
APP_ENV=test php bin/phpunit tests/CacheDependencies
  1. Caching The cache key as a contract: site, language, permissions and query parameters
  2. Caching Invalidation after commit: what happens when a transaction rolls back?
  3. Architecture HTTP cache and application cache: who refreshes the page?
  4. Caching Core, caching, and different devices: three foundation tasks

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article