RedisCache
RedisCache is a Cache implementation backed by Redis. It supports distributed cache invalidation via Redis pub/sub, making it suitable for multi-host deployments.
import { RedisCache } from "@farbenmeer/tag-based-cache/redis-cache";Requires the @redis/client package as a peer dependency.
Constructor
Section titled “Constructor”new RedisCache(redis: RedisClientType)- Parameters:
redis: A connectedRedisClientTypeinstance from@redis/client.
import { createClient } from "@redis/client";import { RedisCache } from "@farbenmeer/tag-based-cache/redis-cache";
const redis = createClient();await redis.connect();
const cache = new RedisCache(redis);
await cache.set({ key: "book:1", data: { title: "Dune" }, ttl: 300, tags: ["books", "book:1"],});
const entry = await cache.get("book:1");// { data: { title: "Dune" }, attachment: null }How It Works
Section titled “How It Works”Storage
Section titled “Storage”Entries are stored as separate Redis keys:
data:{key}— JSON-serialized data, with Redis TTL expiration.attachment:{key}— Binary data, with Redis TTL expiration.tag:{tag}— A Redis set containing all keys associated with that tag.
Invalidation
Section titled “Invalidation”When delete(tags) is called:
- All keys associated with the given tags are looked up via the
tag:{tag}sets. - The corresponding
data:*,attachment:*, andtag:*keys are deleted. - An invalidation message is published to the
invalidateRedis channel so other connected instances are notified.
Subscriptions
Section titled “Subscriptions”subscribe uses a dedicated Redis connection (created via redis.duplicate()) to listen on the invalidate pub/sub channel. The subscription is set up lazily on the first subscribe call and torn down when the last subscriber unsubscribes.
const unsubscribe = cache.subscribe((tags, meta) => { console.log("Invalidated:", tags);});
// Later:unsubscribe();When to Use
Section titled “When to Use”- Multi-host deployments where cache invalidation needs to propagate across processes.
- When you need the TApi Caching Strategies pub/sub system to work across multiple servers.