Redis
Also Known As
TL;DR
Explanation
Redis (Remote Dictionary Server) is a single-threaded in-memory data structure server supporting strings, hashes, lists, sets, sorted sets, streams, and geospatial indexes. In PHP, Redis is accessed via the phpredis C extension (fastest) or Predis (pure PHP, no compilation required). Common PHP use cases: caching (SETEX key value ttl); session storage (configure session handler to use Redis for multi-server deployments); queue backend (Laravel Queue, Horizon); rate limiting (INCR + EXPIRE for atomic counter); pub/sub (real-time notifications via PUBLISH/SUBSCRIBE); leaderboards (sorted sets). Redis data is in-memory — it is fast but limited by RAM and loses data on restart unless persistence is configured (RDB snapshots or AOF append-only file). For PHP, Redis is typically the first infrastructure component added after a relational database, providing caching and session handling with minimal operational complexity.
Common Misconception
Why It Matters
Common Mistakes
- Not setting TTLs on cached keys — keys without expiry accumulate indefinitely and exhaust Redis memory.
- Using Redis as a primary database — Redis is a cache and auxiliary store, not a replacement for a relational database; it lacks ACID transactions and relational queries.
- Not handling Redis connection failures gracefully — if Redis goes down, every request that depends on it should fall back to the database, not throw a 500 error.
- Storing large objects in Redis — serialising and deserialising large PHP objects is slow; store only the data needed for display, not full Eloquent model graphs.
Code Examples
// No TTL — keys accumulate forever, exhausting memory
$redis->set('user:' . $id, serialize($user));
// No fallback — 500 error if Redis is down
$data = unserialize($redis->get('expensive_query'));
return $data; // null if Redis down = broken page
// TTL set, fallback to database if cache miss or Redis failure
function getCachedUser(int $id, PDO $db): array {
$key = 'user:' . $id;
try {
$cached = $redis->get($key);
if ($cached) return json_decode($cached, true);
} catch (RedisException $e) {
// Redis unavailable — fall through to database
logger()->warning('Redis unavailable: ' . $e->getMessage());
}
// Database fallback
$user = $db->query('SELECT * FROM users WHERE id = ?', [$id])->fetch();
try {
$redis->setex($key, 300, json_encode($user)); // 5 min TTL
} catch (RedisException) { /* ignore cache write failure */ }
return $user;
}