Redis helps store data temporarily so many servers can share it fast. This makes apps quicker and smoother.
Redis integration for distributed cache in Express
import express from 'express'; import { createClient } from 'redis'; const app = express(); const redisClient = createClient(); redisClient.on('error', (err) => console.log('Redis Client Error', err)); (async () => { await redisClient.connect(); app.get('/cache', async (req, res) => { const key = 'someKey'; let value = await redisClient.get(key); if (!value) { value = 'some expensive data'; await redisClient.set(key, value, { EX: 60 }); // expires in 60 seconds } res.send(value); }); app.listen(3000); })();
Use createClient() from the official Redis package to connect.
Use async/await because Redis calls are asynchronous.
await redisClient.set('user:123', JSON.stringify({ name: 'Alice' }), { EX: 300 });
const data = await redisClient.get('user:123'); const user = JSON.parse(data);
await redisClient.del('user:123');
This Express app counts how many times the /visit page is loaded using Redis as a shared counter. Each visit increases the count stored in Redis and shows it.
import express from 'express'; import { createClient } from 'redis'; const app = express(); const redisClient = createClient(); redisClient.on('error', (err) => console.log('Redis Client Error', err)); (async () => { await redisClient.connect(); app.get('/visit', async (req, res) => { const visits = await redisClient.get('visits'); const newVisits = visits ? parseInt(visits) + 1 : 1; await redisClient.set('visits', newVisits.toString()); res.send(`Number of visits: ${newVisits}`); }); app.listen(3000, () => console.log('Server running on port 3000')); })();
Always handle Redis connection errors to avoid app crashes.
Set expiration times on cached data to keep cache fresh.
Use JSON.stringify and JSON.parse to store complex data structures.
Redis stores data fast and shared across servers for better app speed.
Use Redis in Express with async calls and proper error handling.
Cache data with expiration to keep it updated and save resources.
Practice
Solution
Step 1: Understand Redis role in caching
Redis stores data in memory, making data access very fast compared to disk-based storage.Step 2: Recognize distributed cache benefit
Redis can be shared across multiple servers, so all Express instances access the same cached data, improving speed and consistency.Final Answer:
It speeds up data access by storing shared data in memory across servers. -> Option AQuick Check:
Redis cache = fast shared data [OK]
- Thinking Redis replaces the database
- Confusing Redis with server scaling tool
- Assuming Redis manages Express routes
Solution
Step 1: Recall redis package usage
The modern redis package uses createClient() to create a client instance.Step 2: Connect the client
After creating, you must call client.connect() to establish connection asynchronously.Final Answer:
const client = redis.createClient(); client.connect(); -> Option BQuick Check:
createClient + connect = correct syntax [OK]
- Using non-existent methods like start() or open()
- Calling connectClient() which does not exist
- Instantiating Redis with new Redis() incorrectly
app.get('/data', async (req, res) => {
const cacheKey = 'myData';
const cached = await client.get(cacheKey);
if (cached) return res.send(JSON.parse(cached));
const data = { value: 42 };
await client.set(cacheKey, JSON.stringify(data), { EX: 10 });
res.send(data);
});What happens when you call
/data twice within 10 seconds?Solution
Step 1: Analyze first call behavior
On first call, cache is empty, so data is created and stored with 10 seconds expiration.Step 2: Analyze second call within 10 seconds
Second call finds cached data and returns it directly without recreating or resetting cache.Final Answer:
The first call stores data in cache, second call returns cached data. -> Option AQuick Check:
Cache empty first, then hit cache [OK]
- Assuming cache is refreshed on every call
- Thinking cache is never used
- Ignoring expiration time effect
app.get('/count', async (req, res) => {
const count = await client.get('count');
const newCount = count + 1;
await client.set('count', newCount);
res.send({ count: newCount });
});What issue will occur when this route is called?
Solution
Step 1: Identify data type of count
Redis stores values as strings, so count is a string when retrieved (null on first call).Step 2: Analyze addition operation
Adding number 1 to a string (after first call) results in string concatenation (e.g., "1" + 1 = "11").Step 3: Predict issue
This causes incorrect count values like 1, "11", "111", etc., instead of proper increments 1, 2, 3.Final Answer:
count is a string from Redis, so count + 1 performs string concatenation instead of numeric addition. -> Option CQuick Check:
String + number without conversion = concatenation [OK]
- Assuming Redis returns numbers directly
- Ignoring async/await correctness
- Thinking no error occurs
Solution
Step 1: Use correct Redis set syntax with expiration
The redis client set method accepts options with EX for expiration in seconds, so { EX: 300 } is correct.Step 2: Handle errors with try-catch
Since set is async, wrapping in try-catch ensures errors are caught and logged properly.Step 3: Check other options for mistakes
client.set('user:123', JSON.stringify(profile), 300); console.log('Cache set'); misses async/await and uses wrong expiration argument; C uses wrong option key; D manually deletes cache but is less efficient.Final Answer:
try { await client.set('user:123', JSON.stringify(profile), { EX: 300 }); } catch (err) { console.error('Cache error:', err); } -> Option DQuick Check:
set with EX + try-catch = correct [OK]
- Passing expiration as a separate argument
- Not stringifying objects before caching
- Ignoring async error handling
Ready to prove it?
Pass the test and this pattern moves unknown
