0
0
Rest APIprogramming~5 mins

Cache invalidation strategies in Rest API

Choose your learning style9 modes available
Introduction

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.

When your app stores data temporarily to speed up responses but the data changes often.
When you want to avoid sending outdated information to users in a web or mobile app.
When your server caches API responses but the underlying data updates regularly.
When you want to reduce load on your database by caching but still keep data accurate.
When you build a REST API that serves data which can be updated by users or other systems.
Syntax
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.

Examples
This HTTP header tells caches to keep data for 60 seconds before invalidating it (time-based expiration).
Rest API
Cache-Control: max-age=60
This API call manually removes cached data for user 123 (manual invalidation).
Rest API
DELETE /cache/user/123
When product 456 changes, the cache for it is cleared (event-based invalidation).
Rest API
On data update event:
  Invalidate cache key 'product_456'
Changing the cache key version forces clients to get fresh data (versioning).
Rest API
Use cache key 'v2_products_list' instead of 'products_list'
Sample Program

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.

Rest API
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)
OutputSuccess
Important Notes

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.

Summary

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.