Building a Redis Cache Layer for High-Traffic PHP Sites
A PHP site often starts with modest traffic, a responsive database, and room to deploy on a quiet Friday. Success changes the workload. Popular products draw repeated catalogue reads, crawlers revisit listings, and a campaign can send identical requests to MySQL.
Redis keeps frequently requested data in memory and removes repeated database work from the critical path. PHP can look up a cache key before opening a database connection, then reuse the stored response while it is acceptable. This cache-aside pattern is measurable and tolerant of brief stale data.
Australian sites face traffic in waves. EOFY sales, Black Friday, Christmas promotions, and Boxing Day create sharp peaks, while customers in Sydney, Melbourne, Brisbane, and Adelaide expect quick responses. Hosting region, data residency, and vendor support are local purchasing decisions, so the cache should fit Australian operating conditions.
The goal is to protect the database from expensive repeated reads without serving incorrect data. A dependable Redis layer needs explicit key rules, bounded expiry, safe invalidation, useful metrics, and a deliberate fallback when the cache is unavailable.
Choose the right caching strategy
Separate the layers before choosing Redis. A CDN can serve static assets or whole pages, OPcache stores compiled PHP bytecode, and Redis can hold product records, rendered fragments, or calculated prices. A CDN cannot remove an expensive origin query when every request still reaches PHP.
For dynamic pages, cache-aside is usually the best starting point. PHP reads Redis first, queries MySQL on a miss, writes the result with a time-to-live, and returns it. Read-through and write-through caches offer more automation, but they add another data path that must be operated and tested.
My infrastructure and systems notes on Karl Katzke's Blog reflect this cache-aside-first approach. Keep Redis for cacheable application data rather than mixing it indiscriminately with queues, locks, or PHP session state.
Design reliable keys and expiry policies
Use namespaced, deterministic keys such as au:product:1842:v3, including tenant, locale, currency, and representation version where they affect the response. A version lets you invalidate a family of entries without scanning Redis. On Redis Cluster, use hash tags deliberately so related keys share a slot without concentrating every key on one shard.
Choose a time-to-live from the business tolerance for stale data. A catalogue description may tolerate ten minutes; a stock reservation may need seconds or an event-driven delete. Add jitter to TTLs so popular entries do not expire together, and record the reason for every expiry policy.
Schedule wall-clock jobs around Australia’s daylight-saving changes. AEST and AEDT alter local midnight and cron timing, although Redis TTLs remain elapsed-time based. A nightly catalogue warm in Sydney should use the correct Australian timezone and be tested across October and April clock changes.
Connect Redis to the PHP request path
Use PhpRedis for PHP-FPM when its C implementation suits your platform, or Predis when a pure-PHP client is easier to manage. Set short connection and command timeouts, reuse connections sensibly, and monitor client numbers. A cache call that exceeds the page latency budget is failing its purpose.
On a hit, decode and return the value. On a miss, query MySQL with a prepared statement, encode the result, and write it to Redis with an expiry. Use JSON unless you control both ends of the serialisation boundary; unserialising untrusted PHP data creates object-injection risks.
Cache warming deserves the same discipline as preparing stock before customers arrive. The experience of starting a honey business in Zambia illustrates how equipment, storage, and repeatable production make demand easier to serve. Warming popular catalogue and route keys ahead of a campaign follows the same operational pattern.
Prevent stampedes and cascading failures
When a popular key expires, a thundering herd can form, with every request waiting for the same slow query. For expensive misses, use a short distributed lock: one worker rebuilds the value while others serve stale data or receive a controlled retry. Give each lock a random owner token and release it atomically only if that token matches.
Soft and hard expiry periods provide another option. The soft period serves an older value while one worker refreshes it; the hard period removes stale data when it is no longer acceptable. This stale-while-revalidate approach reduces load, but it needs clear maximum-age limits for sensitive records.
Treat Redis as an accelerator, not a mandatory dependency. Apply strict timeouts, use a circuit breaker, and let cache failures fall through to a protected database path with query budgets or rate limits. On a dedicated cache node, set a memory limit and an eviction policy so one traffic spike cannot consume all available RAM.
Measure cache behaviour in production
Track hits, misses, hit ratio, evictions, memory use, command latency, connections, lock contention, and the age of rebuilt values. Segment metrics by endpoint and key class, because an overall hit ratio can hide one expensive page causing most misses. Redis INFO, slow logs, and sampled application traces provide useful signals.
Database freshness matters too, since a cache can conceal replication delay. This guide to monitoring MySQL replication lag shows how Percona Monitoring and Management can expose lag that application dashboards might otherwise hide. Review cache age and replica lag together when investigating unexpected results.
Create alerts around sustained low hit ratio, rising evictions, memory saturation, elevated command latency, and stale values exceeding their agreed age. Record cache hits and misses in structured logs with a request identifier, allowing an operator to trace one slow request through PHP, Redis, and MySQL.
Secure and operate Redis for Australian workloads
Keep Redis on a private network, require authentication, encrypt client connections with TLS, and restrict access by security group or network policy. Rotate credentials and use least-privilege ACLs. A cache should never be exposed directly to the public internet, and sensitive session or personal data should not be mixed with disposable catalogue entries.
Choose a managed Redis service or region close to the PHP workers. Australian teams commonly evaluate Sydney and Melbourne for latency and local support, while Brisbane and Adelaide need a measured path to the nearest application tier. Confirm where backups and replicas sit, and check contractual data-residency requirements under the Australian Privacy Act rather than assuming a region label settles the issue.
Plan releases around the Australian retail calendar, including EOFY, Black Friday, Christmas, and Boxing Day. Compare managed Redis prices and egress charges in Australian dollars across AWS, Azure, and Google Cloud, including support and migration costs. Warm only keys with proven value, and keep a bypass switch ready for launch day.
Roll out with a practical checklist
Roll out gradually. Establish the uncached baseline, enable one read-heavy endpoint, compare response times and database load, then expand after checking correctness. A percentage rollout or feature flag makes rollback quick if hit rates, error rates, or stale-data complaints worsen.
The release checklist should make these decisions explicit:
- Record baseline latency, query volume, and database load for the target endpoint.
- Assign every key namespace a purpose, owner, TTL, and invalidation trigger.
- Test cold starts, warm starts, mass expiry, Redis restart, and database failure.
- Roll out by endpoint or traffic percentage with cache bypass and rollback controls.
- Define dashboards, alerts, incident ownership, and the conditions for flushing keys.
Pick the single most expensive read-only endpoint, instrument it, and build a small Redis cache around it today. Measure the result under normal traffic, rehearse the expiry surge, and expand only after the database and cache ownership are clear.
Karl Katzke