This implementation adds Redis caching layer to the PropChain frontend property data API to improve performance by reducing blockchain data fetch requests.
- Redis Connection Setup: Configurable Redis client with connection pooling and retry logic
- Property Listings Cache: 5-minute TTL for property search results and listings
- Property Details Cache: 1-minute TTL for individual property details
- Cache Hit Rate Monitoring: Real-time tracking of cache performance metrics
- Cache Invalidation: Automatic invalidation on blockchain events
/api/properties- Property listings with Redis caching/api/properties/[id]- Individual property details with Redis caching/api/cache/stats- Cache statistics and health monitoring
- Cache-First: Serve from cache when available
- Network-First: Always fetch from network, cache result
- Stale-While-Revalidate: Serve stale cache while refreshing in background
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Client App │───▶│ Next.js API │───▶│ Redis Cache │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌─────────────────┐
│ Property Service │───▶│ Blockchain Data │
└──────────────────┘ └─────────────────┘
Add these to your .env.local file:
# Redis Cache Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
REDIS_DB=0
# Blockchain Configuration (for cache invalidation)
PROPERTY_CONTRACT_ADDRESS=0x1234567890123456789012345678901234567890
BLOCKCHAIN_RPC_URL=https://mainnet.infura.io/v3/YOUR_PROJECT_ID- Property Listings: 5 minutes (300 seconds)
- Property Details: 1 minute (60 seconds)
- Search Results: 5 minutes (300 seconds)
- Autocomplete: 10 minutes (600 seconds)
// API automatically uses Redis caching
const response = await fetch('/api/properties?query=New York&sortBy=price-asc');
const data = await response.json();// API automatically uses Redis caching
const response = await fetch('/api/properties/property-123');
const data = await response.json();// Get cache performance metrics
const response = await fetch('/api/cache/stats');
const stats = await response.json();The system automatically invalidates cache when:
- Blockchain Events Detected: Property creation, updates, sales, etc.
- API Mutations: POST/PUT/DELETE operations
- TTL Expiration: Cache entries expire automatically
import { redisCacheService } from '@/lib/redisCache';
// Invalidate specific property
await redisCacheService.invalidateProperty('property-123');
// Invalidate all property cache
await redisCacheService.invalidateAllProperties();import { redisCacheService } from '@/lib/redisCache';
const health = await redisCacheService.healthCheck();
console.log(`Healthy: ${health.healthy}, Latency: ${health.latency}ms`);const stats = await redisCacheService.getStats();
console.log(`Hit Rate: ${(stats.hitRate * 100).toFixed(2)}%`);
console.log(`Total Requests: ${stats.total}`);- Every property request hits blockchain
- High latency (500ms-2s per request)
- Limited scalability
- High blockchain RPC costs
- Cache hits serve in <10ms
- 80-95% cache hit rate expected
- Reduced blockchain load
- Improved user experience
src/lib/redis.ts- Redis client configuration and connection managementsrc/lib/redisCache.ts- Redis cache service with TTL managementsrc/lib/blockchainCacheInvalidator.ts- Blockchain event listener for cache invalidationsrc/lib/initRedisCache.ts- Initialization and shutdown logicsrc/middleware.ts- Next.js middleware for Redis initializationsrc/app/api/properties/route.ts- Property listings API with Redis cachingsrc/app/api/properties/[id]/route.ts- Property details API with Redis cachingsrc/app/api/cache/stats/route.ts- Cache statistics API endpointsrc/lib/propertyService.ts- Updated to use Redis as primary cache.env.example- Added Redis configuration variables
propchain:property:{propertyId} # Individual property
propchain:listing:{filters}:{page} # Property listings
propchain:search:{filters} # Search results
propchain:autocomplete:{query} # Autocomplete suggestions
propchain:cache:stats # Cache statistics
propchain:cache:hit_rate # Hit rate counter
- Redis Cache (Primary)
- Local IndexedDB Cache (Fallback)
- Network Request (Last resort)
npm test -- --testPathPattern=redisnpm run test:e2e# Test cache hit rates
curl "http://localhost:3000/api/cache/stats"
# Test property caching
curl "http://localhost:3000/api/properties?limit=10"- Redis Server: Deploy Redis cluster or managed service
- Environment Variables: Configure production Redis settings
- Monitoring: Set up cache performance monitoring
- Backup: Configure Redis persistence and backup
# redis.conf
maxmemory 2gb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000-
Redis Connection Failed
- Check Redis server status
- Verify environment variables
- Check network connectivity
-
Cache Not Working
- Verify Redis client initialization
- Check cache TTL settings
- Monitor cache hit rates
-
High Memory Usage
- Adjust maxmemory policy
- Monitor cache size
- Implement cache cleanup
Enable debug logging:
LOG_LEVEL=debug- Cache Warming: Pre-populate cache with popular properties
- Multi-Region Caching: Redis cluster for global distribution
- Advanced Analytics: Detailed cache performance metrics
- Smart Invalidation: Predictive cache invalidation based on usage patterns
- Pipeline Operations: Batch Redis operations for better performance
- Compression: Enable Redis compression for large objects
- Connection Pooling: Optimize Redis connection management
- Redis Authentication: Use strong passwords
- Network Security: Restrict Redis network access
- Data Encryption: Enable Redis TLS in production
- Access Control: Implement proper Redis ACLs
For issues related to Redis caching:
- Check Redis server logs
- Review application logs
- Monitor cache statistics
- Test Redis connectivity
Implementation Date: April 28, 2026
Version: 1.0.0
Status: ✅ Complete