Prompt
How do I use an in-memory store as a shared cache for microservices?
Latest observation
Using an in-memory store as a shared cache for microservices usually means putting a fast external cache in front of your services so they can all read/write the same cached data without hitting the database every time.
Common options
- Redis — most common choice
- Memcached — simpler, pure cache
- Hazelcast / Ignite — distributed in-memory data grids, more feature-rich
Typical architecture
Each microservice:
- Receives a request
- Checks the shared cache first
- If found, returns cached data
- If not found, fetches from DB or downstream service
- Stores the result in the cache with a TTL
- Returns the result
This is usually called the cache-aside pattern.
Cache-aside pattern
Read flow
service -> cache.get(key)- If hit: return cached value
- If miss:
- query DB/service
cache.set(key, value, ttl)- return value
Write flow
When data changes:
- Write to the source of truth first
- Invalidate or update the cache
cache.delete(key)orcache.set(key, newValue, ttl)
Example with Redis
Pseudocode
def get_user(user_id):
key = f"user:{user_id}"
cached = redis.get(key)
if cached:
return deserialize(cached)
user = db.query_user(user_id)
redis.set(key, serialize(user), ex=300) # 5 min TTL
return user
Write/update
def update_user(user_id, new_data):
db.update_user(user_id, new_data)
redis.delete(f"user:{user_id}") # invalidate
Important design considerations
1. Choose what to cache
Best candidates:
- Frequently read, infrequently changed data
- Expensive computations
- Reference data
- Session/auth tokens
- API responses that are safe to reuse
Avoid caching:
- Highly volatile data
- Large objects that change constantly
- Sensitive data unless properly protected
2. Use TTLs
Always set expiration so stale data doesn’t live forever.
Example TTLs:
- User profile: 5–30 min
- Product catalog: 1–10 min
- Configuration data: longer, with invalidation
3. Handle cache invalidation carefully
This is the hardest part.
Common strategies:
- Delete-on-write: remove cache entry after DB update
- Write-through: update cache and DB together
- Write-behind: update cache first, persist later
- Event-driven invalidation: publish events when data changes so all services invalidate
For microservices, event-driven invalidation is often useful when multiple services depend on the same cached entity.
4. Prevent cache stampede
If many requests miss at once, they may all hit the DB.
Mitigations:
- Use request coalescing / locks
- Add random jitter to TTLs
- Use stale-while-revalidate patterns
- Prewarm hot keys
5. Keep cache keys consistent
Use a clear naming convention:
user:123order:456product:list:category=books
Include versioning if needed:
v1:user:123
6. Avoid using cache as the source of truth
The cache should support your system, not replace durable storage.
Your primary store should remain:
- database
- event store
- persistent data source
7. Make it shared and resilient
If all microservices use the same cache cluster:
- run it as a separate service
- enable replication/sentinel/cluster mode if supported
- monitor memory usage, eviction, latency, hit rate
When to use a shared cache
Good use cases:
- Shared reference data across services
- Aggregated API data
- Rate limiting counters
- Session storage
- Authentication tokens
- Expensive computed results
Potentially bad use cases:
- Business-critical state that cannot be lost
- Data that requires strong consistency
- Very large datasets that won’t fit in memory
Best practices checklist
- Use Redis or another distributed cache
- Apply TTLs to all entries
- Prefer cache-aside for simplicity
- Invalidate on writes
- Protect against stampedes
- Monitor hit rate and latency
- Secure the cache network access
- Don’t treat cache as durable storage
Quick recommendation
If you’re starting out, use:
- Redis
- Cache-aside pattern
- TTL + invalidation on write
- Event-driven cache invalidation if multiple services share the same data
If you want, I can also show:
- a real implementation in Node.js / Python / Java / Go, or
- how to design this for Kubernetes + Redis.