{
    "slug": "redis",
    "term": "Redis",
    "category": "performance",
    "difficulty": "beginner",
    "short": "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.",
    "long": "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.",
    "aliases": [
        "Redis",
        "phpredis",
        "Predis",
        "redis cache",
        "Redis queue",
        "in-memory cache"
    ],
    "tags": [
        "redis",
        "caching",
        "performance",
        "sessions",
        "queues",
        "php",
        "in-memory"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "caching_strategies",
        "php_sessions",
        "message_queue",
        "rate_limiting"
    ],
    "prerequisites": [],
    "refs": [
        "https://redis.io/docs/",
        "https://github.com/phpredis/phpredis"
    ],
    "bad_code": "// No TTL — keys accumulate forever, exhausting memory\n$redis->set('user:' . $id, serialize($user));\n\n// No fallback — 500 error if Redis is down\n$data = unserialize($redis->get('expensive_query'));\nreturn $data; // null if Redis down = broken page",
    "good_code": "// TTL set, fallback to database if cache miss or Redis failure\nfunction getCachedUser(int $id, PDO $db): array {\n    $key = 'user:' . $id;\n    try {\n        $cached = $redis->get($key);\n        if ($cached) return json_decode($cached, true);\n    } catch (RedisException $e) {\n        // Redis unavailable — fall through to database\n        logger()->warning('Redis unavailable: ' . $e->getMessage());\n    }\n    // Database fallback\n    $user = $db->query('SELECT * FROM users WHERE id = ?', [$id])->fetch();\n    try {\n        $redis->setex($key, 300, json_encode($user)); // 5 min TTL\n    } catch (RedisException) { /* ignore cache write failure */ }\n    return $user;\n}",
    "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",
    "severity": "info",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-04-05",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/redis",
        "html_url": "https://codeclaritylab.com/glossary/redis",
        "json_url": "https://codeclaritylab.com/glossary/redis.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Redis](https://codeclaritylab.com/glossary/redis) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/redis"
            }
        }
    }
}