Redis with real implementation

Redis is an in-memory data store used as a cache, session store, message broker, rate limiter, and more. It’s super fast because data lives in RAM, supports many data types (strings, hashes, lists, sets, sorted sets), and provides primitives for atomic operations.

Vivek Rastogi

8/12/20252 min read

What is Redis?

Redis is an in-memory data store used as a cache, session store, message broker, rate limiter, and more. It’s super fast because data lives in RAM, supports many data types (strings, hashes, lists, sets, sorted sets), and provides primitives for atomic operations.

Why use Redis?
  • Extremely fast (in-memory reads/writes).

  • Rich data structures (hashes, lists, sets, sorted sets).

  • Atomic operations and primitives for locking, counters, rate-limits.

  • Lightweight and easy to deploy (Docker).

  • Excellent for caching, sessions, pub/sub, leaderboards, queues.

Disadvantages of Redis?
  • Memory cost: Limited by server RAM.

  • Persistence optional: May lose data if not configured for AOF or RDB.

  • Needs extra service: Must install/maintain Redis server.

Implementation
1. Install Redis Server

Windows

Linux

  • sudo apt update

  • sudo apt install redis-server -y

  • sudo systemctl enable redis-server

  • sudo systemctl start redis-server

    Check:

  • redis-cli ping

2. Install Predis for Laravel

Laravel works with phpredis (PHP extension) or predis (PHP package).
Predis is simpler — no server PHP config changes.

From Laravel root: composer require predis/predis

3. Configure Laravel for Redis

Edit .env:

  • CACHE_DRIVER=redis

  • SESSION_DRIVER=redis

  • QUEUE_CONNECTION=redis

  • REDIS_HOST=127.0.0.1

  • REDIS_PASSWORD=null

  • REDIS_PORT=6379

No change needed in config/database.php unless you use a different Redis DB or password.

4. Example — Cache an Expensive Query

routes/web.php:

How it works:

  • First request → fetched from DB, stored in Redis for 60 seconds.

  • Subsequent requests → served instantly from Redis.

5. Example — Rate Limiting API

Laravel’s throttle middleware automatically uses Redis when CACHE_DRIVER=redis.

routes/api.php:

Explanation:
  • Allows 5 requests per minute per IP.

  • Redis keeps a counter with TTL — if limit exceeded → HTTP 429.

6. Example — Direct Redis Commands

routes/web.php: