Junior — Middle
Have you had experience implementing and using caching in Node.js applications?
sobes.tech AI
Answer from AI
Yes, I have experience implementing caching in Node.js applications to improve performance and reduce load on databases or external APIs.
Most often, I used Redis as an external cache, as well as built-in in-memory cache for small tasks. For example, when querying a database, you can first check the cache, and if the data is there — return it, otherwise fetch from the database and store in the cache.
An example using Redis and the redis library:
const redis = require('redis');
const client = redis.createClient();
async function getUser(userId) {
const cacheKey = `user:${userId}`;
const cached = await client.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
const user = await db.getUserById(userId); // database query
await client.set(cacheKey, JSON.stringify(user), 'EX', 3600); // cache for 1 hour
return user;
}
This approach significantly reduces response time and load on the database.