コンテンツにスキップ
日本語

Redis cache

このコンテンツはまだ日本語訳がありません。

RedisCache is the Redis-backed Cache implementation. Production-ready, multi-pod-safe, with single-round-trip bulk operations.

import { RedisCache, RedisCacheOptions } from 'actor-ts/cache';
const redisCacheOptions = RedisCacheOptions.create().withUrl('redis://redis.example.com:6379');
const cache = new RedisCache(
redisCacheOptions,
);

Most multi-pod production cases:

  • Multi-pod cache sharing — pods see the same cache state.
  • Bulk operations matter — MGET / MSET single round-trip.
  • Persistence wanted — AOF / RDB survive Redis restart.
  • You already run Redis — reuse existing infrastructure.

For single-pod, in-memory is simpler.

type RedisCacheOptionsType = {
url?: string; // 'redis://host:port'
host?: string;
port?: number;
password?: string;
db?: number;
keyPrefix?: string;
client?: RedisClientLike; // pre-built ioredis client
};

URL form:

const redisCacheOptions = RedisCacheOptions.create().withUrl('redis://localhost:6379/0');
new RedisCache(redisCacheOptions);
const redisCache2Options = RedisCacheOptions.create().withUrl('rediss://redis.example.com:6380');
new RedisCache(redisCache2Options); // TLS
const redisCache3Options = RedisCacheOptions.create().withUrl('redis://user:pass@host:6379');
new RedisCache(redisCache3Options);

Field form:

const redisCacheOptions = RedisCacheOptions.create()
.withHost('redis.example.com')
.withPort(6379)
.withPassword(process.env.REDIS_PASS)
.withDb(1)
.withKeyPrefix('my-app:');
new RedisCache(
redisCacheOptions,
);

keyPrefix is applied to every key — useful when sharing a Redis instance across multiple apps:

keyPrefix: 'my-app:cache:'
// → 'my-app:cache:user:42', 'my-app:cache:session:abc', ...

The framework registers the Redis factory itself, so a cache comes up on Redis with no registerCache call and no new RedisCache(...) anywhere in your code — just a plugin id and a block:

actor-ts.cache {
sessions.plugin = "actor-ts.cache.redis" # cache('sessions') is Redis
redis {
url = ${?REDIS_URL} # or host/port below
db = 0
key-prefix = "my-app:"
password = ${?REDIS_PASSWORD}
}
}

The leaves are the kebab-case of the RedisCacheOptionsType fields above. host and port are read but ship as comments in reference.conf: url is mutually exclusive with them, and a published host = "localhost" would be set for every deployment and would turn every url into an OptionsError. Left unset, ioredis applies its own 127.0.0.1:6379.

An empty string means unset. url, key-prefix and password ship as "" so you can see the shape of the key; the reader drops them rather than handing them on. Explicit options always win over the block, and the block over the built-in defaults.

Each named cache can have its own connection settings, layered over the global block leaf by leaf — which is what lets two consumers share one server without sharing a database:

actor-ts.cache {
redis.url = ${?REDIS_URL}
rate-limit { plugin = "actor-ts.cache.redis", redis.db = 1 }
idempotency { plugin = "actor-ts.cache.redis", redis.db = 2 }
}

ioredis is a lazy optional peer, so the block costs nothing until a cache actually resolves onto it: the driver is imported on the first cache operation, not at startup. A bad value is refused at the first cache(name) with an OptionsError naming the field.

import { Cluster } from 'ioredis';
const redisCacheOptions = RedisCacheOptions.create().withClient(
new Cluster([
{ host: 'redis-1', port: 6379 },
{ host: 'redis-2', port: 6379 },
{ host: 'redis-3', port: 6379 },
]),
);
new RedisCache(
redisCacheOptions,
);

ioredis handles the cluster protocol (MOVED / ASK redirects, slot tracking). Use Redis Cluster for horizontal scale beyond a single Redis server’s memory.

const redisCacheOptions = RedisCacheOptions.create().withUrl('rediss://redis.example.com:6380');
new RedisCache(redisCacheOptions);
// TLS is selected by the `rediss://` URL scheme:
const redisCache2Options = RedisCacheOptions.create().withUrl('rediss://redis.example.com:6380');
new RedisCache(redisCache2Options);

rediss:// URL prefix selects TLS — or pass a pre-built TLS client via withClient. Cert verification goes through Node’s TLS defaults; for self-signed in dev, you’d need explicit ioredis TLS options.

const users = await cache.mget<User>(['user:1', 'user:2', 'user:3']);
// ↑
// single MGET round-trip

mget on RedisCache → single Redis MGET command → one network round-trip. Critical for the sharded-entity hydration pattern (rebuilding state for many entities on node startup).

Both map to Redis primitives:

  • incr → Redis INCR (atomic, no race).
  • setIfAbsent → Redis SET NX (atomic CAS).

Used by the framework’s rate-limit + idempotency-key middleware. Safe across pods.

Redis is the best-supported backend for locking: a key lives on one logical keyspace, so SET NX decides a race the same way for every pod. See acquireLock for the token-checked release that pairs with it.

// Not exposed directly in Cache; ioredis pipelining is automatic
// for batched calls within the same tick.

ioredis pipelines commands issued in the same JS turn, sending them in a single TCP write. The Cache interface doesn’t expose pipelining explicitly; the framework’s implementation uses pipelining where helpful.

Terminal window
npm install ioredis
# or: bun add ioredis

ioredis is the underlying client. Versions 5+ are tested.

Redis supports two persistence modes:

  • RDB — periodic snapshots. Default in many configs.
  • AOF — append-only log. More durable, slower.

The framework’s Cache doesn’t care about Redis-side persistence config — caches are opportunistic. But for cache survival across Redis restarts, enable RDB at minimum.

const redisCacheOptions = RedisCacheOptions.create().withUrl(
'rediss://default:password@my-cluster.cache.amazonaws.com:6380',
);
new RedisCache(
redisCacheOptions,
);

AWS ElastiCache, GCP Memorystore, Azure Cache for Redis — all support rediss:// URLs. Use them.

import { Cluster } from 'ioredis';
const redisCacheOptions = RedisCacheOptions.create().withClient(
new Cluster([...], {
enableReadyCheck: true,
redisOptions: { maxRetriesPerRequest: 3 },
}),
);
new RedisCache(
redisCacheOptions,
);

Defaults to ioredis sensible-defaults. For very-tight latency or specific connection-pool sizing, pass ioredis-style options explicitly.