Overview
The Redis provider extends your application ports with cache capabilities using ioredis. It provides a simple caching interface for storing and retrieving data with optional TTL (time-to-live) support.Installation
Configuration
The Redis provider reads configuration from environment variables:| Variable | Required | Description | Example |
|---|---|---|---|
REDIS_URL | Yes | Redis connection URL | redis://localhost:6379 |
REDIS_DB | No | Redis database number (default: 0) | 0 |
Example .env
Setup
Basic Setup
Type Your Ports
To get proper type inference for the cache port, extend your ports type:API Reference
The provider extends your ports with acache property:
get(key: string)
Get a value from the cache.Promise<string | null>
set(key: string, value: string, ttlSeconds?: number)
Set a value in the cache with optional TTL (time-to-live) in seconds.Promise<void>
del(key: string)
Delete a key from the cache. Returns the number of keys deleted (0 or 1).Promise<number>
exists(key: string)
Check if a key exists in the cache.Promise<boolean>
client
Access the underlying ioredis client for advanced operations.Redis (from ioredis)
Usage Examples
Caching User Profiles
Cache Invalidation
Using Advanced Redis Features
Lifecycle
The Redis provider:- During
register: Connects to Redis and adds thecacheport - During
onAppStop: Gracefully closes the Redis connection
Error Handling
The provider will throw errors in these cases:- Missing
REDIS_URLenvironment variable - Failed connection to Redis server
Best Practices
Use consistent key naming
Use consistent key naming
Use a consistent pattern like
entity:id:field for cache keys to make debugging easier.Set appropriate TTLs
Set appropriate TTLs
Always set TTLs for cached data to prevent stale data and memory issues.
Invalidate on writes
Invalidate on writes
When updating data in your database, remember to invalidate the corresponding cache entries.
Serialize complex objects
Serialize complex objects
Use
JSON.stringify() and JSON.parse() for storing and retrieving complex objects.Handle cache misses gracefully
Handle cache misses gracefully
Always have a fallback to fetch from the primary data source when cache misses occur.