Doctrine Second-Level Cache: Cutting Repeated SELECTs While Keeping Data Fresh
Enable Doctrine ORM's second-level cache to eliminate repeated SELECTs, but plan manual invalidation to avoid serving stale entities.
14 Jan 2026, 13:17 UTC

The problem: the same SELECT on every request
In a read‑heavy PHP application, Doctrine ORM often issues an identical SELECT for a frequently accessed entity (e.g., a site‑wide configuration row or a core user profile) on every HTTP request. Each query adds latency and database load even though the underlying data rarely changes.
The practical takeaway: enabling Doctrine’s built‑in second‑level cache lets repeated reads retrieve a fully hydrated entity from a shared store, eliminating the round‑trip to the database. The trade‑off is that cache invalidation is not automatic; you must evict or update cache entries whenever the entity changes outside the current EntityManager.
Where the cache sits in the stack
The first‑level cache lives inside a single EntityManager and disappears at the end of the request. The second‑level cache is global for the application process (or across processes when a networked driver is used). It stores hydrated entities and collection results keyed by entity class and identifier, and it can also cache query result sets.
Supported drivers include apcu (shared memory, single‑server only), redis (networked, safe for multiple PHP‑FPM nodes), and array (in‑memory, useful only for tests). The cache is disabled by default; you must opt in and choose a driver.
Enabling the cache (Doctrine ORM ≥ 2.6)
Verify your installed Doctrine version first (composer show doctrine/orm). Versions before 2.6 have limited or no second‑level cache support.
In a plain PHP bootstrap:
$config = new \Doctrine\ORM\Configuration();
$config->setSecondLevelCacheEnabled(true);
$cacheConfig = new \Doctrine\ORM\Cache\CacheConfiguration();
$cacheConfig->setDefaultCache(new \Doctrine\Common\Cache\RedisCache(
(new \Redis())->connect('127.0.0.1', 6379)
));
$config->setSecondLevelCacheConfiguration($cacheConfig);
$entityManager = \Doctrine\ORM\EntityManager::create($connection, $config);
In a Symfony project the same settings live under doctrine.orm.second_level_cache and doctrine.orm.second_level_cache_driver (exact keys depend on the DoctrineBundle version; consult its documentation).
Worked example: caching a User entity
Assume the User entity is mapped for caching (e.g., @ORM\Cache(usage="READ_ONLY", region="user")). The repository call:
$user = $entityManager->find('App\\Entity\\User', 42);
On the first request Doctrine executes a SELECT and stores the hydrated object in the user region. On the next nine requests the same find() returns the cached instance and the SQL logger shows zero additional queries for that ID. Enable Doctrine’s SQL logger ($config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger())) to verify the query count.
Invalidation: the mandatory manual step
If a background job updates the same row with raw SQL, the cache still holds the old entity. Doctrine does not detect external writes. The usual pattern is to evict the entry in a Doctrine lifecycle listener:
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Cache\DefaultCacheFactory;
class UserCacheInvalidator {
private $cacheFactory;
public function __construct(DefaultCacheFactory $factory) { $this->cacheFactory = $factory; }
public function postUpdate(LifecycleEventArgs $args): void {
$entity = $args->getObject();
if ($entity instanceof \App\Entity\User) {
$cache = $this->cacheFactory->getRegion('user');
$cache->evict($entity->getId());
}
}
}
Register the listener in your configuration so it runs after every persist/flush that touches a User. For raw‑SQL paths you must call the same eviction logic explicitly after the statement executes.
Limitations and practical checks
- Driver scope:
apcuis isolated per PHP‑FPM worker; in a load‑balanced setup each node has its own cache, leading to divergence. Useredis(or Memcached) for multi‑node deployments. - Stale data risk: Any write that bypasses Doctrine (raw SQL, external services, direct DB admin tools) requires manual eviction. There is no automatic TTL‑based invalidation built into the second‑level cache.
- Version dependency: Confirm Doctrine ORM ≥ 2.6; older releases lack the
CacheConfigurationAPI used above. - Memory pressure: APCu and Redis have finite memory. Monitor eviction rates and set appropriate
maxmemory-policyon Redis.
To confirm the cache is active and effective:
- Check configuration:
grep -R "second_level_cache" config/packages/doctrine.yaml(or your config format). Expect a line enabling the cache. - Enable SQL logging and hit a read‑heavy endpoint 10 times. The log should show a single
SELECTfor the cached entity. - Inspect the driver: for Redis run
redis-cli KEYS 'doctrine:*'after the first load; keys should appear. For APCu callapcu_cache_info()from a script executed by the same web‑server user.
Closing checklist
- Enable the second‑level cache in a staging environment first, using the
arraydriver to validate mappings without persisting data. - Map only read‑heavy, rarely‑changed entities to cache regions.
- Run a benchmark (e.g.,
wrk -t4 -c100 -d30s http://staging/endpoint) before and after enabling the cache; look for a drop in average DB queries per request. - Add lifecycle listeners (or explicit eviction calls) for every write path that touches cached entities, including raw‑SQL scripts.
- Deploy with
redisin production, configure monitoring (Redis INFOkeyspace_hits/keyspace_misses) and alert on a sudden hit‑rate drop, which often signals stale‑data incidents.