What is Redis and Why Use It with CodeIgniter 4?


Redis, which stands for Remote Dictionary Server, is an open-source, in-memory key-value store that supports various data structures like strings, hashes, lists, sets, and sorted sets. Unlike traditional relational databases that read from disk, Redis keeps all data in RAM, enabling sub-millisecond read and write operations with optional persistence to disk via RDB snapshots or AOF (Append-Only File) logging.


In CodeIgniter 4, using Redis as a cache driver offers several advantages over file-based or database caching:

  • Speed: Operations are sub-millisecond, perfect for caching query results, session data, API responses, or computed values.
  • Scalability: Handles high concurrency with ease and can be clustered across multiple nodes for distributed caching.
  • Flexibility: Supports advanced features like key expiration (TTL), atomic increment/decrement operations, pub/sub messaging, and Lua scripting.
  • Built-in Integration: CI4's caching library natively supports Redis, allowing you to switch cache drivers with a single configuration change — no code rewrites needed.
  • Memory Efficiency: Redis uses optimized data structures internally, consuming less memory than you might expect for large datasets.

Compared to other CI4 cache drivers like File (slow disk I/O), Memcached (no persistence, simpler data types), or Wincache (Windows-only), Redis provides the best balance of speed, features, and reliability for production applications. The trade-off is that Redis requires a running server process and either the phpredis C extension or the Predis PHP library.


When should you use Redis in CI4? Consider Redis caching when your application has database-heavy pages, repeated expensive computations, high API call volumes, or needs session storage that survives server restarts. Common real-world use cases include caching product listings on e-commerce sites, storing user session data, rate limiting API endpoints, and caching rendered HTML fragments.



How to Use Redis Cache in CodeIgniter 4: A Complete Guide with Code Examples

Table Of Content

1 Prerequisites for Setting Up Redis in CodeIgniter 4

Before integrating Redis with your CodeIgniter 4 application, ensure the following requirements are met:

  • CodeIgniter 4 Installation: Have a working CI4 project (v4.4 or newer recommended). You can set one up using Composer: composer create-project codeigniter4/appstarter.
  • Redis Server: Install Redis on your server.
    • For Ubuntu/Debian: sudo apt update && sudo apt install redis-server
    • Start Redis: sudo systemctl start redis and enable on boot: sudo systemctl enable redis
    • For macOS (Homebrew): brew install redis && brew services start redis
    • For Windows: Use WSL2 with Ubuntu, or download from the Redis Windows port.
  • PHP Extension or Library (choose one):
    • Option A — phpredis (recommended for performance): Install the phpredis C extension via PECL: pecl install redis, then add extension=redis to your php.ini. Restart your web server afterward.
    • Option B — Predis (easier setup, no compilation): Install via Composer: composer require predis/predis. Predis is a pure PHP library, so no system-level extension is needed — ideal for shared hosting.
  • PHP Version: CodeIgniter 4.4+ requires PHP 8.1 or higher. Ensure your PHP version is compatible with your chosen Redis library.

Verify your Redis installation by running redis-cli in your terminal and executing PING. You should receive a PONG response. You can also check the Redis version with redis-server --version.


Verify phpredis is loaded (if using Option A) by running: php -m | grep redis. If it outputs redis, the extension is active.

2 Introduction

In this step-by-step tutorial, we will set up Redis as the primary cache driver in a CodeIgniter 4 application. You will learn how to configure both phpredis and Predis handlers, build a practical controller that demonstrates caching database queries, implement cache invalidation, and inspect cache metadata for debugging.


By the end of this guide, you will be able to:

  • Install and configure Redis on your development server
  • Switch CI4's cache handler from file to Redis with one config change
  • Use get(), save(), delete(), and remember() methods effectively
  • Cache expensive database queries to reduce MySQL load
  • Clear specific keys or flush the entire cache programmatically
  • Debug cache behavior using metadata and cache info endpoints

This tutorial assumes you have a basic understanding of CodeIgniter 4, PHP, and MySQL. If you are new to CI4, check out our guide on How to Build a Simple Blog in CodeIgniter 4 with MySQL first.

3 Create / Install a Codeigniter 4 Project

First, make sure your computer has Composer installed. Use the following command to create a new CodeIgniter 4 project:

composer create-project codeigniter4/appstarter ci4-redis

Then, navigate to your project directory:

cd ci4-redis

After installation, copy the env file to .env and set your environment to development mode:


cp env .env

Open the .env file and update these lines:


# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development

# Database Configuration
database.default.hostname = localhost
database.default.database = ci4_redis_demo
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi

Setting the environment to development enables detailed error messages, which is helpful while building and testing your caching logic. For more details on CI4 project setup and performance tips, see our article on Boosting CodeIgniter 4 Performance and Page Speed.

4 Configure Redis Cache in CodeIgniter 4

Redis cache configuration in CodeIgniter 4 is managed through the file app/Config/Cache.php. CI4 supports two Redis handlers: redis (using the phpredis C extension) and predis (using the Predis PHP library).

Open app/Config/Cache.php and update the configuration:

    
        <?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Cache extends BaseConfig
{
    /**
     * Primary cache handler.
     * Use 'redis' for phpredis extension, 'predis' for Predis library.
     */
    public string $handler = 'redis';

    /**
     * Fallback handler if Redis is unavailable.
     */
    public string $backupHandler = 'file';

    /**
     * Cache key prefix to avoid collisions with other apps sharing the same Redis instance.
     */
    public string $prefix = 'ci4_';

    /**
     * Default Time-To-Live in seconds. Keys expire after this duration.
     */
    public int $ttl = 3600;

    /**
     * phpredis configuration
     */
    public array $redis = [
        'host'       => '127.0.0.1',
        'password'   => null,           // Set if Redis requires AUTH
        'port'       => 6379,
        'timeout'    => 2.5,            // Connection timeout in seconds
        'database'   => 0,              // Redis DB index (0-15)
    ];

    /**
     * Predis configuration (if using 'predis' handler)
     */
    public array $predis = [
        'scheme'   => 'tcp',
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'password' => null,
        'database' => 0,
    ];
}
    

Configuration Options Explained:

  • handler: Set to 'redis' if you installed phpredis, or 'predis' if you installed the Predis Composer package.
  • backupHandler: CI4 automatically falls back to this driver (e.g., file) if Redis becomes unavailable — a safety net for production.
  • prefix: All cache keys are prefixed with this string. Useful when multiple applications share one Redis instance to prevent key collisions.
  • host / port: Points to your Redis server. For Unix socket connections, use 'host' => '/var/run/redis/redis.sock' and set port to 0.
  • password: Required if your Redis server has requirepass set in redis.conf. Always set a password in production.
  • timeout: How long CI4 waits to establish a connection. Set lower (e.g., 1.0) in production to fail fast.
  • database: Redis supports 16 databases (0–15) by default. Use separate databases for cache, sessions, and queues to keep data isolated.

Performance Note: phpredis (the C extension) is approximately 3–5x faster than Predis for most operations because it runs as compiled native code. However, Predis requires zero compilation and works on shared hosting where you cannot install PHP extensions. Choose based on your hosting environment.


After saving this configuration, CI4's cache service (\Config\Services::cache()) will automatically connect to Redis when called.

5 Create a Controller

Create a new controller file at app/Controllers/CacheDemo.php with the following code:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\API\ResponseTrait;

class CacheDemo extends Controller
{
    use ResponseTrait;

    protected $cache;

    public function __construct()
    {
        // Load the cache service — uses the handler defined in Config/Cache.php
        $this->cache = \Config\Services::cache();
    }

    /**
     * Basic cache set/get demonstration.
     * First request generates and caches data; subsequent requests serve from Redis.
     */
    public function index()
    {
        $key = 'demo_greeting';

        // Attempt to retrieve from cache
        $greeting = $this->cache->get($key);

        if ($greeting === null) {
            // Cache MISS — generate fresh data
            $greeting = 'Hello from Redis Cache! Generated at: ' . date('Y-m-d H:i:s');

            // Store in Redis with a 5-minute TTL (300 seconds)
            $this->cache->save($key, $greeting, 300);

            $status = 'Cache MISS — Data freshly generated and cached!';
        } else {
            // Cache HIT — served from Redis
            $status = 'Cache HIT — Served from Redis!';
        }

        return $this->respond([
            'status'   => $status,
            'greeting' => $greeting,
            'metadata' => $this->cache->getMetadata($key),
        ]);
    }

    /**
     * Cache an expensive database query using the remember() helper.
     * remember() checks cache first; if empty, executes the callback and stores the result.
     */
    public function users()
    {
        $key = 'cached_users_list';

        $users = $this->cache->remember($key, 600, function () {
            // This closure only runs on cache MISS
            $db = db_connect();
            $query = $db->table('users')->limit(20)->get();
            $result = $query->getResultArray();

            return [
                'data'       => $result,
                'cached_at'  => date('Y-m-d H:i:s'),
                'source'     => 'database',
            ];
        });

        // After remember(), this always runs — override to indicate cache source
        $users['served_from'] = 'redis_cache';

        return $this->respond($users);
    }

    /**
     * Invalidate (delete) specific cache keys or flush all cached data.
     * Call this after data updates to ensure users see fresh content.
     */
    public function clear(string $type = 'all')
    {
        switch ($type) {
            case 'greeting':
                $this->cache->delete('demo_greeting');
                return $this->respond(['message' => 'Greeting cache cleared successfully.']);

            case 'users':
                $this->cache->delete('cached_users_list');
                return $this->respond(['message' => 'Users cache cleared successfully.']);

            default:
                // Flush ALL keys with the configured prefix
                $this->cache->clean();
                return $this->respond(['message' => 'All Redis cache cleared successfully.']);
        }
    }

    /**
     * Display cache handler info and key metadata (useful for debugging).
     */
    public function info()
    {
        return $this->respond([
            'cache_handler'      => get_class($this->cache),
            'cache_info'         => $this->cache->getCacheInfo(),
            'greeting_metadata'  => $this->cache->getMetadata('demo_greeting'),
            'users_metadata'     => $this->cache->getMetadata('cached_users_list'),
        ]);
    }
}

Code Breakdown:

  • Constructor: Loads CI4's cache service, which connects to Redis using the settings defined in Config/Cache.php.
  • index() Method: Demonstrates the basic cache-aside pattern — check cache first, generate on miss, serve on hit. This is the most common caching strategy.
  • users() Method: Uses remember(), a convenient wrapper that combines get, callback execution, and save into one call. The closure only executes when the cache key is missing or expired.
  • clear() Method: Shows three invalidation strategies — delete a single key, delete a specific key, or flush all cached data. Always invalidate relevant keys when underlying data changes (e.g., after a database INSERT or UPDATE).
  • info() Method: Returns Redis server information and key metadata including TTL, expiration timestamps, and memory usage — invaluable for debugging cache behavior in development.

Important: Notice the controller does not use a closing ?> PHP tag. This follows the PSR-12 coding standard and prevents accidental whitespace issues that can break HTTP headers.


For a complete REST API implementation with CodeIgniter 4, you may also want to read our CodeIgniter 4 REST API CRUD Tutorial.

6 Add Routes: app/Config/Routes.php

Open app/Config/Routes.php and add these routes to map URLs to the CacheDemo controller methods:


$routes->get('cache', 'CacheDemo::index');           // Basic cache demo
$routes->get('cache/users', 'CacheDemo::users');     // DB query caching
$routes->get('cache/clear/(:segment)', 'CacheDemo::clear/$1');  // Invalidate cache
$routes->get('cache/info', 'CacheDemo::info');       // Debug cache info

The (:segment) placeholder captures the cache type parameter (e.g., greeting, users, or all) and passes it to the clear() method. If you are new to CodeIgniter routing, see our guide on building a blog in CI4 which covers routing fundamentals.

7 Create Dummy Table for Testing (Optional)

To test the users() method, create a simple users table in your database. Run the following SQL in phpMyAdmin or your MySQL client:


CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO users (name, email) VALUES
('John Doe', 'john@example.com'),
('Jane Smith', 'jane@example.com'),
('Bob Johnson', 'bob@example.com'),
('Alice Williams', 'alice@example.com'),
('Charlie Brown', 'charlie@example.com');

Make sure your .env database credentials match the database where this table exists. The users() controller method will query this table and cache the results in Redis for 10 minutes.

8.5 Common Issues & Troubleshooting

If you encounter problems connecting to Redis from CodeIgniter 4, here are the most common issues and their solutions:


"Unable to connect to Redis" Error:

  • Verify Redis is running: sudo systemctl status redis. If stopped, start it with sudo systemctl start redis.
  • Check that the host and port in Config/Cache.php match your Redis server (default: 127.0.0.1:6379).
  • If using a remote Redis server, ensure the firewall allows connections on port 6379 and that bind in redis.conf includes the server's IP.

"Class Redis not found" Error:

  • The phpredis extension is not installed or not enabled. Run php -m | grep redis to check. If missing, install it with pecl install redis and add extension=redis to php.ini.
  • Alternatively, switch to the predis handler and install via composer require predis/predis.

Cache Not Working (always returns null):

  • Check that $handler is set to 'redis' (not 'file') in Config/Cache.php.
  • Verify your Redis database index — if another application flushed database 0, your keys may have been deleted. Use a dedicated database index (e.g., 'database' => 2).
  • Check key expiration — if TTL is very short, data may expire before the next request. Increase TTL or verify with redis-cli TTL ci4_your_key.

Stale Data After Database Updates:

  • You must manually invalidate cache keys after modifying data. Call $this->cache->delete('your_key') in your update/delete controller methods.
  • For complex invalidation, use cache tags or key naming conventions (e.g., users_list_page_1) to target specific cached datasets.

8 Test Your Redis Cache

Start the CI4 development server:


php spark serve

Now visit these URLs in your browser to test each endpoint:

  • http://localhost:8080/cache
    First visit: Generates a greeting string and stores it in Redis (cache MISS)
    Subsequent visits (within 5 minutes): Returns the cached greeting instantly (cache HIT)
  • http://localhost:8080/cache/users
    → Fetches users from MySQL on first call, then serves from Redis for 10 minutes
  • http://localhost:8080/cache/info
    → Displays Redis handler class name, server info, and TTL metadata for each cached key
  • Clear specific caches:
    http://localhost:8080/cache/clear/greeting — Removes only the greeting key
    http://localhost:8080/cache/clear/users — Removes only the users list key
    http://localhost:8080/cache/clear/all — Flushes all cached keys with the configured prefix

Verify in Redis CLI: You can also confirm that keys are being stored by opening a terminal and running:


redis-cli
KEYS ci4_*

This command lists all keys with the ci4_ prefix, confirming that your CodeIgniter 4 application is successfully writing to Redis.

9 Conclusion

Redis Cache is one of the most effective and straightforward performance optimizations you can implement in CodeIgniter 4. With just a few configuration changes and CI4's clean caching API, you can dramatically reduce database load, improve response times, and handle significantly higher traffic volumes.


Key Takeaways from this tutorial:

  • Redis stores data in memory, making it orders of magnitude faster than file or database caching.
  • CI4 supports both phpredis (faster, requires C extension) and Predis (easier to install, pure PHP).
  • The remember() method simplifies the cache-aside pattern into a single, readable call.
  • Always invalidate relevant cache keys after data mutations (INSERT, UPDATE, DELETE) to prevent serving stale data.
  • Use the prefix and database config options to isolate cache data when sharing a Redis instance.

Best Practices for Production:

  • Always set a Redis requirepass password in production environments.
  • Configure maxmemory and maxmemory-policy (e.g., allkeys-lru) in redis.conf to prevent Redis from consuming all available RAM.
  • Monitor Redis with redis-cli INFO or tools like RedisInsight to track memory usage and hit/miss ratios.
  • Use CI4's backupHandler (set to file) so your application gracefully degrades if Redis goes down.

If you are building APIs, dashboards, or content-heavy platforms with CodeIgniter 4, Redis caching is no longer optional — it is essential for delivering a fast, reliable user experience at scale.


Related tutorials you might find useful:

Continue learning CodeIgniter 4 with these related tutorials from our site:

Revathi M - PHP and CodeIgniter Developer

Written by Revathi M

PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel

Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.

Frequently Asked Questions

Redis Cache in CodeIgniter 4 is an in-memory caching mechanism where CI4 uses Redis as its cache backend to store frequently accessed data such as database query results, computed values, and session data. Instead of hitting the database on every request, the application checks Redis first and serves data from memory, which is dramatically faster. CI4 provides native support for Redis through its Cache library, requiring only a configuration change in app/Config/Cache.php.

Yes, CodeIgniter 4 has built-in Redis cache support through its Cache library. You can choose between two handlers: the phpredis C extension (faster, requires server-level installation) or the Predis PHP library (installed via Composer, no compilation needed). Simply set the handler to "redis" or "predis" in app/Config/Cache.php, configure your Redis server details, and CI4 handles the rest.

Yes, Redis is significantly faster than file-based caching because it stores all data in RAM rather than reading from disk. While file cache involves disk I/O operations (which are slow, especially on shared hosting), Redis delivers sub-millisecond response times. For a typical web application, Redis can serve cached responses 10–100x faster than file-based caching, making a noticeable difference in page load times under moderate to heavy traffic.

Yes, database query results can be cached using Redis to reduce repeated database calls. In CodeIgniter 4, you can use the cache remember() method, which checks if a cached result exists for a given key. If the key is not found (cache miss), the callback function executes the database query, stores the result in Redis with a specified TTL, and returns it. On subsequent requests within the TTL window, the data is served directly from Redis without touching the database.

Cache duration (TTL) depends on how often your underlying data changes. For mostly static data like site settings or navigation menus, a TTL of 1–24 hours is appropriate. For moderately changing data like product listings or user profiles, 5–30 minutes works well. For frequently changing data like dashboard statistics, use shorter TTLs of 30 seconds to 5 minutes. Always implement cache invalidation (deleting keys after data updates) alongside TTL to ensure data freshness.