← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Redis

performance PHP 7.0+ Beginner

Also Known As

Redis phpredis Predis redis cache Redis queue in-memory cache

TL;DR

An in-memory key-value data store used in PHP applications for caching, session storage, queues, rate limiting, and pub/sub — providing sub-millisecond data access compared to database queries.

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

Redis data is durable by default. Redis is an in-memory store — without persistence configuration, all data is lost if the Redis process restarts or the server reboots. For session storage and cache, this is usually acceptable (users are logged out, cache is cold). For queue data or any data that must survive restarts, configure Redis persistence: RDB for periodic snapshots, AOF for append-only journaling, or both. Redis Cluster provides replication for high availability.

Why It Matters

Redis is the highest-ROI infrastructure addition for most PHP applications. Caching database query results in Redis reduces response times from 200–500ms to under 10ms for cache hits. Using Redis for PHP sessions allows horizontal scaling across multiple servers (file-based sessions are server-specific). Redis-backed queues with Laravel Horizon provide real-time job monitoring and automatic retry. For PHP applications that have outgrown a single server or need faster response times, Redis addresses multiple problems with one tool.

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

✗ Vulnerable
// 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
✓ Fixed
// 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;
}

Added 23 Mar 2026
Edited 5 Apr 2026
Views 26
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Amazonbot 6 Perplexity 6 Google 2 ChatGPT 1 Meta AI 1 Ahrefs 1
crawler 16 crawler_json 1
DEV INTEL Tools & Severity
🔵 Info ⚙ Fix effort: Low
⚡ Quick Fix
Use phpredis extension for best performance; always set TTL with SETEX or EXPIRE; wrap Redis calls in try/catch with database fallback; use Redis::pipeline() for multiple operations
📦 Applies To
PHP 7.0+ web cli

✓ schema.org compliant