Cloud
Distributed Cache
In-memory TTL cache with LRU eviction and tag-based invalidation, with tenant-scoped keys and tags for isolation.
On this page10
Overview
CloudCache is an in-memory TTL cache with LRU eviction and tag-based
invalidation. It is per process; nothing is shared between instances. Keys are
not prefixed automatically, so scope keys and tags by tenant yourself (see
below).
Basic Usage
TypeScript
TS
1import { cache } from '@axiljs/cloud'
2
3cache.set('user:42', { name: 'Tariq', role: 'admin' })
4const user = cache.get('user:42') // value, or undefined if missing or expired
5
6cache.has('user:42') // true
7cache.delete('user:42')Custom TTL and Tags
TypeScript
TS
1cache.set('report:monthly', reportData, {
2 ttlMs: 300_000, // 5 minutes
3 tags: ['tenant:acme-corp', 'reports'],
4})Tenant Isolation
Prefix keys with the tenant ID and tag entries by tenant:
TypeScript
TS
1const tenantId = getTenantId(req)
2const key = `tenant:${tenantId}:user:${userId}`
3
4cache.set(key, userData, {
5 tags: [`tenant:${tenantId}`],
6})Tag-Based Invalidation
invalidateTag() removes every entry carrying the tag and returns how many
were removed:
TypeScript
TS
const cleared = cache.invalidateTag('tenant:acme-corp')
console.log(`Cleared ${cleared} entries`)Eviction
When the cache holds maxEntries items, adding a new key evicts the least
recently used entry. get() and has() mark an entry as recently used, and
set() on an existing key refreshes it.
Cache Maintenance
TypeScript
TS
1cache.prune() // remove expired entries; returns the count
2cache.clear() // remove everything
3
4cache.stats()
5// { size: 142, maxEntries: 10000, defaultTtlMs: 60000 }Custom Instance
TypeScript
TS
1import { CloudCache } from '@axiljs/cloud'
2
3const sessionCache = new CloudCache<Session>({
4 defaultTtlMs: 1_800_000, // 30 minutes
5 maxEntries: 50_000,
6})Options
| Option | Type | Default | Description |
|---|---|---|---|
defaultTtlMs | number | 60000 | Default time-to-live in milliseconds |
maxEntries | number | 10000 | Maximum entries before LRU eviction |
API Reference
| Method | Returns |
|---|---|
set(key, value, { ttlMs?, tags? }?) | void |
get(key) | T | undefined |
has(key) | boolean |
delete(key) | boolean |
invalidateTag(tag) | number removed |
prune() | number removed |
clear() | void |
stats() | { size, maxEntries, defaultTtlMs } |
Was this page helpful?