What to cache and how.
THE CANDIDATES
Expensive query results Rendered template fragments External API responses Computed values used repeatedly Configuration assembled at runtime
WHERE TO STORE IT
File-based caching works on shared hosting and needs nothing installed Redis or Memcached, where available, are faster The database, which is slower but simpler
THE PATTERN
Check the cache. If present, return it. If not, compute, store, and return.
INVALIDATION
When the underlying data changes, clear the relevant cache entry. Clearing everything on every change defeats the purpose.
Tag or key cache entries so you can clear precisely.
TIME-BASED EXPIRY
Simpler than event-based invalidation and usually sufficient. Set an expiry appropriate to how stale the data may acceptably be.
WHAT NOT TO CACHE
Anything specific to one visitor, unless the cache key includes their identity.
Serving one visitor's cached data to another is the most serious caching error and it happens regularly.
MEASURING
Cache something, measure, and keep it if it helped. Cache hit rates tell you whether it is working.