Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 62 ยท Caching, Performance and Testing

The Cache Component

Use Symfony's Cache component: CacheInterface::get(), cache pools and adapters, expiration, tags, invalidation and stampede protection, with runnable stand-ins.

HTTP caching saves whole responses. Inside your application you also compute things that are expensive and rarely change: a database aggregate, a remote API result, a rendered fragment, a parsed configuration file. The Cache component gives you a small, uniform way to store those values and read them back, with the storage (files, Redis, Memcached, a database, memory) swappable without touching your code.

This lesson covers the one method you will use most, get() with a callback, then cache pools and adapters, expiration, tags, and stampede protection. As usual, the Symfony code is real and read-only here, while the runnable examples are plain-PHP stand-ins that follow the same ideas. The lesson assumes you know autowiring, because caches are services you inject.

The cache contract: get with a callback

Symfony's cache API revolves around CacheInterface from symfony/cache-contracts. It has a single method that does both reading and writing:

PHP
// src/Service/ReportService.php (real Symfony, read-only)
namespace App\Service;

use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

final class ReportService
{
    public function __construct(private CacheInterface $cache)
    {
    }

    public function monthlyTotals(int $year): array
    {
        return $this->cache->get("totals_$year", function (ItemInterface $item) use ($year): array {
            $item->expiresAfter(3600); // one hour

            return $this->computeExpensiveTotals($year);
        });
    }
}

If the key totals_2025 exists and has not expired, get() returns the stored value and the callback never runs. If not, it runs the callback, stores the result under that key and returns it. There is no separate if (!$cache->has()) step, which also avoids the classic race between checking and storing.

Autowiring CacheInterface gives you the application's default pool (cache.app). Delete a key with $cache->delete('totals_2025').

flowchart LR
    C["cache->get(key, callback)"] --> H{"Value stored and fresh?"}
    H -->|yes| R["Return the stored value"]
    H -->|no| X["Run callback"]
    X --> S["Store with its expiry"]
    S --> R

get() hides the hit-or-compute decision from your code.

Pools and adapters

A cache pool is a named bucket of cache items with its own storage. An adapter is the class that talks to that storage: FilesystemAdapter, ArrayAdapter (memory for one request, great in tests), RedisAdapter, MemcachedAdapter, PdoAdapter, ApcuAdapter and others. You configure pools in config/packages/cache.yaml:

YAML
# config/packages/cache.yaml (real Symfony, read-only)
framework:
    cache:
        app: cache.adapter.filesystem
        default_redis_provider: '%env(REDIS_URL)%'
        pools:
            cache.reports:
                adapter: cache.adapter.redis
                default_lifetime: 3600
            cache.catalog:
                adapter: cache.adapter.apcu

Each pool becomes a service you can inject, either by its CacheInterface argument name or with the #[Target] attribute:

PHP
// real Symfony, read-only
use Symfony\Component\DependencyInjection\Attribute\Target;

public function __construct(
    #[Target('cache.reports')] private CacheInterface $reportsCache,
) {
}

Use separate pools when data has different lifetimes or storage needs; you can clear one pool (php bin/console cache:pool:clear cache.reports) without flushing everything. In production, a shared store such as Redis lets all your servers see the same cache, while the filesystem adapter is private to each machine.

Do not confuse the application cache (cache.app, yours) with the system cache (cache.system, used internally for compiled metadata) and the container cache in var/cache. cache:clear rebuilds the container; cache:pool:clear empties pools.

Expiration

Items live until you delete them unless you set a lifetime. Two methods on the ItemInterface argument do it:

  • $item->expiresAfter(300): an interval in seconds (or a DateInterval).
  • $item->expiresAt(new \DateTimeImmutable('tomorrow')): a fixed moment.

A pool also accepts default_lifetime in its configuration. Choose lifetimes deliberately: a long one is fast but serves stale data, a short one is fresh but computes often.

Keys have rules too: they must not contain {}()/\@: (these are reserved), and should be short and stable. Build them from the inputs of the computation, such as "totals_{$year}_{$region}", and make sure every input that changes the result is part of the key. A key that forgets the locale shows French text to English users.

Tags and invalidation

Expiry is simple but blunt. Often you want "delete everything that depends on product 7 the moment product 7 changes". That is what tags are for, available with a tag-aware pool (cache.app is one by default):

PHP
// real Symfony, read-only (needs TagAwareCacheInterface)
use Symfony\Contracts\Cache\TagAwareCacheInterface;

$html = $cache->get('product_card_7', function (ItemInterface $item) use ($product) {
    $item->tag(['products', 'product_7']);

    return $this->renderCard($product);
});

// later, when product 7 is edited:
$cache->invalidateTags(['product_7']);

Every entry tagged product_7 becomes invalid at once, no matter its key or its remaining lifetime. Tags need a TagAware pool; inject TagAwareCacheInterface rather than CacheInterface to use them. With Doctrine, a lifecycle listener or an event subscriber is the usual place to call invalidateTags().

Stampede protection

Picture a popular key that expires while 200 requests per second arrive. All 200 find an empty cache and start the same expensive computation together, which can overwhelm the database: a cache stampede. Symfony helps in two ways:

  1. Locking. Pools use a locking mechanism so that one process computes while others wait for its result, when a lock store is available.
  2. Probabilistic early expiration. get() takes an optional third argument, beta. With the default value of 1.0, a request has a small, growing chance of recomputing the value shortly before it expires, so one lucky request refreshes it while the rest still get the old value. A beta of 0 disables early recomputation (useful in tests), and INF forces recompute.

You do not have to manage this by hand, but you should know it exists, because it is a reason to prefer get() with a callback over hand-rolled has()/set() logic.

A cache you can run

The real component needs Composer. This stand-in implements the get() contract with an array store and a fake clock, so you can watch hits, misses and expiry. It is not Symfony's code.

PHP get() with a callback and expiry (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The callback runs at t=0, again when the entry has expired at t=60, and once more after an explicit delete. Everything else is a hit. The caller never writes an if: the cache owns the decision.

Tags, seen in code

Tags need an index from tag to keys. The stand-in below keeps that index in memory and shows how one invalidateTags() call removes entries with different keys.

PHP Invalidating by tag (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Editing product 7 removes its card and its page, and leaves the others alone. Invalidating the broader products tag then clears the remaining entries. Real tag-aware pools do the same bookkeeping with versioned tag values so it stays cheap even with millions of items.

What to cache, and what not to

Good candidates are results that are expensive to compute, read much more often than they change, and the same for many users: aggregates, remote API calls, rendered fragments, configuration. Be careful with per-user data (put the user id in the key), with anything that must be exactly current (balances, stock counts), and with very large values. And remember the oldest joke in computing: there are two hard things, and cache invalidation is one of them. Prefer short lifetimes plus tags over clever manual deletion, and measure before and after to prove the cache helps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $cache->get('key', $callback) do when the key is already stored and fresh?

    get() returns the cached value on a hit. The callback only runs on a miss, and its result is stored.
  2. 2. What is a cache pool?

    Pools let different kinds of data use different storage and lifetimes, and be cleared independently.
  3. 3. Why use tags?

    Tag entries with what they depend on, then call invalidateTags() when that data changes.
  4. 4. What problem does stampede protection address?

    Locking and probabilistic early expiration let one process refresh a hot value while the others keep using it or wait.

Summary

  • CacheInterface::get($key, $callback) returns a stored value or computes, stores and returns it; the callback sets expiry on the ItemInterface.
  • A pool is a named cache; an adapter is its storage (filesystem, Redis, APCu, array, database).
  • Include every input that changes the result in the key, and choose lifetimes deliberately.
  • Tag entries with $item->tag() and clear groups with invalidateTags() using a tag-aware pool.
  • Stampede protection (locking and early expiration) keeps hot keys from overloading your backend.
  • The runnable examples are stand-ins; the Symfony snippets are real and read-only here.

Next up: Testing with PHPUnit.