How TTL, Event-Based, and Cache-Aside Solve the Problem of Data Staleness
Every developer has faced a situation: data on the site is outdated, the user sees obsolete information, and logs are silent. The reason is the lack of a well-thought-out cache invalidation strategy. In one of our e-commerce projects, improper invalidation caused database load to triple and response time to increase by 200 ms. After implementing the correct strategy, the hit rate reached 95%, and load dropped by 4x. Proper invalidation is not a luxury but a necessity for any production service.
We design and implement turnkey invalidation strategies: from choosing an approach to writing code and monitoring. In 3–5 business days, you get a reliable mechanism that guarantees data freshness without performance loss. Our experience: over 50 implemented projects with caching for high-load systems.
How to Choose an Invalidation Strategy?
TTL, Cache-Aside, Event-Based: Comparison of Approaches
The choice of strategy depends on the acceptable data update delay. TTL is the simplest: data is stored with a timer, after which it reloads. The update delay is up to 5 minutes. Cache-Aside: the application first checks the cache; on a miss, it loads from the database and saves with a TTL. The delay is up to 1 minute with proper invalidation. Event-Based: when data changes, an event is generated that immediately invalidates the cache. The delay is less than 1 second. The difference between TTL and Event-Based can be up to 15x: Event-Based updates data in 200 ms, TTL up to 5 minutes.
Event-Based invalidation is harder to implement, but for frequently changing data (product catalog, exchange rates) it is indispensable. Cache-Aside is the golden mean, suitable for most scenarios. We often combine: for user profiles — Cache-Aside with TTL of 10 minutes, for the catalog — Event-Based with immediate invalidation.
| Criterion | TTL | Cache-Aside | Event-Based |
|---|---|---|---|
| Data freshness | Up to 5 min | Up to 1 min | < 1 sec |
| Implementation complexity | Low | Medium | High |
| DB load | Low | Medium | High (events) |
| Typical use case | Static data | User profiles | Frequently changing catalogs |
Advantages of Cache Tagging
Tags (cache tags) allow invalidating groups of keys by a single event. For example, when a product category changes, clear all caches associated with that category, including product lists and category pages. This simplifies logic and reduces unnecessary clears. Tags are especially useful when the same data is cached in different representations.
Practical Implementation with Examples
Cache-Aside with TTL (Python/Redis)
import redis import json from functools import wraps redis_client = redis.Redis(host='redis', decode_responses=True) def cached(key_template, ttl=300): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): cache_key = key_template.format(*args, **kwargs) cached_val = redis_client.get(cache_key) if cached_val: return json.loads(cached_val) result = func(*args, **kwargs) redis_client.setex(cache_key, ttl, json.dumps(result)) return result return wrapper return decorator @cached("user:{0}", ttl=600) def get_user(user_id): return db.query("SELECT * FROM users WHERE id = %s", user_id) def update_user(user_id, data): db.execute("UPDATE users SET ... WHERE id = %s", user_id) redis_client.delete(f"user:{user_id}") # Invalidate related keys redis_client.delete(f"user_posts:{user_id}") redis_client.delete(f"user_profile_full:{user_id}") Event-Based Invalidation via Queue
# subscriber (cache service) def on_user_changed(channel, method, properties, body): event = json.loads(body) patterns_to_invalidate = [ f"user:{event['id']}", f"user_full:{event['id']}", ] if 'role' in (event.get('fields') or []): patterns_to_invalidate.append(f"user_permissions:{event['id']}") for key in patterns_to_invalidate: redis_client.delete(key) Cache Tags (PHP)
class TaggedCache { public function put(string $key, $value, int $ttl, array $tags = []): void { Redis::setex($key, $ttl, serialize($value)); foreach ($tags as $tag) { Redis::sadd("cache_tag:{$tag}", $key); Redis::expire("cache_tag:{$tag}", $ttl + 60); } } public function invalidateByTag(string $tag): void { $keys = Redis::smembers("cache_tag:{$tag}"); if (!empty($keys)) { Redis::del($keys); } Redis::del("cache_tag:{$tag}"); } } Stale-While-Revalidate (Python)
import threading def get_with_stale_revalidate(key, fetch_fn, ttl=300, stale_ttl=60): data = redis_client.get(key) if data: result = json.loads(data) remaining_ttl = redis_client.ttl(key) if remaining_ttl < stale_ttl: lock_key = f"revalidate_lock:{key}" if redis_client.set(lock_key, 1, nx=True, ex=30): threading.Thread( target=lambda: _background_refresh(key, fetch_fn, ttl) ).start() return result # Cache miss — synchronous fetch result = fetch_fn() redis_client.setex(key, ttl, json.dumps(result)) return result def _background_refresh(key, fetch_fn, ttl): try: result = fetch_fn() redis_client.setex(key, ttl, json.dumps(result)) finally: redis_client.delete(f"revalidate_lock:{key}") TTL Strategies by Data Type
| Data type | TTL | Invalidation |
|---|---|---|
| User profile | 10 min | On update |
| Product list | 5 min | On product change |
| App config | 1 hour | On deploy |
| Exchange rates | 30 sec | On event |
| User permissions | 5 min | On role change |
| HTML pages | 1 hour | On publish |
Monitoring Cache Efficiency
The key metric is hit rate (fraction of requests served from cache). Typical value for a well-configured cache is 90-95%. If hit rate falls below 80%, it's a signal to review the strategy. We set up monitoring via Prometheus and Redis exporter, sending alerts on anomalies.
Process and Timeline
- Audit of current caching architecture.
- Selection of optimal strategy (TTL, Event-Based, Cache-Aside, or combined).
- Implementation on your stack (Python/Redis, PHP/Laravel, Node.js).
- Documentation of cache keys and invalidation processes.
- Monitoring of hit rate with alerts if it drops below 80%.
Developing a strategy with Cache Tags and Event-Based approach takes 3–5 business days. Cost is calculated individually after analyzing your project.
Our Experience
We have implemented over 50 projects with caching for high-load systems. Each project undergoes load testing to ensure the hit rate stays above 90%. We guarantee quality and reliability.
Order a consultation — we will help you choose the optimal invalidation strategy. Contact us for a detailed audit of your caching.







