Improving API performance using request caching

Loading

API requests can significantly slow down an application if the same data is repeatedly fetched from the server. Request caching helps reduce redundant API calls, improve performance, and enhance the user experience by storing previously retrieved data.


1. What is Request Caching?

Request caching stores previously fetched API responses so that subsequent requests reuse the stored data instead of making a new API call.

Benefits of Request Caching:
Reduces API load → Fewer server requests
Speeds up UI rendering → Faster data retrieval
Enhances user experience → Smooth navigation
Improves offline support → Cached data is available when offline


2. Techniques for API Request Caching in AngularJS

1. Using $cacheFactory to Cache API Responses

AngularJS provides the $cacheFactory service to cache API responses.

Example: Caching HTTP Requests

app.factory('DataService', function($http, $cacheFactory) {
var dataCache = $cacheFactory('dataCache'); // Create a cache

return {
getData: function(url) {
return $http.get(url, { cache: dataCache }); // Enable caching
}
};
});

How it works?

  • The $http.get(url, { cache: dataCache }) stores the response in dataCache.
  • When the same URL is requested again, the cached data is returned instead of calling the server.

Best Use Case: Ideal for static data that doesn’t change frequently.


2. Using $httpProvider.defaults.cache = true for Auto-Caching

Instead of manually enabling caching for each request, you can globally enable it.

Enable Caching for All $http Requests

app.config(function($httpProvider) {
$httpProvider.defaults.cache = true;
});

When to Use?

  • If most API responses can be reused across multiple users.
  • Great for non-sensitive data (e.g., configuration settings, lookup values).

3. Implementing Custom Cache Service for More Control

For more flexibility, create a custom caching service using $cacheFactory.

Example: Creating a Cache Service

app.factory('CacheService', function($cacheFactory) {
var cache = $cacheFactory('apiCache');

return {
put: function(key, value) {
cache.put(key, value);
},
get: function(key) {
return cache.get(key);
},
remove: function(key) {
cache.remove(key);
},
clear: function() {
cache.removeAll();
}
};
});

Usage in API Calls

app.factory('DataService', function($http, CacheService) {
return {
getData: function(url) {
var cachedData = CacheService.get(url);
if (cachedData) {
return Promise.resolve(cachedData); // Return cached data
}
return $http.get(url).then(function(response) {
CacheService.put(url, response.data); // Store in cache
return response.data;
});
}
};
});

When to Use?

  • When you need custom expiration times for cached data.
  • When handling different cache strategies (e.g., per-user caching).

4. Caching API Responses in localStorage for Persistent Data

Use localStorage to store API data beyond the session, so users don’t have to fetch data repeatedly.

Example: Storing API Responses in localStorage

app.factory('LocalCacheService', function() {
return {
set: function(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
remove: function(key) {
localStorage.removeItem(key);
},
clear: function() {
localStorage.clear();
}
};
});

Using It in API Calls

app.factory('DataService', function($http, LocalCacheService) {
return {
getData: function(url) {
var cachedData = LocalCacheService.get(url);
if (cachedData) {
return Promise.resolve(cachedData);
}
return $http.get(url).then(function(response) {
LocalCacheService.set(url, response.data);
return response.data;
});
}
};
});

Best Use Case:

  • Ideal for user preferences, settings, and offline support.
  • Ensures faster reloads after a page refresh.

5. Using Service Workers for API Caching (Progressive Web Apps – PWA)

For advanced caching, service workers store API responses offline.

Example: Caching API Responses with Service Workers

self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});

Best Use Case:

  • Great for offline-first applications.
  • Reduces API calls by serving cached responses.

3. Implementing Cache Expiration & Invalidations

Caching API responses forever is not ideal. You need to set expiration times and clear outdated cache.

1. Time-Based Cache Expiry

Modify the cache service to include an expiration time.

Example: Auto-Expire Cached Data

app.factory('CacheService', function($cacheFactory) {
var cache = $cacheFactory('apiCache');

return {
put: function(key, value, expireInMinutes) {
cache.put(key, {
data: value,
timestamp: new Date().getTime(),
expire: expireInMinutes * 60 * 1000
});
},
get: function(key) {
var cached = cache.get(key);
if (!cached) return null;

var now = new Date().getTime();
if (now - cached.timestamp > cached.expire) {
cache.remove(key); // Remove expired cache
return null;
}
return cached.data;
},
clear: function() {
cache.removeAll();
}
};
});

This prevents serving outdated data.


4. Summary – Best Practices for Request Caching

TechniqueWhen to Use?
$cacheFactory for HTTP cachingBest for short-term caching of API responses
Global $httpProvider.defaults.cache = trueWhen caching should be applied to all requests
Custom Cache ServiceWhen you need fine control over caching policies
Using localStorage for persistenceWhen data should be saved even after page reload
Service WorkersBest for Progressive Web Apps (PWA) and offline support
Cache Expiration StrategyEnsures data is fresh and prevents outdated cache

Leave a Reply

Your email address will not be published. Required fields are marked *