0

Job middleware — rate limiting, preventing overlaps

Advanced5 min read·lv-19-008

Concept

Caching stores the result of expensive operations so subsequent requests can retrieve it instantly. The right caching strategy dramatically reduces database load and response times.

Cache drivers:

  • file: Stores in storage/framework/cache/. Simple, no infrastructure needed. Doesn't share across servers.
  • database: Stores in cache table. Simple, shared across servers, slower than file.
  • redis: In-memory, extremely fast, shared across servers. The standard for production.
  • memcached: Similar to Redis, no persistence.
  • array: In-memory within a single PHP process. Disappears after request. Used in tests.
  • null: Disables caching. Useful in tests.

Cache tags: Group related cache entries and invalidate them together. Only supported by Redis and Memcached drivers.

cache() helper: cache($key) gets. cache([$key => $value], $ttl) sets. cache()->remember(...) is the most common usage.

Serialization: Cache stores serialized PHP values. Objects, arrays, models — all serializable. Eloquent models carry their loaded relationships when cached.

TTL (Time To Live): How long before the cache entry expires. In seconds or a DateInterval / Carbon instance. null = forever.

Atomic locks: Prevent cache stampedes and implement distributed mutexes. Cache::lock(string $name, int $seconds).

Code Example

php
<?php
use Illuminate\Support\Facades\Cache;

// Basic operations
Cache::put('greeting', 'Hello World', 3600);         // store for 1 hour
Cache::put('user:1', $user, now()->addDay());         // with Carbon
$value = Cache::get('greeting');                       // retrieve
$value = Cache::get('greeting', 'default');            // with default
Cache::has('greeting');                                // existence check
Cache::forget('greeting');                             // delete
Cache::flush();                                        // clear ALL cache (dangerous)

// forever / forgets
Cache::forever('config_checksum', $hash);              // no expiry
Cache::forget('config_checksum');                      // must manually delete

// remember — get or compute and store
$users = Cache::remember('active-users', 3600, function() {
    return User::where('active', true)->get();
});
// On first call: executes closure, stores result for 1 hour, returns it
// On subsequent calls within 1 hour: returns stored value (no DB query)

// rememberForever
$categories = Cache::rememberForever('categories', function() {
    return Category::all();
});

// Multiple operations
Cache::many(['key1', 'key2', 'key3']); // get multiple
Cache::putMany(['key1' => 'val1', 'key2' => 'val2'], 3600);

// increment/decrement (atomic)
Cache::increment('page_views');
Cache::increment('page_views', 5);
Cache::decrement('items_in_cart');

// pull — get and delete
$token = Cache::pull('verification_token_' . $userId); // get + forget in one op

// Cache tags — group and invalidate together (Redis/Memcached only)
Cache::tags(['users', 'admin'])->put('admin-users', $users, 3600);
Cache::tags(['users'])->get('admin-users');
Cache::tags(['users'])->flush(); // invalidate all 'users'-tagged cache