Cache invalidation strategies help keep stored data fresh and correct. They decide when to update or remove cached data so users get the latest information.
Cache invalidation strategies in Rest API
There is no single code syntax for cache invalidation because it depends on the strategy used. Common strategies include: 1. Time-based expiration: Set a time limit (TTL) after which cached data is removed. 2. Manual invalidation: Explicitly clear or update cache when data changes. 3. Event-based invalidation: Invalidate cache when certain events happen (like data update). 4. Versioning: Use version numbers or keys to identify fresh data.
Cache invalidation is often implemented with headers, cache keys, or API logic.
Choosing the right strategy depends on how often your data changes and how fresh it needs to be.
Cache-Control: max-age=60DELETE /cache/user/123On data update event:
Invalidate cache key 'product_456'Use cache key 'v2_products_list' instead of 'products_list'
This simple Flask app caches data for 5 seconds. If you request /data within 5 seconds, it returns cached data. After 5 seconds, it fetches fresh data. You can clear the cache manually by calling /invalidate.
from flask import Flask, jsonify, request import time app = Flask(__name__) cache = {} CACHE_TTL = 5 # seconds @app.route('/data') def get_data(): current_time = time.time() cached = cache.get('data') if cached and current_time - cached['time'] < CACHE_TTL: return jsonify({'source': 'cache', 'data': cached['value']}) # Simulate fresh data fetch fresh_data = {'message': 'Hello, world!', 'timestamp': current_time} cache['data'] = {'value': fresh_data, 'time': current_time} return jsonify({'source': 'fresh', 'data': fresh_data}) @app.route('/invalidate') def invalidate_cache(): cache.pop('data', None) return jsonify({'status': 'cache cleared'}) if __name__ == '__main__': app.run(debug=True)
Cache invalidation is tricky but important to avoid showing old data.
Time-based expiration is simple but may serve stale data briefly.
Manual or event-based invalidation gives more control but needs extra code.
Cache invalidation keeps cached data fresh and accurate.
Common strategies: time-based, manual, event-based, and versioning.
Choose a strategy based on how often your data changes and how fresh it must be.
Practice
Solution
Step 1: Understand time-based invalidation
Time-based invalidation removes cached data after a fixed time, ensuring data freshness automatically.Step 2: Compare with other strategies
Manual invalidation requires user action, event-based depends on data changes, and versioning uses data versions.Final Answer:
Time-based invalidation -> Option CQuick Check:
Automatic removal after time = Time-based invalidation [OK]
- Confusing manual with automatic removal
- Thinking event-based triggers on time
- Mixing versioning with time expiry
Solution
Step 1: Identify HTTP method for deletion
DELETE requests are used to remove resources, including cache entries.Step 2: Understand other methods
GET retrieves data, POST creates, and PUT updates; none remove cache.Final Answer:
Send a DELETE request to the cache endpoint -> Option DQuick Check:
DELETE removes cache entry manually [OK]
- Using GET to remove cache
- Confusing POST with deletion
- Thinking PUT deletes cache
if (dataChangedEvent) {
invalidateCache(key);
}
return getCachedData(key);
What will happen if dataChangedEvent is true?Solution
Step 1: Analyze the condition
If dataChangedEvent is true, invalidateCache(key) runs, removing cached data.Step 2: Understand cache behavior after invalidation
After invalidation, next data fetch will get fresh data, not stale cache.Final Answer:
Cache is invalidated and fresh data is fetched next time -> Option AQuick Check:
Event triggers invalidation = fresh data next fetch [OK]
- Assuming cache stays after invalidation
- Thinking cache updates automatically
- Believing invalidation causes errors
cache = { 'v1': data1 }
function getData(version) {
return cache[version];
}
// Later
cache['v2'] = newData;
What is the main bug if the client still requests v1 after update?Solution
Step 1: Understand versioning cache behavior
Old version 'v1' remains in cache, so requests for it get stale data.Step 2: Identify bug impact
Client requesting 'v1' does not see 'v2' data, causing stale responses.Final Answer:
Client gets stale data because old version is still cached -> Option BQuick Check:
Old version key returns stale data [OK]
- Assuming cache auto-updates old versions
- Expecting errors on missing keys
- Thinking client loses all cache access
Solution
Step 1: Analyze freshness requirement
Data must be fresh within 5 minutes, so time-based expiry should be 5 minutes or less.Step 2: Combine with event-based invalidation
Event-based invalidation clears cache immediately on data changes, improving freshness.Step 3: Evaluate other options
Manual invalidation is slow, versioning alone may keep stale data, and 1-hour expiry is too long.Final Answer:
Use time-based invalidation with 5-minute expiry plus event-based invalidation on data changes -> Option AQuick Check:
Combine time and event for fresh cache [OK]
- Relying only on manual invalidation
- Using too long expiry times
- Ignoring event triggers for changes
Ready to prove it?
Pass the test and this pattern moves unknown
