Skip to main content
Sonamu provides a powerful caching system based on BentoCache. It supports various drivers including memory and Redis, and supports multi-layer caching (L1/L2) and distributed invalidation.

Basic Structure

default

Specifies the default cache store to use. Type: string

stores

Defines the cache stores to use. Type: Record<string, BentoCacheStore>

Single Layer: Memory

The simplest configuration, storing cache only in memory.
Pros: Fast speed, simple configuration
Cons: Cache lost on server restart, cannot share between multiple servers

Multi-layer Cache: L1 (Memory) + L2 (Redis)

L1 caches quickly in memory, L2 caches persistently in Redis.
How it works:
  1. Check L1 (memory) first when querying cache
  2. If not in L1, check L2 (Redis)
  3. If found in L2, also store in L1
  4. If not in both, query original data and store in L1, L2

Distributed Cache: L1 + L2 + Bus

Synchronizes cache invalidation across multiple servers.
How it works:
  • When cache is invalidated on one server
  • Propagated to all other servers via Bus
  • L1 cache on all servers is also automatically invalidated
If running multiple servers (behind a load balancer), enable Bus. Cache consistency is guaranteed.

ttl

Sets the default Time To Live for cache. Type: string (optional) Default: "5m" (5 minutes)
Time formats:
  • "5s" - 5 seconds
  • "1m" - 1 minute
  • "1h" - 1 hour
  • "1d" - 1 day
Using different TTL per API:

prefix

Sets a prefix to be added to all cache keys. Type: string (optional) Default: ""
Example:
If multiple apps share the same Redis instance, set a prefix to prevent key collisions.

Driver Options

memory driver

Stores cache in memory.
Options:
  • maxSize: Maximum memory usage ("50mb", "100mb", "1gb", etc.)

redis driver

Stores cache in Redis.
connection configuration:

redisBus driver

Propagates cache invalidation using Redis Pub/Sub.
redisBus can use the same connection as the redis driver.

Practical Examples

Single Server: Memory Only

Use case: Small apps, single server

Multi-layer Cache: Memory + Redis

Use case: Medium apps, single server, persistent cache needed

Distributed Environment: Memory + Redis + Bus

Use case: Large apps, multiple servers (load balancer), cache consistency needed

Multiple Stores: Separated by Purpose

Usage example:

Using Cache

After configuration, use the @cache decorator in APIs.
Cache Decorator Usage

Installing Redis

Redis must be installed before using it.

Docker

macOS

Linux

Connection Verification

Important Notes

1. Redis Connection Management

2. Memory Size Configuration

3. TTL Selection

Next Steps

After completing cache configuration: