Bird
Raised Fist0
Node.jsframework~20 mins

Redis for distributed caching in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Redis Caching Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Redis caching code snippet?

Consider this Node.js code using Redis to cache a value and then retrieve it:

import { createClient } from 'redis';

async function cacheExample() {
  const client = createClient();
  await client.connect();

  await client.set('key1', 'value1', { EX: 10 });
  const result = await client.get('key1');

  await client.disconnect();
  return result;
}

cacheExample().then(console.log);

What will be printed to the console?

Node.js
import { createClient } from 'redis';

async function cacheExample() {
  const client = createClient();
  await client.connect();

  await client.set('key1', 'value1', { EX: 10 });
  const result = await client.get('key1');

  await client.disconnect();
  return result;
}

cacheExample().then(console.log);
A"value1"
Bnull
Cundefined
DThrows a connection error
Attempts:
2 left
💡 Hint

Think about what happens immediately after setting a key with expiration.

📝 Syntax
intermediate
1:30remaining
Which option correctly sets a Redis key with a 5-minute expiration in Node.js?

Given the Redis client in Node.js, which code snippet correctly sets a key 'session' with value 'abc123' that expires after 5 minutes?

Aawait client.set('session', 'abc123', { EX: 300 });
Bawait client.set('session', 'abc123', { PX: 300000 });
Cawait client.set('session', 'abc123', 'EX', 300);
Dawait client.set('session', 'abc123', { EX: '300' });
Attempts:
2 left
💡 Hint

Check the official Redis client method signature for expiration options.

🔧 Debug
advanced
2:00remaining
Why does this Redis cache retrieval code throw an error?

Examine this code snippet:

import { createClient } from 'redis';

const client = createClient();

async function getCache() {
  const value = await client.get('missingKey');
  console.log(value.length);
}

getCache();

What error will this code throw and why?

Node.js
import { createClient } from 'redis';

const client = createClient();

async function getCache() {
  const value = await client.get('missingKey');
  console.log(value.length);
}

getCache();
ANo error, prints 0
BReferenceError: client is not defined
CSyntaxError: Unexpected token 'await'
DTypeError: Cannot read property 'length' of null
Attempts:
2 left
💡 Hint

What does Redis return when a key does not exist?

❓ state_output
advanced
2:00remaining
What is the value of 'count' after running this Redis increment code?

Consider this code snippet:

import { createClient } from 'redis';

async function incrementCounter() {
  const client = createClient();
  await client.connect();

  await client.set('count', '5');
  const count = await client.incr('count');

  await client.disconnect();
  return count;
}

incrementCounter().then(console.log);

What will be printed to the console?

Node.js
import { createClient } from 'redis';

async function incrementCounter() {
  const client = createClient();
  await client.connect();

  await client.set('count', '5');
  const count = await client.incr('count');

  await client.disconnect();
  return count;
}

incrementCounter().then(console.log);
Anull
B5
C6
DThrows a TypeError
Attempts:
2 left
💡 Hint

What does the Redis INCR command do to the string value?

🧠 Conceptual
expert
2:30remaining
Which statement best explains Redis distributed caching behavior in a multi-instance Node.js app?

You have a Node.js app running on multiple servers. Each server connects to the same Redis instance for caching. Which statement is true about the cache behavior?

AEach server has its own isolated cache in Redis, so cache data is not shared across servers.
BAll servers share the same cache data, so a cache set by one server is immediately visible to others.
CRedis automatically replicates cache data to each server's local memory for faster access.
DCache data is only visible to the server that set it until Redis is restarted.
Attempts:
2 left
💡 Hint

Think about how Redis works as a centralized cache.

Practice

(1/5)
1. What is the main benefit of using Redis for distributed caching in a Node.js application?
easy
A. It slows down data retrieval to ensure consistency.
B. It automatically writes data to disk for permanent storage.
C. It replaces the need for any database in the application.
D. It stores data in memory for very fast access across multiple servers.

Solution

  1. Step 1: Understand Redis caching purpose

    Redis stores data in memory, which is much faster than disk storage.
  2. Step 2: Recognize distributed caching advantage

    Redis can be shared across servers, speeding up data access in distributed systems.
  3. Final Answer:

    It stores data in memory for very fast access across multiple servers. -> Option D
  4. Quick Check:

    Redis = Fast in-memory cache [OK]
Hint: Redis caches in memory for speed, not disk storage [OK]
Common Mistakes:
  • Confusing Redis with a permanent database
  • Thinking Redis slows down data access
  • Assuming Redis replaces all databases
2. Which of the following is the correct way to create a Redis client using the official Node.js Redis library with async/await?
easy
A. const client = redis.createClient(); await client.connect();
B. const client = redis.connectClient();
C. const client = new Redis(); client.connect();
D. const client = redis.createClient; client.connect();

Solution

  1. Step 1: Recall official Redis client creation

    The official Redis client uses createClient() method to create a client instance.
  2. Step 2: Connect client asynchronously

    After creating, you must call await client.connect() to establish connection.
  3. Final Answer:

    const client = redis.createClient(); await client.connect(); -> Option A
  4. Quick Check:

    createClient + await connect = correct syntax [OK]
Hint: Use createClient() then await connect() to start Redis client [OK]
Common Mistakes:
  • Using incorrect method names like connectClient()
  • Forgetting to await client.connect()
  • Calling createClient without parentheses
3. Given this Node.js code using Redis client, what will be logged to the console?
const redis = require('redis');
async function test() {
  const client = redis.createClient();
  await client.connect();
  await client.set('key', 'value');
  const result = await client.get('key');
  console.log(result);
  await client.disconnect();
}
test();
medium
A. undefined
B. null
C. value
D. Error: client.get is not a function

Solution

  1. Step 1: Set key-value pair in Redis

    The code sets 'key' to 'value' using await client.set('key', 'value').
  2. Step 2: Retrieve the value for 'key'

    Using await client.get('key') returns the stored string 'value'.
  3. Final Answer:

    value -> Option C
  4. Quick Check:

    Set then get returns stored string [OK]
Hint: Set key then get key returns stored value string [OK]
Common Mistakes:
  • Expecting undefined or null instead of stored value
  • Confusing async calls without await
  • Assuming get returns an object instead of string
4. What is the error in this Node.js Redis code snippet?
const redis = require('redis');
const client = redis.createClient();
client.connect();
client.set('foo', 'bar');
const val = client.get('foo');
console.log(val);
medium
A. Redis client does not support set and get methods.
B. Missing await before async calls causing unresolved promises.
C. Calling createClient without parentheses.
D. Using require instead of import for Redis client.

Solution

  1. Step 1: Identify async Redis methods

    client.connect(), client.set(), and client.get() return promises and must be awaited.
  2. Step 2: Recognize missing await usage

    Without await, val is a promise, so console.log(val) logs a Promise object, not the value.
  3. Final Answer:

    Missing await before async calls causing unresolved promises. -> Option B
  4. Quick Check:

    Async Redis calls need await [OK]
Hint: Always await async Redis calls to get actual results [OK]
Common Mistakes:
  • Not awaiting client.get causing Promise logged
  • Assuming require is invalid in Node.js
  • Thinking Redis client lacks set/get methods
5. You want to cache user profile data in Redis to reduce database calls. Which approach correctly handles cache misses and updates the cache in Node.js?
hard
A. Try to get data from Redis; if null, fetch from DB, then set Redis cache with the data.
B. Always fetch from DB and update Redis cache without checking Redis first.
C. Set Redis cache with empty string before fetching DB to avoid cache misses.
D. Fetch from Redis and DB simultaneously and use whichever returns first.

Solution

  1. Step 1: Check Redis cache first

    Attempt to get user profile from Redis to avoid unnecessary DB calls.
  2. Step 2: On cache miss, fetch from DB and update Redis

    If Redis returns null, fetch from database, then store result in Redis for future fast access.
  3. Final Answer:

    Try to get data from Redis; if null, fetch from DB, then set Redis cache with the data. -> Option A
  4. Quick Check:

    Cache miss handled by DB fetch then cache update [OK]
Hint: Check cache first; on miss, fetch DB then update cache [OK]
Common Mistakes:
  • Skipping cache check and always querying DB
  • Setting empty cache values causing wrong data
  • Fetching DB and cache simultaneously causing race conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard