LaraflareDocsPackages13.x

Docs / Digging Deeper / Cache

Cache

Introduction

Some of the data retrieval or processing tasks performed by your application could be CPU intensive or take several seconds to complete. When this is the case, it is common to cache the retrieved data for a time so it can be retrieved quickly on subsequent requests for the same data. The cached data is usually stored in a very fast data store such as Redis or Workers KV.

Laraflare provides an expressive, unified API for various cache backends, allowing you to take advantage of their fast data retrieval and speed up your web application.

Configuration

Your application's cache configuration file is located at config/cache.ts. In this file, you may specify which cache store you would like to be used by default throughout your application. Laraflare supports Redis, Workers KV, relational databases, and filesystem disks out of the box. In addition, array and null cache drivers provide convenient cache backends for your automated tests.

The cache configuration file also contains a variety of other options that you may review. By default, Laraflare is configured to use the database cache driver, which stores the serialized, cached objects in your application's database. The default store is set by the CACHE_STORE environment variable.

Note

Workers have no filesystem, no memcached sockets and no APCu, and Laraflare does not include the AWS SDK. Laraflare therefore has no file, memcached, apc or dynamodb cache driver; a store that names one answers "Driver [x] is not supported." Use the database, kv or redis driver on a Worker, or add your own, as described in Adding Custom Cache Drivers.

Driver Prerequisites

Database

When using the database cache driver, you will need a database table to contain the cache data. Typically, this is included in the starter app's 0001_01_01_000001_create_cache_table.ts database migration; however, if your application does not contain this migration, you may use the make:cache-table Artisan command to create it:

npx artisan make:cache-table

npx artisan migrate

Workers KV

The kv cache driver stores cached values in a Workers KV namespace. Bind the namespace in wrangler.toml and name the binding with the KV_CACHE_BINDING environment variable (it defaults to CACHE). Atomic locks are not held in KV; they stay in the database's cache_locks table:

kv: {
  driver: 'kv' as const,
  binding: envString('KV_CACHE_BINDING', 'CACHE'),
  lock_table: 'cache_locks',
},

Redis

Before using a Redis cache with Laraflare, configure a Redis connection as described in Laraflare's Redis documentation, then add a store that uses the redis driver. The store's connection option names the Redis connection to use; it defaults to default:

redis: {
  driver: 'redis' as const,
  connection: 'default',
},

Storage

The storage cache driver allows you to store cached values on any of your application's configured filesystem disks. This can be useful when you want to use an existing disk, such as an S3 disk, as a key / value cache store:

storage: {
  driver: 'storage' as const,
  disk: envString('CACHE_STORAGE_DISK', ''),
  path: envString('CACHE_STORAGE_PATH', 'framework/cache/data'),
},

Cache Usage

Obtaining a Cache Instance

To obtain a cache store instance, you may use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying cache implementations. Every method that reads or writes the store is asynchronous and returns a promise:

import { Cache, Controller } from '@laraflare/framework';

export class UserController extends Controller {
  /**
   * Show a list of all users of the application.
   */
  async index() {
    const value = await Cache.get('key');

    return [
      // ...
    ];
  }
}

Accessing Multiple Cache Stores

Using the Cache facade, you may access various cache stores via the store method. The key passed to the store method should correspond to one of the stores listed in the stores object in your cache configuration file:

const value = await Cache.store('database').get('foo');

await Cache.store('redis').put('bar', 'baz', 600); // 10 Minutes

Retrieving Items From the Cache

The Cache facade's get method is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. If you wish, you may pass a second argument to the get method specifying the default value you wish to be returned if the item doesn't exist:

const value = await Cache.get('key');

const value = await Cache.get('key', 'default');

You may even pass a function as the default value. The result of the function will be returned if the specified item does not exist in the cache. Passing a function allows you to defer the retrieval of default values from a database or other external service:

const value = await Cache.get('key', () => DB.table(/* ... */).get());

Determining Item Existence

The has method may be used to determine if an item exists in the cache. This method will also return false if the item exists but its value is null:

if (await Cache.has('key')) {
  // ...
}

Incrementing / Decrementing Values

The increment and decrement methods may be used to adjust the value of integer items in the cache. Both of these methods accept an optional second argument indicating the amount by which to increment or decrement the item's value:

// Initialize the value if it does not exist...
await Cache.add('key', 0, now().plus({ hours: 4 }));

// Increment or decrement the value...
await Cache.increment('key');
await Cache.increment('key', amount);
await Cache.decrement('key');
await Cache.decrement('key', amount);

Retrieve and Store

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. For example, you may wish to retrieve all users from the cache or, if they don't exist, retrieve them from the database and add them to the cache. You may do this using the Cache.remember method:

const value = await Cache.remember('users', seconds, () => DB.table('users').get());

If the item does not exist in the cache, the function passed to the remember method will be executed and its result will be placed in the cache.

If you need to know whether the item was retrieved from the cache instead of by executing the given function, you may use the rememberWithWarmth method. This method returns an array containing the cached value and a boolean indicating whether the item was "warm", meaning it was retrieved from the cache and not resolved from the function:

const [value, warm] = await Cache.rememberWithWarmth('users', seconds, () => DB.table('users').get());

You may use the rememberForever method to retrieve an item from the cache or store it forever if it does not exist:

const value = await Cache.rememberForever('users', () => DB.table('users').get());

Stale While Revalidate

When using the Cache.remember method, some users may experience slow response times if the cached value has expired. For certain types of data, it can be useful to allow partially stale data to be served while the cached value is recalculated in the background, preventing some users from experiencing slow response times while cached values are calculated. This is often referred to as the "stale-while-revalidate" pattern, and the Cache.flexible method provides an implementation of this pattern.

The flexible method accepts an array that specifies how long the cached value is considered "fresh" and when it becomes "stale". The first value in the array represents the number of seconds the cache is considered fresh, while the second value defines how long it can be served as stale data before recalculation is necessary.

If a request is made within the fresh period (before the first value), the cache is returned immediately without recalculation. If a request is made during the stale period (between the two values), the stale value is served to the user, and a deferred function is registered to refresh the cached value after the response is sent to the user. If a request is made after the second value, the cache is considered expired, and the value is recalculated immediately, which may result in a slower response for the user:

const value = await Cache.flexible('users', [5, 10], () => DB.table('users').get());

Retrieve and Delete

If you need to retrieve an item from the cache and then delete the item, you may use the pull method. Like the get method, null will be returned if the item does not exist in the cache:

const value = await Cache.pull('key');

const value = await Cache.pull('key', 'default');

Storing Items in the Cache

You may use the put method on the Cache facade to store items in the cache:

await Cache.put('key', 'value', 10);

If the storage time is not passed to the put method, the item will be stored indefinitely:

await Cache.put('key', 'value');

Instead of passing the number of seconds as an integer, you may also pass a date instance representing the desired expiration time of the cached item:

await Cache.put('key', 'value', now().plus({ minutes: 10 }));

Store if Not Present

The add method will only add the item to the cache if it does not already exist in the cache store. The method will return true if the item is actually added to the cache. Otherwise, the method will return false. The add method is an atomic operation:

await Cache.add('key', 'value', seconds);

Extending Item Lifetime

The touch method allows you to extend the lifetime (TTL) of an existing cache item. The touch method will return true if the cache item exists and its expiration time was successfully extended. If the item does not exist in the cache, the method will return false:

await Cache.touch('key', 3600);

You may provide a date instance to specify an exact expiration time:

await Cache.touch('key', now().plus({ hours: 2 }));

Storing Items Forever

The forever method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the forget method:

await Cache.forever('key', 'value');

Removing Items From the Cache

You may remove items from the cache using the forget method:

await Cache.forget('key');

You may also remove items by providing a zero or negative number of expiration seconds:

await Cache.put('key', 'value', 0);

await Cache.put('key', 'value', -5);

You may clear the entire cache using the flush method:

await Cache.flush();

You may clear all atomic locks in the cache using the flushLocks method:

await Cache.flushLocks();

Warning

Flushing the cache does not respect your configured cache "prefix" and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.

Cache Memoization

Laraflare's memo cache driver allows you to temporarily store resolved cache values in memory during a single request or job execution. This prevents repeated cache hits within the same execution, significantly improving performance.

To use the memoized cache, invoke the memo method:

import { Cache } from '@laraflare/framework';

const value = await Cache.memo().get('key');

The memo method optionally accepts the name of a cache store, which specifies the underlying cache store the memoized driver will decorate:

// Using the default cache store...
const value = await Cache.memo().get('key');

// Using the Redis cache store...
const value = await Cache.memo('redis').get('key');

The first get call for a given key retrieves the value from your cache store, but subsequent calls within the same request or job will retrieve the value from memory:

// Hits the cache...
const value = await Cache.memo().get('key');

// Does not hit the cache, returns memoized value...
const value = await Cache.memo().get('key');

When calling methods that modify cache values (such as put, increment, remember, etc.), the memoized cache automatically forgets the memoized value and delegates the mutating method call to the underlying cache store:

await Cache.memo().put('name', 'Taylor'); // Writes to underlying cache...
await Cache.memo().get('name');           // Hits underlying cache...
await Cache.memo().get('name');           // Memoized, does not hit cache...

await Cache.memo().put('name', 'Tim');    // Forgets memoized value, writes new value...
await Cache.memo().get('name');           // Hits underlying cache again...

The Cache Helper

In addition to using the Cache facade, you may also use the global cache function to retrieve and store data via the cache. When the cache function is called with a single, string argument, it will return a promise for the value of the given key:

const value = await cache('key');

If you provide an object of key / value pairs and an expiration time to the function, it will store values in the cache for the specified duration:

await cache({ key: 'value' }, seconds);

await cache({ key: 'value' }, now().plus({ minutes: 10 }));

When the cache function is called without any arguments, it returns the cache manager, allowing you to call other caching methods:

await cache().remember('users', seconds, () => DB.table('users').get());

Cache Tags

Warning

Cache tags are only supported by stores that implement them, such as the redis driver. They are not supported when using the database, kv, storage, array or null cache drivers.

Storing Tagged Cache Items

Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put a value into the cache:

import { Cache } from '@laraflare/framework';

await Cache.tags(['people', 'artists']).put('John', john, seconds);
await Cache.tags(['people', 'authors']).put('Anne', anne, seconds);

Accessing Tagged Cache Items

Items stored via tags may not be accessed without also providing the tags that were used to store the value. To retrieve a tagged cache item, pass the same ordered list of tags to the tags method, then call the get method with the key you wish to retrieve:

const john = await Cache.tags(['people', 'artists']).get('John');

const anne = await Cache.tags(['people', 'authors']).get('Anne');

Removing Tagged Cache Items

You may flush all items that are assigned a tag or list of tags. For example, the following code would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

await Cache.tags(['people', 'authors']).flush();

In contrast, the code below would remove only cached values tagged with authors, so Anne would be removed, but not John:

await Cache.tags('authors').flush();

Atomic Locks

Warning

To utilize this feature, your application must be using a cache store that supports locks, such as the kv, redis, database or array driver, as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.

Managing Locks

Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. You may create and manage locks using the Cache.lock method:

import { Cache } from '@laraflare/framework';

const lock = Cache.lock('foo', 10);

if (await lock.get()) {
  // Lock acquired for 10 seconds...

  await lock.release();
}

The get method also accepts a function. After the function is executed, Laraflare will automatically release the lock:

await Cache.lock('foo', 10).get(async () => {
  // Lock acquired for 10 seconds and automatically released...
});

If the lock is not available at the moment you request it, you may instruct Laraflare to wait for a specified number of seconds. If the lock cannot be acquired within the specified time limit, a LockTimeoutException will be thrown:

import { Cache, LockTimeoutException } from '@laraflare/framework';

const lock = Cache.lock('foo', 10);

try {
  await lock.block(5);

  // Lock acquired after waiting a maximum of 5 seconds...
} catch (e) {
  if (!(e instanceof LockTimeoutException)) throw e;

  // Unable to acquire lock...
} finally {
  await lock.release();
}

The example above may be simplified by passing a function to the block method. When a function is passed to this method, Laraflare will attempt to acquire the lock for the specified number of seconds and will automatically release the lock once the function has been executed:

await Cache.lock('foo', 10).block(5, async () => {
  // Lock acquired for 10 seconds after waiting a maximum of 5 seconds...
});

Managing Locks Across Processes

Sometimes, you may wish to acquire a lock in one process and release it in another process. For example, you may acquire a lock during a web request and wish to release the lock at the end of a queued job that is triggered by that request. In this scenario, you should pass the lock's scoped "owner token" to the queued job so that the job can re-instantiate the lock using the given token.

In the example below, we will dispatch a queued job if a lock is successfully acquired. In addition, we will pass the lock's owner token to the queued job via the lock's owner method:

const podcast = await Podcast.find(id);

const lock = Cache.lock('processing', 120);

if (await lock.get()) {
  await ProcessPodcast.dispatch(podcast, lock.owner());
}

Within our application's ProcessPodcast job, we can restore and release the lock using the owner token:

await Cache.restoreLock('processing', this.owner).release();

If you would like to release a lock without respecting its current owner, you may use the forceRelease method:

await Cache.lock('processing').forceRelease();

Refreshing Locks

If you need to extend the expiration of a lock that you currently own, you may use the refresh method. If no number of seconds is provided, the lock's original duration will be used. This is useful for long-running operations where you prefer to acquire a short lock and periodically extend it instead of acquiring a lock with a very long expiration time:

const lock = Cache.lock('generate-reports', 60);

if (await lock.get()) {
  for (const report of reports) {
    await report.generate();

    // Extend the lock for another 60 seconds...
    await lock.refresh();
  }

  await lock.release();
}

Concurrency Limiting

Laraflare's atomic lock functionality also provides a few ways to limit concurrent execution of functions. Use withoutOverlapping when you want to allow only one running instance across your infrastructure:

await Cache.withoutOverlapping('foo', async () => {
  // Lock acquired after waiting a maximum of 10 seconds...
});

By default, the lock is held until the function finishes executing, and the method waits up to 10 seconds to acquire the lock. You may customize these values using additional arguments:

await Cache.withoutOverlapping('foo', async () => {
  // Lock acquired for 120 seconds after waiting a maximum of 5 seconds...
}, 120, 5);

If the lock cannot be acquired within the specified wait time, a LockTimeoutException will be thrown.

If you want controlled parallelism, use the funnel method to set a maximum number of concurrent executions. The funnel method works with any cache driver that supports locks:

await Cache.funnel('foo')
  .limit(3)
  .releaseAfter(60)
  .block(10)
  .then(async () => {
    // Concurrency lock acquired...
  }, async () => {
    // Could not acquire concurrency lock...
  });

The funnel key identifies the resource being limited. The limit method defines the maximum concurrent executions. The releaseAfter method sets a safety timeout in seconds before an acquired slot is automatically released. The block method sets how many seconds to wait for an available slot.

If you prefer to handle the timeout via exceptions instead of providing a failure function, you may omit the second function. A LimiterTimeoutException will be thrown if the lock cannot be acquired within the specified wait time:

import { Cache, LimiterTimeoutException } from '@laraflare/framework';

try {
  await Cache.funnel('foo')
    .limit(3)
    .releaseAfter(60)
    .block(10)
    .then(async () => {
      // Concurrency lock acquired...
    });
} catch (e) {
  if (!(e instanceof LimiterTimeoutException)) throw e;

  // Unable to acquire concurrency lock...
}

If you would like to use a specific cache store for the concurrency limiter, you may invoke the funnel method on the desired store:

await Cache.store('redis').funnel('foo')
  .limit(3)
  .block(10)
  .then(async () => {
    // Concurrency lock acquired using the "redis" store...
  });

Note

The funnel method requires the cache store to provide locks. If you attempt to use funnel with a cache store that does not support locks, a BadMethodCallException will be thrown.

Cache Failover

The failover cache driver provides automatic failover functionality when interacting with the cache. If the primary cache store of the failover store fails for any reason, Laraflare will automatically attempt to use the next configured store in the list. This is particularly useful for ensuring high availability in production environments where cache reliability is critical.

To configure a failover cache store, specify the failover driver and provide an array of store names to attempt in order. By default, Laraflare includes an example failover configuration in your application's config/cache.ts configuration file:

failover: {
  driver: 'failover' as const,
  stores: ['database', 'array'],
},

Once you have configured a store that uses the failover driver, you will need to set the failover store as your default cache store in your application's .env file to make use of the failover functionality:

CACHE_STORE=failover

When a cache store operation fails and failover is activated, Laraflare will dispatch the CacheFailedOver event, allowing you to report or log that a cache store has failed.

Adding Custom Cache Drivers

Writing the Driver

To create our custom cache driver, we first need to implement the CacheStore interface. So, a MongoDB cache implementation might look something like this:

import type { CacheStore } from '@laraflare/framework';

export class MongoStore implements CacheStore {
  async get(key: string) {}
  async many(keys: string[]) {}
  async put(key: string, value: unknown, seconds: number) {}
  async putMany(values: Record<string, unknown>, seconds: number) {}
  async increment(key: string, value = 1) {}
  async decrement(key: string, value = 1) {}
  async forever(key: string, value: unknown) {}
  async touch(key: string, seconds: number) {}
  async forget(key: string) {}
  async flush() {}
  getPrefix() {}
}

We just need to implement each of these methods using a MongoDB connection. For an example of how to implement each of these methods, take a look at the DatabaseStore in Laraflare's src/Illuminate/Cache directory. Once our implementation is complete, we can finish our custom driver registration by calling the Cache facade's extend method:

Cache.extend('mongo', (app) => {
  return Cache.repository(new MongoStore());
});

Note

If you're wondering where to put your custom cache driver code, you could create an Extensions directory within your app directory. However, keep in mind that Laraflare does not have a rigid application structure and you are free to organize your application according to your preferences.

Registering the Driver

To register the custom cache driver with Laraflare, we will use the extend method on the Cache facade. Since other service providers may attempt to read cached values within their boot method, we will register our custom driver within a booting callback. By using the booting callback, we can ensure that the custom driver is registered just before the boot method is called on our application's service providers but after the register method is called on all of the service providers. We will register our booting callback within the register method of our application's AppServiceProvider class:

import { Cache, ServiceProvider } from '@laraflare/framework';
import { MongoStore } from '../Extensions/MongoStore';

export class AppServiceProvider extends ServiceProvider {
  /**
   * Register any application services.
   */
  override register(): void {
    this.app.booting(() => {
      Cache.extend('mongo', (app) => {
        return Cache.repository(new MongoStore());
      });
    });
  }

  /**
   * Bootstrap any application services.
   */
  override boot(): void {
    // ...
  }
}

The first argument passed to the extend method is the name of the driver. This will correspond to your driver option in the config/cache.ts configuration file. The second argument is a function that should return a cache Repository instance. The function will be passed an app instance, which is the service container.

Once your extension is registered, update the CACHE_STORE environment variable or default option within your application's config/cache.ts configuration file to the name of your extension.

Events

To execute code on every cache operation, you may listen for various events dispatched by the cache:

Event Name
CacheFlushed
CacheFlushing
CacheFlushFailed
CacheLocksFlushed
CacheLocksFlushing
CacheLocksFlushFailed
CacheHit
CacheMissed
ForgettingKey
KeyForgetFailed
KeyForgotten
KeyWriteFailed
KeyWritten
RetrievingKey
RetrievingManyKeys
WritingKey
WritingManyKeys

To increase performance, you may disable cache events by setting the events configuration option to false for a given cache store in your application's config/cache.ts configuration file:

database: {
  driver: 'database' as const,
  // ...
  events: false,
},
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.