6 min read
ā¢Question 21 of 28hardHow do you implement API caching?
Understanding API caching strategies.
What You'll Learn
- Caching strategies
- HTTP cache headers
- Implementation patterns
Caching Levels
- Browser/Client cache
- CDN cache
- Application cache (Redis)
- Database cache
HTTP Cache Headers
Cache-Control
code.jsJavaScript
Cache-Control: public, max-age=3600
Cache-Control: private, no-cache
Cache-Control: no-storeETag (Entity Tag)
code.jsJavaScript
// Response
ETag: "abc123"
// Next request
If-None-Match: "abc123"
// Server returns 304 Not Modified if unchangedLast-Modified
code.jsJavaScript
// Response
Last-Modified: Wed, 21 Oct 2024 07:28:00 GMT
// Next request
If-Modified-Since: Wed, 21 Oct 2024 07:28:00 GMTImplementation
code.jsJavaScript
const redis = require('redis');
const client = redis.createClient();
// Middleware for caching
async function cacheMiddleware(req, res, next) {
const key = `cache:${req.originalUrl}`;
const cached = await client.get(key);
if (cached) {
return res.json(JSON.parse(cached));
}
// Store original json method
const originalJson = res.json.bind(res);
res.json = (data) => {
client.setEx(key, 3600, JSON.stringify(data)); // Cache for 1 hour
originalJson(data);
};
next();
}
// HTTP caching headers
app.get('/users', (req, res) => {
res.set({
'Cache-Control': 'public, max-age=300',
'ETag': generateETag(users),
});
res.json(users);
});Cache Invalidation
code.jsJavaScript
// Invalidate on update
app.put('/users/:id', async (req, res) => {
await User.update(req.params.id, req.body);
await client.del(`cache:/users/${req.params.id}`);
await client.del('cache:/users');
res.json({ success: true });
});