Caching Infrastructure
Caching Infrastructure
Section titled “Caching Infrastructure”Core Idea: Redis provides fast in-memory caching for query results, service contracts, and session data with automatic TTL management.
Overview
Section titled “Overview”The platform uses Redis 7 for caching:
- Query results (CQRS queries)
- Service contracts (service discovery)
- Session data (API Gateway)
- Read model materialization
Configuration
Section titled “Configuration”Development
Section titled “Development”redis: image: redis:7-alpine command: redis-server --appendonly yes --requirepass redis123 ports: - "56379:6379" volumes: - redis-data:/dataConnection
Section titled “Connection”REDIS_URL=redis://:redis123@redis:6379Usage Patterns
Section titled “Usage Patterns”Query Caching
Section titled “Query Caching”@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); }}Contract Caching
Section titled “Contract Caching”// Service discovery caches contractsawait redis.set( `contracts:${serviceName}:${version}`, JSON.stringify(contracts), 'EX', 3600 // 1 hour TTL);Best Practices
Section titled “Best Practices”-
Set Appropriate TTLs
- Frequently changing data: 10-60 seconds
- Stable data: 5-60 minutes
- Configuration: Hours to days
-
Use Cache Keys Wisely
- Include relevant query parameters
- Use namespacing:
user:123, not just123
-
Monitor Hit Rate
- Target >80% hit rate for cached queries
- Low hit rate indicates wrong TTL or cache keys
Monitoring
Section titled “Monitoring”# Redis statsredis-cli -a redis123 INFO stats
# Key spaceredis-cli -a redis123 DBSIZE
# Memory usageredis-cli -a redis123 INFO memory