Redis is used as a fast, in-memory data store to cache data and improve performance by reducing database load in an Express app.
Click to reveal answer
beginner
How do you connect Redis to an Express app?
You install a Redis client like the 'redis' npm package, create a Redis client instance, and use it to set and get cached data inside your Express routes or middleware.
Click to reveal answer
intermediate
What does 'distributed cache' mean with Redis?
Distributed cache means Redis stores cached data centrally so multiple app servers can share the same cache, improving speed and consistency across the system.
Click to reveal answer
intermediate
Why use Redis instead of in-memory cache in Express?
Redis keeps cache outside the app process, so cache survives app restarts and can be shared across multiple servers, unlike in-memory cache which is local and temporary.
Click to reveal answer
beginner
Show a simple example of setting and getting a cache value with Redis in Express.
A. SyntaxError due to incorrect async function syntax.
B. ReferenceError because client is not defined.
C. count is a string from Redis, so count + 1 performs string concatenation instead of numeric addition.
D. No error; the count increments correctly.
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 C
Quick Check:
String + number without conversion = concatenation [OK]
Hint: Convert Redis string to number before adding [OK]
Common Mistakes:
Assuming Redis returns numbers directly
Ignoring async/await correctness
Thinking no error occurs
5. You want to cache user profile data in Redis with a 5-minute expiration in an Express app. Which code snippet correctly sets the cache with expiration and handles errors properly?
hard
A. client.set('user:123', JSON.stringify(profile)); setTimeout(() => client.del('user:123'), 300000);
B. client.set('user:123', JSON.stringify(profile), 300);
console.log('Cache set');
C. await client.set('user:123', profile, { expire: 300 });
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.