Caching Basics
What Caching Solves
Caching reduces repeated work: DB queries, rendering, expensive computations. Done right, it improves latency and reduces load. Done wrong, it serves stale data or creates hard-to-debug behavior.
What to Cache
Good candidates: read-heavy data (categories), computed results, rendered fragments, and expensive API calls. Avoid caching user-specific sensitive responses unless you understand the scope.
Simple In-memory Cache (Educational)
This shows the concept. In production you might use Redis or APCu depending on environment.
<?php
$cache = [];
function cacheGet(array $cache, string $key): ?string {
return $cache[$key] ?? null;
}
function cacheSet(array &$cache, string $key, string $value): void {
$cache[$key] = $value;
}
TTL and Cache Keys
Use stable keys and explicit TTL. Keys must include parameters that change the result (page, language, filters).
<?php $key = "items:page=" . (int)($_GET["page"] ?? 1) . ":lang=php"; $ttlSeconds = 60;
Stampede Control (Baseline)
Cache stampede happens when many requests miss at the same time and all recompute. A basic mitigation is short TTLs + jitter and optionally a lock in shared cache.
<?php $ttl = 60; $jitter = random_int(0, 10); $effectiveTtl = $ttl + $jitter;
Production Tip
Plan invalidation: time-based TTL is simplest, event-based invalidation is harder but more correct. Start with small TTL + observability, then evolve to Redis cache with clear key strategy.