Implement a caching layer to improve API response times and reduce database load
Build a caching system that stores frequently accessed data in memory or Redis, reducing database queries and improving application performance.
const cache = new Map();
function getCacheKey(key) {
return `cache:${key}`;
}
async function get(key) {
const cacheKey = getCacheKey(key);
const cached = cache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
return cached.value;
}
cache.delete(cacheKey);
return null;
}
async function set(key, value, ttl = 3600) {
const cacheKey = getCacheKey(key);
cache.set(cacheKey, {
value,
expires: Date.now() + ttl * 1000
});
}