#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
•Question 21 of 28hard

How do you implement API caching?

Understanding API caching strategies.

What You'll Learn

  • Caching strategies
  • HTTP cache headers
  • Implementation patterns

Caching Levels

  1. Browser/Client cache
  2. CDN cache
  3. Application cache (Redis)
  4. Database cache

HTTP Cache Headers

Cache-Control

code.jsJavaScript
Cache-Control: public, max-age=3600
Cache-Control: private, no-cache
Cache-Control: no-store

ETag (Entity Tag)

code.jsJavaScript
// Response
ETag: "abc123"

// Next request
If-None-Match: "abc123"

// Server returns 304 Not Modified if unchanged

Last-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 GMT

Implementation

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 });
});