Skip to content

Cache ​

Complete Example: Cache Miss, Hit, and Invalidation ​

Create this command in the Blog template:

csharp
// app/Commands/CacheDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class CacheDemo : Command
{
    public override string Signature => "demo:cache";
    public override async Task<int> Handle()
    {
        Cache.Fake();
        var calls = 0;
        Task<int> Calculate() => Task.FromResult(++calls);
        var first = await Cache.Remember("demo:count", TimeSpan.FromMinutes(1), Calculate);
        var second = await Cache.Remember("demo:count", TimeSpan.FromMinutes(1), Calculate);
        await Cache.Forget("demo:count");
        var third = await Cache.Remember("demo:count", TimeSpan.FromMinutes(1), Calculate);
        if (first != 1 || second != 1 || third != 2 || calls != 2)
            throw new InvalidOperationException("Unexpected cache behavior.");
        Line("miss=1; hit=1; after invalidation=2");
        return 0;
    }
}

Run dotblaze demo:cache. Expected output is the line above; no shared cache is changed. Use the same invalidation key after successful writes in real application code. Include the tenant/user identity in a key when the cached data is private. Remember caches a result; it does not make arbitrary callback side effects exactly-once.

Introduction ​

The Cache facade is Laravel's cache: store the result of slow work (queries, API calls) for a while and read it back fast. Values are stored as JSON, so anything System.Text.Json can serialize works.

csharp
var count = await Cache.Remember("posts.count", TimeSpan.FromMinutes(5), () => Post.Query().Count());

Configuration ​

config/Cache.cs:

csharp
public class CacheConfig : ConfigFile
{
    public override object Values() => new
    {
        @default = "memory",
        prefix = "cache:",
        stores = new
        {
            memory = new { driver = "memory" },
            redis = new { driver = "redis", connection = "cache" },
        },
    };
}
KeyDescription
defaultThe store used by the facade. Defaults to memory.
prefixPrepended to every key (also stores.*.prefix per store).
stores.*.drivermemory, database, or redis.
stores.*.connectionFor redis: the Redis connection.
limiterThe store the rate limiter uses. Defaults to default.

Drivers ​

Driver
memoryIn the process. Fast, but each server (and each queue:work process) has its own, and it is empty after a restart.
databaseThe cache and cache_locks tables of a database connection. Shared by every server without extra infrastructure; slower than Redis.
redisShared by every server. Needs the DotBlaze.Redis package, see Redis.

With more than one server, use redis or database, so that Cache.Forget, counters, and locks mean the same thing everywhere.

The database store's tables come with the application template (the create_cache_table migration). Its options are connection (default: the default connection), table (cache), and lock_table (cache_locks). In stores of config/Cache.cs:

csharp
database = new { driver = "database", table = "cache", lock_table = "cache_locks" },

Cache Usage ​

Retrieving Items ​

csharp
var name = await Cache.Get<string>("user:1:name");               // null when missing
var theme = await Cache.Get("user:1:theme", "light");            // with a fallback
var stats = await Cache.Get<DashboardStats>("dashboard");        // any JSON-serializable type

if (await Cache.Has("dashboard")) { ... }
if (await Cache.Missing("dashboard")) { ... }

Storing Items ​

csharp
await Cache.Put("dashboard", stats, TimeSpan.FromMinutes(10));
await Cache.Put("settings", settings);            // no ttl: forever
await Cache.Forever("settings", settings);

var added = await Cache.Add("welcome-sent:1", true, TimeSpan.FromDays(1));   // only if missing (atomic)

Retrieve and Store ​

Remember returns the cached value, or runs the callback, stores its result, and returns it:

csharp
var users = await Cache.Remember("users.active", TimeSpan.FromMinutes(5), async () =>
    (await User.Where(u => u.Active).Get()).ToList());

var config = await Cache.RememberForever("remote-config", () => FetchRemoteConfig());

Pull reads a value and deletes it:

csharp
var code = await Cache.Pull<string>("login-code:1");

Incrementing and Decrementing ​

Counters are atomic on every driver. A missing key counts as 0, and the key's expiry is kept:

csharp
await Cache.Increment("visits");
await Cache.Increment("visits", 5);
await Cache.Decrement("stock:42");
var visits = await Cache.Get<long>("visits");

Removing Items ​

csharp
await Cache.Forget("dashboard");
await Cache.Flush();   // every key of the store's prefix

dotblaze cache:clear [store] flushes a store from the command line. On redis with an empty prefix, Flush empties the whole Redis database, like Laravel; keep a prefix when the database is shared.

Accessing Multiple Stores ​

csharp
var value = await Cache.Store("redis").Get<string>("key");
await Cache.Store("memory").Put("key", "value", TimeSpan.FromSeconds(30));

Atomic Locks ​

A lock makes sure only one process does something at a time, across servers when the store is redis:

csharp
var ran = await Cache.Lock("reports:daily", TimeSpan.FromMinutes(5)).Get(async () =>
{
    await BuildDailyReport();
});   // false if another process holds the lock

await Cache.Lock("invoice:42", TimeSpan.FromSeconds(30)).Block(TimeSpan.FromSeconds(10), async () =>
{
    await ChargeInvoice(42);
});   // waits up to 10 seconds, otherwise TimeoutException

Without a callback, Get() returns whether you got the lock and Release() frees it. The lock expires after its ttl even if it is never released. Only the owner can release it; to release it in another process, pass the owner along:

csharp
var lockHandle = Cache.Lock("import", TimeSpan.FromMinutes(10));
if (await lockHandle.Get())
    await new ImportJob { LockOwner = lockHandle.Owner }.Dispatch();

// in the job
await Cache.Lock("import", TimeSpan.FromMinutes(10), LockOwner).Release();

Testing ​

Cache.Fake() gives the current test flow an empty in-memory cache (every store name maps to it), so tests do not see each other's values:

csharp
var cache = Cache.Fake();
await service.RefreshDashboard();
Assert.NotNull(await cache.Get<DashboardStats>("dashboard"));

See Fakes for where fakes apply.

Custom Drivers ​

Implement ICacheStore (get, put, add, increment, forget, flush, and locks) and an ICacheConnector that creates it from the store's config section, then register the connector under the driver name:

csharp
services.AddKeyedSingleton<ICacheConnector, DynamoCacheConnector>("dynamodb");