Caching with Redis
Use Redis for caching hot reads, rate limiting and short-lived data like OTPs and sessions, with clear invalidation rules.
Advanced · about 4 hours · difficulty 3/5
Learn first: Indexes and Query Performance
Redis is an in-memory key-value store. It is fast enough to sit in front of your database for data many users read at once.
Common uses
- Cache-aside: check Redis, fall back to the database on a miss, store the result with a TTL. Good for leaderboards, public company lists and expensive aggregates.
- Rate limiting: count requests per user or IP with expiring keys.
- Short-lived data: OTP codes, password reset tokens and session data with automatic expiry.
- Queues: libraries like BullMQ use Redis to store background jobs.
Invalidation
Caching is easy; keeping it correct is hard. Choose a strategy per key: short TTLs for data that can be slightly stale, explicit deletes after writes for data that must be fresh. Include versions or ids in key names.
Hosting
Run Redis in Docker locally, and use a managed service (Upstash, Redis Cloud or your platform's add-on) in production.
Pitfalls
- Caching user-specific data under a shared key and showing one student's data to another.
- No TTL, so stale data lives forever.
- Treating Redis as your primary database without understanding persistence settings.
You are ready to move on when you can add cache-aside caching to an expensive endpoint, invalidate it on writes, and show the latency improvement.
Key concepts
- Keys, TTLs and data types
- Cache-aside pattern
- Invalidation strategies
- Rate limiting with Redis
- OTPs and short-lived tokens
- Managed Redis (Upstash)
Mini project
Cache the placement statistics endpoint (branch-wise placement rate and average CTC) in Redis with a 5-minute TTL, invalidate it when a new offer is recorded, and log cache hit ratio.
Check yourself
What could go wrong if you cache the response of /api/me under the key 'me'?
Free resources
- Redis Documentation (Redis)
- Upstash Redis (Upstash)