Redis & Advanced Caching

Introduction to Redis

20 min Lesson 2 of 30

What is Redis?

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store that can be used as a database, cache, message broker, and streaming engine. It supports various data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes.

Key Feature: Redis stores all data in RAM (Random Access Memory), making it extremely fast - capable of handling millions of operations per second with sub-millisecond latency.

In-Memory Data Store

Unlike traditional databases that store data on disk, Redis keeps everything in memory. This fundamental design choice provides:

  • Speed: RAM access is ~100,000x faster than disk access
  • Simplicity: Simple key-value model with rich data structures
  • Atomic Operations: All Redis operations are atomic by default
  • Persistence Options: Can save snapshots to disk for durability
// Speed comparison\nDisk Access: ~10ms (10,000 microseconds)\nSSD Access: ~0.1ms (100 microseconds)\nRAM Access: ~0.0001ms (0.1 microseconds)\n\nRedis can perform 100,000+ operations per second on modest hardware!

Redis vs Memcached

Both are popular in-memory caching solutions, but Redis offers significantly more features:

FeatureRedisMemcached
Data StructuresStrings, Lists, Sets, Hashes, Sorted Sets, etc.Only strings
PersistenceRDB snapshots, AOF logsNone
ReplicationMaster-slave replicationNone
ClusteringRedis Cluster built-inClient-side sharding
Pub/SubYesNo
Lua ScriptingYesNo
When to Use Redis: Choose Redis for its rich data structures, persistence, and pub/sub features. Choose Memcached only if you need simple string caching with multiple threads.

Redis Use Cases

Redis excels in many scenarios beyond simple caching:

  1. Session Storage: Store user sessions with automatic expiration
  2. Real-Time Analytics: Count page views, clicks, and events in real-time
  3. Leaderboards: Use sorted sets for gaming scores and rankings
  4. Rate Limiting: Track API requests per user/IP with counters
  5. Queue Systems: Job queues using lists (Laravel queues can use Redis)
  6. Pub/Sub Messaging: Real-time chat, notifications, broadcasting
  7. Geospatial Data: Store and query location-based data
  8. Full-Page Caching: Cache entire HTML pages for ultra-fast delivery
// Laravel session configuration using Redis\n// config/session.php\n'driver' => 'redis',\n'connection' => 'session',\n\n// Laravel queue configuration using Redis\n// config/queue.php\n'default' => 'redis',

Installing Redis

Redis installation varies by operating system:

// Ubuntu/Debian\nsudo apt update\nsudo apt install redis-server\nsudo systemctl start redis-server\nsudo systemctl enable redis-server\n\n// macOS (using Homebrew)\nbrew install redis\nbrew services start redis\n\n// Windows (using WSL or Docker)\ndocker run -d -p 6379:6379 --name redis redis:latest\n\n// Verify installation\nredis-cli ping\n// Should return: PONG
Default Port: Redis runs on port 6379 by default. The server listens on localhost (127.0.0.1) and requires no authentication in default configuration (change this in production!).

Redis CLI Basics

The redis-cli (command-line interface) is the primary tool for interacting with Redis:

// Start redis-cli\nredis-cli\n\n// Basic commands\n127.0.0.1:6379> SET mykey "Hello Redis"\nOK\n\n127.0.0.1:6379> GET mykey\n"Hello Redis"\n\n127.0.0.1:6379> EXISTS mykey\n(integer) 1\n\n127.0.0.1:6379> DEL mykey\n(integer) 1\n\n127.0.0.1:6379> GET mykey\n(nil)\n\n// Check server info\n127.0.0.1:6379> INFO\n// Returns detailed server statistics\n\n// Exit redis-cli\n127.0.0.1:6379> QUIT

Redis Data Model

Redis is fundamentally a key-value store where:

  • Keys: Binary-safe strings (can contain any data, max 512 MB)
  • Values: One of several data structures (strings, lists, sets, etc.)
  • Namespace: Use colons for hierarchical keys: user:1000:sessions
// Key naming conventions (best practices)\nuser:1000:profile // User profile data\nuser:1000:sessions // User sessions\nproduct:5000:views // Product view count\ncache:homepage:en // Cached homepage (English)\nqueue:emails:pending // Email queue\nrate_limit:api:192.168.1.1 // Rate limit for IP
Key Design: Use descriptive, hierarchical key names with colons. Include object type, ID, and attribute for clarity. Example: object:id:attribute

Redis Persistence

While Redis is an in-memory database, it offers two persistence mechanisms:

1. RDB (Redis Database) Snapshots

Point-in-time snapshots of your dataset at specified intervals. Fast and compact.

// RDB configuration in redis.conf\nsave 900 1 // Save if 1 key changed in 900 seconds\nsave 300 10 // Save if 10 keys changed in 300 seconds\nsave 60 10000 // Save if 10000 keys changed in 60 seconds

2. AOF (Append Only File)

Logs every write operation. More durable but slower and larger files.

// AOF configuration in redis.conf\nappendonly yes\nappendfsync everysec // Sync to disk every second
Durability vs Speed: Persistence comes at a performance cost. For pure caching (where data loss is acceptable), disable persistence. For critical data, enable AOF with fsync.

Redis Security Basics

By default, Redis has no authentication. For production environments:

// Set password in redis.conf\nrequirepass your_strong_password_here\n\n// Bind to specific interface (don't expose to internet!)\nbind 127.0.0.1\n\n// Rename dangerous commands\nrename-command FLUSHDB ""\nrename-command FLUSHALL ""\nrename-command CONFIG "CONFIG_abc123"

Installing Redis PHP Extension

To use Redis with PHP/Laravel, install the PHP Redis extension or use Predis:

// Option 1: PhpRedis (faster, C extension)\nsudo pecl install redis\n// Add to php.ini: extension=redis.so\n\n// Option 2: Predis (pure PHP, no compilation)\ncomposer require predis/predis\n\n// Laravel configuration (config/database.php)\n'redis' => [\n 'client' => env('REDIS_CLIENT', 'phpredis'),\n 'default' => [\n 'host' => env('REDIS_HOST', '127.0.0.1'),\n 'password' => env('REDIS_PASSWORD', null),\n 'port' => env('REDIS_PORT', 6379),\n 'database' => 0,\n ],\n];
Exercise: Install Redis on your development machine and complete these tasks:
  1. Start the Redis server and connect with redis-cli
  2. Execute the PING command to verify the connection
  3. Set a key "myname" with your name as the value
  4. Retrieve the value using GET
  5. Delete the key and confirm it's gone
  6. Run the INFO command and note the Redis version

In the next lesson, we'll explore Redis strings - the most basic and versatile data type in Redis.