Bird
Raised Fist0
Expressframework~20 mins

Why caching improves performance in Express - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Caching Mastery in Express
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
How does caching reduce server load in Express?

Imagine your Express server handles many requests for the same data. How does caching help reduce the server's work?

ACaching stores the data temporarily so the server can quickly send it without recalculating or fetching it again.
BCaching deletes old data to free up memory and speed up the server.
CCaching forces the server to process every request from scratch to ensure fresh data.
DCaching slows down the server by adding extra steps before sending data.
Attempts:
2 left
💡 Hint

Think about how remembering answers helps you avoid repeating work.

❓ component_behavior
intermediate
2:00remaining
What happens when Express serves cached content?

Consider an Express route that caches API responses. What is the main effect on response time when a cached response is available?

Express
app.get('/data', (req, res) => {
  if (cache.has('data')) {
    res.send(cache.get('data'));
  } else {
    const data = fetchDataFromDB();
    cache.set('data', data);
    res.send(data);
  }
});
AResponse time is unpredictable because cache may cause errors.
BResponse time is slower because the server checks the cache first.
CResponse time is faster because data is sent directly from cache without waiting for the database.
DResponse time is the same because the database is always queried.
Attempts:
2 left
💡 Hint

Think about skipping the slowest step.

🔧 Debug
advanced
2:30remaining
Identify the caching mistake causing stale data in Express

Look at this Express caching code. Why might users see outdated data?

Express
const cache = new Map();

app.get('/info', (req, res) => {
  if (cache.has('info')) {
    res.send(cache.get('info'));
  } else {
    const info = fetchLatestInfo();
    cache.set('info', info);
    res.send(info);
  }
});
AThe fetchLatestInfo function is asynchronous but used synchronously.
BThe cache is cleared too often, causing frequent database calls.
CThe cache key 'info' is misspelled, so cache is never used.
DThe cache never expires, so old data stays forever without updates.
Attempts:
2 left
💡 Hint

Think about how long cached data stays valid.

📝 Syntax
advanced
2:30remaining
Which caching code snippet correctly caches JSON responses in Express?

Choose the code that properly caches and sends JSON data in Express.

A
app.get('/user', (req, res) => {
  if (cache.user) {
    res.json(cache.user);
  } else {
    const user = getUser();
    cache.user = user;
    res.json(user);
  }
});
B
app.get('/user', (req, res) => {
  if (cache.user) {
    res.send(JSON.stringify(cache.user));
  } else {
    const user = getUser();
    cache.user = JSON.stringify(user);
    res.send(user);
  }
});
C
app.get('/user', (req, res) => {
  if (cache.user) {
    res.json(JSON.parse(cache.user));
  } else {
    const user = getUser();
    cache.user = user;
    res.send(user);
  }
});
D
app.get('/user', (req, res) => {
  if (cache.user) {
    res.send(cache.user);
  } else {
    const user = getUser();
    cache.user = JSON.stringify(user);
    res.send(JSON.parse(cache.user));
  }
});
Attempts:
2 left
💡 Hint

Remember Express has a method to send JSON directly.

❓ state_output
expert
3:00remaining
What is the cache state after multiple requests?

Given this Express caching code, what is the content of cache after three requests to /count?

Express
const cache = {};

app.get('/count', (req, res) => {
  if (!cache.count) {
    cache.count = 1;
  } else {
    cache.count += 1;
  }
  res.send(`Count is ${cache.count}`);
});
A{}
B{"count": 3}
C{"count": 0}
D{"count": 1}
Attempts:
2 left
💡 Hint

Each request increases the count by one if cached.

Practice

(1/5)
1. Why does caching improve performance in an Express app?
easy
A. It slows down the server to handle more requests
B. It increases the size of the server's memory permanently
C. It stores data temporarily to avoid repeating expensive operations
D. It deletes old data to free up space immediately

Solution

  1. Step 1: Understand caching purpose

    Caching saves results of expensive operations temporarily so they can be reused.
  2. Step 2: Relate caching to performance

    By reusing stored data, the server avoids repeating slow tasks, speeding up responses.
  3. Final Answer:

    It stores data temporarily to avoid repeating expensive operations -> Option C
  4. Quick Check:

    Caching = Temporary storage for speed [OK]
Hint: Caching saves repeated work to speed up responses [OK]
Common Mistakes:
  • Thinking caching permanently increases memory
  • Believing caching slows down the server
  • Confusing caching with deleting data
2. Which Express middleware syntax correctly sets a simple cache header for 1 hour?
easy
A. res.cacheControl('3600')
B. res.set('Cache-Control', 'max-age=3600')
C. res.header('Cache-Control', 'no-cache')
D. res.cache('max-age=3600')

Solution

  1. Step 1: Identify correct Express method

    Express uses res.set() or res.header() to set headers; res.set() is common.
  2. Step 2: Check cache header format

    'Cache-Control' with 'max-age=3600' sets cache for 3600 seconds (1 hour).
  3. Final Answer:

    res.set('Cache-Control', 'max-age=3600') -> Option B
  4. Quick Check:

    Correct header syntax = res.set('Cache-Control', 'max-age=3600') [OK]
Hint: Use res.set() with 'Cache-Control' header [OK]
Common Mistakes:
  • Using non-existent res.cache() method
  • Setting 'no-cache' disables caching
  • Wrong method names like res.cacheControl()
3. Consider this Express route with caching logic:
app.get('/data', (req, res) => {
  if (cache.data) {
    res.send(cache.data);
  } else {
    const result = expensiveCalculation();
    cache.data = result;
    res.send(result);
  }
});
What happens on the second request to '/data'?
medium
A. The server sends cached data without recalculating
B. The server runs expensiveCalculation() again
C. The server returns an error because cache.data is undefined
D. The server sends an empty response

Solution

  1. Step 1: Analyze first request behavior

    On first request, cache.data is empty, so expensiveCalculation() runs and result is cached.
  2. Step 2: Analyze second request behavior

    On second request, cache.data exists, so server sends cached data directly without recalculating.
  3. Final Answer:

    The server sends cached data without recalculating -> Option A
  4. Quick Check:

    Cache hit = reuse data [OK]
Hint: Cached data skips recalculation on repeat requests [OK]
Common Mistakes:
  • Assuming calculation runs every time
  • Thinking cache.data is undefined on second request
  • Believing server sends empty response
4. This Express caching code has a bug:
app.get('/info', (req, res) => {
  if (cache.info) {
    res.send(cache.info);
  } else {
    const data = fetchData();
    cache.info = data;
    res.send(data);
  }
});
fetchData() is asynchronous and returns a Promise. What is the main issue?
medium
A. fetchData() blocks the server, causing timeout
B. cache.info is never set, causing infinite loop
C. res.send() cannot send strings
D. res.send() is called before fetchData() resolves, sending a Promise object

Solution

  1. Step 1: Identify async function usage

    fetchData() returns a Promise but code treats it as synchronous.
  2. Step 2: Understand res.send() timing

    res.send(data) runs immediately, sending the unresolved Promise, not actual data.
  3. Final Answer:

    res.send() is called before fetchData() resolves, sending a Promise object -> Option D
  4. Quick Check:

    Async function needs await before sending [OK]
Hint: Await async calls before sending response [OK]
Common Mistakes:
  • Ignoring async nature of fetchData()
  • Assuming cache is never set
  • Thinking res.send() can't send strings
5. You want to cache user profile data in Express but ensure it updates every 10 minutes. Which approach best balances caching and data freshness?
hard
A. Store data in cache with a timestamp; refresh cache if older than 10 minutes
B. Cache data forever without expiration to maximize speed
C. Never cache user data to always get fresh info
D. Clear cache manually only when server restarts

Solution

  1. Step 1: Understand caching with expiration

    To keep data fresh, cache should have a time limit after which it refreshes.
  2. Step 2: Evaluate options for freshness and speed

    Store data in cache with a timestamp; refresh cache if older than 10 minutes uses timestamp to refresh cache every 10 minutes, balancing speed and freshness.
  3. Final Answer:

    Store data in cache with a timestamp; refresh cache if older than 10 minutes -> Option A
  4. Quick Check:

    Timed cache refresh = Store data in cache with a timestamp; refresh cache if older than 10 minutes [OK]
Hint: Use timestamps to refresh cache periodically [OK]
Common Mistakes:
  • Caching forever causes stale data
  • Never caching loses speed benefits
  • Manual cache clearing is unreliable
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