0
0
RedisHow-ToBeginner · 4 min read

How to Implement Caching with Redis: Simple Guide

To implement caching with Redis, store frequently accessed data using SET with an expiration time via EXPIRE or SETEX. Retrieve cached data using GET, and if missing, fetch from the original source and update the cache.
📐

Syntax

Redis caching mainly uses these commands:

  • SET key value [EX seconds]: Stores a value with an optional expiration time in seconds.
  • GET key: Retrieves the value stored at the key.
  • DEL key: Deletes the cached key.
  • EXPIRE key seconds: Sets or updates the expiration time for a key.

Use SETEX key seconds value as a shortcut to set a value with expiration.

redis
SET user:123 "John Doe" EX 3600
GET user:123
DEL user:123
EXPIRE user:123 1800
SETEX user:123 3600 "John Doe"
💻

Example

This example shows caching a user profile in Redis with a 1-hour expiration. If the cache misses, it simulates fetching from a database and updates Redis.

python
import redis

# Connect to Redis server
r = redis.Redis(host='localhost', port=6379, db=0)

user_id = '123'
cache_key = f'user:{user_id}'

# Try to get cached data
cached_user = r.get(cache_key)

if cached_user:
    print('Cache hit:', cached_user.decode())
else:
    # Simulate database fetch
    user_profile = 'John Doe'
    print('Cache miss, fetching from DB:', user_profile)
    # Cache the data with 1 hour expiration
    r.setex(cache_key, 3600, user_profile)
Output
Cache miss, fetching from DB: John Doe
⚠️

Common Pitfalls

Common mistakes when using Redis caching include:

  • Not setting expiration, causing stale data to persist indefinitely.
  • Ignoring cache misses and not updating the cache after fetching fresh data.
  • Using overly large values that can slow Redis performance.
  • Not handling Redis connection errors gracefully.

Always set sensible expiration times and handle cache misses properly.

redis
Wrong way (no expiration):
SET user:123 "John Doe"

Right way (with expiration):
SETEX user:123 3600 "John Doe"
📊

Quick Reference

CommandDescriptionExample
SETStore a key-value pairSET user:1 "Alice"
GETRetrieve value by keyGET user:1
SETEXSet key with expirationSETEX user:1 3600 "Alice"
EXPIRESet expiration on existing keyEXPIRE user:1 1800
DELDelete a keyDEL user:1

Key Takeaways

Use SETEX or SET with EX option to store cached data with expiration.
Always handle cache misses by fetching fresh data and updating Redis.
Set appropriate expiration times to avoid stale data.
Keep cached values small and simple for better Redis performance.
Handle Redis connection errors to maintain application stability.