The Sticky Notes Analogy
Your desk has two places to store information:
- Filing cabinet (database): Organized, permanent, slow to find things
- Sticky notes (Redis): Right in front of you, instant access, temporary
Redis is like putting the most important info on sticky notes. It stores data in memory for lightning-fast access, while your main database handles permanent storage.
Why Redis Is So Fast
Memory vs Disk
Database (disk):
1. Find file on disk
2. Read from slow spinning/flash storage
3. Return data
Time: ~10-20 milliseconds
Redis (memory):
1. Look up in RAM
Time: ~0.1 milliseconds
That's 100-200x faster!
The Trade-off
Memory: Fast but limited and volatile
Disk: Slow but abundant and persistent
Redis chooses SPEED for data that needs it.
What Redis Stores
Key-Value Pairs
Everything in Redis is a key pointing to a value:
SET user:123 "Alice"
GET user:123 → "Alice"
Key: user:123
Value: "Alice"
Data Structures
Redis isn't just strings. It supports rich data types:
| Type | Description | Example Use |
|---|---|---|
| String | Text, numbers, binary | Cache, counters |
| List | Ordered collection | Message queues |
| Set | Unique values | Tags, followers |
| Sorted Set | Ordered by score | Leaderboards |
| Hash | Field-value pairs | User profiles |
| Stream | Append-only log | Event streams |
Common Use Cases
1. Caching
Without cache:
User requests page
→ Query database (slow)
→ Return response
With Redis cache:
User requests page
→ Check Redis (instant!)
→ Cache hit? Return immediately
→ Cache miss? Query DB, store in Redis, return
First request: Same speed
Next 1000 requests: 100x faster!
2. Session Storage
User logs in:
Store session in Redis
session:abc123 → { userId: 5, name: "Alice" }
User makes requests:
Check Redis for session (microseconds)
No database query needed!
Benefits:
- Fast session lookups
- Stateless app servers
- Easy to scale
3. Rate Limiting
Allow 100 API calls per minute per user:
User makes request:
INCR api:user:123:minute
If count > 100:
Return "Too many requests"
Else:
Process request
Redis TTL auto-clears counters after 1 minute.
4. Leaderboards
Sorted Sets perfect for rankings:
ZADD leaderboard 100 "Alice"
ZADD leaderboard 85 "Bob"
ZADD leaderboard 95 "Carol"
ZREVRANGE leaderboard 0 2
→ ["Alice", "Carol", "Bob"]
Scores automatically sort players!
5. Pub/Sub (Real-Time Messaging)
Publisher:
PUBLISH chat:room1 "Hello everyone!"
Subscribers (all receive instantly):
SUBSCRIBE chat:room1
→ "Hello everyone!"
Used for: Chat, notifications, live updates
6. Message Queues
Producer adds tasks:
LPUSH job:queue "process_video:123"
LPUSH job:queue "send_email:456"
Workers consume tasks:
BRPOP job:queue
→ "process_video:123" (removed from queue)
Expiration (TTL)
Auto-Cleanup
SET cache:weather "sunny"
EXPIRE cache:weather <seconds>
After the TTL expires: the key disappears automatically!
Or combine:
SETEX cache:weather <seconds> "sunny"
Why TTL Matters
Cache fresh data:
Set TTL to refresh interval
Session timeout:
Expire inactive sessions
Rate limits:
Auto-reset counters
Persistence Options
Redis CAN Persist Data
Option 1: RDB (Snapshots)
Dump memory to disk periodically
Fast recovery, possible data loss
Option 2: AOF (Append Only File)
Log every write operation
Slower, minimal data loss
Option 3: Both
Best durability, higher disk usage
When to Enable Persistence
Pure cache: No persistence needed
(Can rebuild from source database)
Session store: AOF recommended
(Don't want users to re-login)
Primary database: Both RDB + AOF
(Need durability guarantees)
Redis Clustering
Scaling Beyond One Server
Single Redis: Limited by one machine's RAM
Redis Cluster: Data spread across multiple nodes
Key → Hash → Node
user:123 → Node 1
user:456 → Node 2
user:789 → Node 3
Replication
Master: Handles writes
Replicas: Handle reads, take over if master fails
Master → Write
↓ Sync
Replica 1 → Read
Replica 2 → Read
Redis vs Other Solutions
| Feature | Redis | Memcached | Database |
|---|---|---|---|
| Speed | ⚡ Ultra-fast | ⚡ Ultra-fast | Slow |
| Data structures | Rich | Only strings | Rich |
| Persistence | Optional | No | Yes |
| Pub/Sub | Yes | No | Limited |
| Clustering | Yes | Yes | Varies |
When to Use Redis
✓ Need sub-millisecond latency
✓ Caching database results
✓ Session management
✓ Real-time features
✓ Leaderboards, counters, rate limits
When NOT to Use Redis
✗ Primary data store (usually)
✗ Large data that won't fit in RAM
✗ Complex queries (use SQL database)
✗ Strong consistency requirements
Common Patterns
Cache-Aside
1. Check Redis for data
2. If not found, query database
3. Store result in Redis
4. Return data
Most common pattern!
Write-Through
1. Write to Redis AND database together
2. Read from Redis
Helps keep cache current.
Write-Behind
1. Write to Redis immediately
2. Async write to database later
Faster writes, eventual consistency.
Common Mistakes
1. Using Redis as Primary Database
Redis is cache-first. Have a persistent database as source of truth.
2. Not Setting TTLs
Memory fills up! Expire cached data appropriately.
3. Storing Too Much Data
If data doesn't fit in RAM, Redis slows dramatically. Cache selectively.
4. Ignoring Persistence for Important Data
Sessions, rate limits - these should persist through restarts.
FAQ
Q: Is Redis a database?
It's often called a "data structure store." It CAN be used as a database with persistence, but it's primarily used as a cache.
Q: What happens if Redis crashes?
Without persistence: all data lost. With persistence: recovers from last snapshot/log.
Q: How much data can Redis handle?
Limited by RAM. A single instance can handle millions of keys easily if they fit in memory.
Q: Redis vs Memcached?
Redis: more features (data structures, persistence, pub/sub). Memcached: simpler, slightly faster for pure string caching.
Summary
Redis is an in-memory data store that provides lightning-fast access to frequently needed data.
Key Takeaways:
- In-memory = 100-200x faster than disk
- Rich data structures: strings, lists, sets, sorted sets, hashes
- TTL for automatic expiration
- Common uses: caching, sessions, rate limiting, leaderboards
- Persistence optional (RDB/AOF)
- Not a replacement for your database - works alongside it
Redis is the sticky notes on your desk - instant access to what you need most!
Related Concepts
Leave a Comment
Comments (0)
Be the first to comment on this concept.
Comments are approved automatically.