Skip to content

Caching Infrastructure

Core Idea: Redis provides fast in-memory caching for query results, service contracts, and session data with automatic TTL management.

The platform uses Redis 7 for caching:

  • Query results (CQRS queries)
  • Service contracts (service discovery)
  • Session data (API Gateway)
  • Read model materialization
redis:
image: redis:7-alpine
command: redis-server --appendonly yes --requirepass redis123
ports:
- "56379:6379"
volumes:
- redis-data:/data
Terminal window
REDIS_URL=redis://:redis123@redis:6379
@QueryHandler(GetUserQuery, {
cache: {
ttl: 60, // Cache for 60 seconds
key: (query) => `user:${query.userId}`
}
})
export class GetUserHandler {
async handle(query: GetUserQuery) {
// Result automatically cached
return await this.userRepo.findById(query.userId);
}
}
// Service discovery caches contracts
await redis.set(
`contracts:${serviceName}:${version}`,
JSON.stringify(contracts),
'EX',
3600 // 1 hour TTL
);
  1. Set Appropriate TTLs

    • Frequently changing data: 10-60 seconds
    • Stable data: 5-60 minutes
    • Configuration: Hours to days
  2. Use Cache Keys Wisely

    • Include relevant query parameters
    • Use namespacing: user:123, not just 123
  3. Monitor Hit Rate

    • Target >80% hit rate for cached queries
    • Low hit rate indicates wrong TTL or cache keys
Terminal window
# Redis stats
redis-cli -a redis123 INFO stats
# Key space
redis-cli -a redis123 DBSIZE
# Memory usage
redis-cli -a redis123 INFO memory