Skip to content

platform-caching

Layered caching library providing both an in-memory LRU cache and a Redis-backed distributed cache. Both implementations share the ILayeredCache contract and support TTL expiration, stale-while-revalidate, warm-up, and pluggable metrics recording.

Package: @breadstone/archipel-platform-caching

npm install @breadstone/archipel-platform-caching

Quick Start

typescript
import { MemoryLayeredCache } from '@breadstone/archipel-platform-caching';

const cache = new MemoryLayeredCache<string, IProduct>(async (key) => productRepository.findById(key), {
  ttlMs: 60_000,
  maxEntries: 500,
  staleWhileRevalidate: true,
});

const product = await cache.getAsync('prod-123');

For Redis-backed caching:

typescript
import { RedisLayeredCache } from '@breadstone/archipel-platform-caching/redis';

const cache = new RedisLayeredCache<string, IProduct>(redisClient, async (key) => productRepository.findById(key), {
  url: 'redis://localhost:6379',
  keyPrefix: 'products:',
  ttlSeconds: 300,
  cacheName: 'products',
});

ILayeredCache Interface

Both implementations share this contract:

MethodDescription
get(key)Synchronous cache lookup.
getAsync(key)Asynchronous cache lookup — triggers the load function on a miss.
set(key, value)Synchronous write.
setAsync(key, value)Asynchronous write.
invalidate(key)Synchronous eviction.
invalidateAsync(key)Asynchronous eviction.
warm(key)Proactively loads and caches a value.
stats()Returns hit/miss/eviction counters as ICacheStats.

Configuration Options

ILayeredCacheOptions (In-Memory)

PropertyTypeDefaultDescription
ttlMsnumberTime-to-live in milliseconds.
staleWhileRevalidatebooleanfalseServe stale entries while refreshing in the background.
maxEntriesnumberLRU eviction threshold.
metricsRecorderICacheMetricsRecorderNoopPluggable metrics hook.
cacheNamestring'memory'Label used in metrics and logging.

IRedisLayeredCacheOptions

PropertyTypeDefaultDescription
urlstringRedis connection URL (e.g. redis://localhost:6379).
keyPrefixstringKey prefix applied to all Redis keys.
ttlSecondsnumberTime-to-live in seconds.
serialize(value) => stringJSON.stringifyCustom serializer for cache values.
deserialize(raw) => valueJSON.parseCustom deserializer for cache entries.
metricsRecorderICacheMetricsRecorderNoopPluggable metrics hook.
cacheNamestring'redis'Label used in metrics and logging.

Environment Variables

Core (optional)

VariableDescriptionDefaultRequired
CACHE_DEFAULT_TTL_MSDefault cache TTL in millisecondsNo
CACHE_MAX_ENTRIESMaximum number of entries retained in an in-memory cacheNo
CACHE_STALE_WHILE_REVALIDATEWhether expired entries are served during background refreshfalseNo

Redis

Subpath: @breadstone/archipel-platform-caching/redisSDK: ioredis ≥ 5.0.0

VariableDescriptionDefaultRequired
REDIS_URLRedis connection URLYes
REDIS_KEY_PREFIXKey prefix for all Redis cache keys''No
REDIS_TTL_SECONDSTTL in seconds for Redis entriesNo

Metrics

Implement ICacheMetricsRecorder to forward cache statistics to your telemetry system:

typescript
import { ICacheMetricsRecorder } from '@breadstone/archipel-platform-caching';

class TelemetryCacheRecorder implements ICacheMetricsRecorder {
  recordHit(cacheName: string): void {
    /* increment counter */
  }
  recordMiss(cacheName: string): void {
    /* increment counter */
  }
  recordLoadSuccess(cacheName: string, durationMs: number): void {
    /* histogram */
  }
  recordLoadError(cacheName: string): void {
    /* increment counter */
  }
  recordEviction(cacheName: string): void {
    /* increment counter */
  }
}

When no recorder is provided, NoopCacheMetricsRecorder is used as a silent fallback.


Health Check

The CachingHealthIndicator reports the caching subsystem as available. Import it from the /health subpath:

typescript
import { CachingHealthIndicator } from '@breadstone/archipel-platform-caching/health';
import { HealthModule } from '@breadstone/archipel-platform-health';

@Module({
  imports: [
    CachingModule,
    HealthModule.withIndicators([CachingHealthIndicator]),
  ],
})
export class AppModule {}
KeyCheckDependencies
cachingAlways reports upNone

API Reference

See the full API documentation for all exported types and classes.

Released under the MIT License.