Redis Caching Strategies

matt
Matthew Gros · Dec 18, 2025

TLDR

Cache database queries, session data, and computed values. Set proper TTLs. Use Redis data structures appropriately.

Redis Caching Strategies

Redis is Fast

In-memory storage means microsecond responses.

Basic Operations

// String
Cache::put('user:123', $userData, 3600);
$user = Cache::get('user:123');

// Remember pattern
$posts = Cache::remember('posts:popular', 3600, function () {
    return Post::popular()->get();
});

What to Cache

  1. Database queries - Especially repeated ones
  2. API responses - From external services
  3. Computed values - Expensive calculations
  4. Session data - Faster than database

Cache Keys

Be consistent and descriptive:

"user:{$id}"
"user:{$id}:posts"
"posts:popular"
"posts:category:{$slug}:page:{$page}"

Invalidation

The hard part of caching:

// Clear specific key
Cache::forget('user:123');

// Clear pattern (with tags)
Cache::tags(['users'])->flush();

// Clear on model change
class User extends Model
{
    protected static function booted()
    {
        static::saved(fn($user) => Cache::forget("user:{$user->id}"));
    }
}

Redis Data Structures

More than just key-value:

// Lists (queues)
Redis::lpush('queue', $job);
Redis::rpop('queue');

// Sets (unique values)
Redis::sadd('online_users', $userId);
Redis::sismember('online_users', $userId);

// Sorted sets (leaderboards)
Redis::zadd('scores', $score, $userId);
Redis::zrevrange('scores', 0, 9);  // Top 10

TTL Strategy

  • User sessions: 1-24 hours
  • API responses: 5-60 minutes
  • Computed data: depends on freshness needs
  • Static content: long (hours/days)

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.