Bird
Raised Fist0
Expressframework~20 mins

Cache invalidation strategies in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Cache Invalidation Types
Which cache invalidation strategy immediately removes cached data when the underlying data changes?
ATime-based expiration where cache clears after a set time
BLazy invalidation where cache is cleared only on next access
CManual invalidation triggered by data update events
DCache warming that preloads data before expiration
Attempts:
2 left
💡 Hint
Think about which method reacts instantly to data changes.
❓ component_behavior
intermediate
2:00remaining
Cache Behavior in Express Middleware
Given an Express middleware that caches responses with a TTL of 10 seconds, what happens if a client requests the same resource twice within 5 seconds?
Express
app.use((req, res, next) => {
  const key = req.originalUrl;
  if (cache[key]) {
    res.send(cache[key]);
  } else {
    res.sendResponse = res.send;
    res.send = (body) => {
      cache[key] = body;
      setTimeout(() => { delete cache[key]; }, 10000);
      res.sendResponse(body);
    };
    next();
  }
});
AThe cache never expires because setTimeout is not cleared
BThe second request triggers next() and fetches fresh data
CThe cache clears immediately after the first request
DThe second request returns cached data instantly without calling next()
Attempts:
2 left
💡 Hint
Consider what happens when cache[key] exists.
🔧 Debug
advanced
2:00remaining
Identifying Cache Invalidation Bug
Why does this Express cache invalidation code fail to clear the cache after data update?
Express
app.post('/update', (req, res) => {
  updateData(req.body);
  delete cache[req.originalUrl];
  res.send('Updated');
});
ACache key uses req.originalUrl which differs from cached GET request URL
Bdelete operator cannot remove properties from cache object
CupdateData is asynchronous but cache deletion runs before update completes
Dres.send should be called before deleting cache
Attempts:
2 left
💡 Hint
Check if the cache key matches the cached data key.
📝 Syntax
advanced
2:00remaining
Correct Cache Invalidation Syntax
Which option correctly invalidates a cache entry for a given key in an Express app using a simple object cache?
Express
const cache = {};

function invalidateCache(key) {
  // Invalidate cache here
}
Acache.remove(key);
Bdelete cache[key];
Ccache[key] = null;
Dcache.pop(key);
Attempts:
2 left
💡 Hint
Think about how to remove a property from an object in JavaScript.
❓ state_output
expert
3:00remaining
Cache State After Multiple Requests
Consider this Express cache middleware with manual invalidation. After these requests, what keys remain in the cache object? 1. GET /data (cache miss, stores response) 2. POST /data (updates data, invalidates cache) 3. GET /data (cache miss, stores new response) 4. GET /info (cache miss, stores response)
Express
const cache = {};

app.use((req, res, next) => {
  if (req.method === 'GET') {
    if (cache[req.originalUrl]) {
      res.send(cache[req.originalUrl]);
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        cache[req.originalUrl] = body;
        res.sendResponse(body);
      };
      next();
    }
  } else if (req.method === 'POST') {
    updateData(req.body);
    delete cache['/data'];
    res.send('Updated');
  } else {
    next();
  }
});
A['/data', '/info']
B['/data']
C['/info']
D[]
Attempts:
2 left
💡 Hint
Remember the POST request deletes '/data' cache key.

Practice

(1/5)
1. What is the main purpose of cache invalidation in an Express app?
easy
A. To permanently store data without expiration
B. To increase server CPU usage
C. To keep cached data fresh and up-to-date
D. To disable caching completely

Solution

  1. Step 1: Understand cache invalidation

    Cache invalidation means removing or updating cached data when it becomes outdated.
  2. Step 2: Purpose in Express apps

    Express uses cache invalidation to ensure users get fresh data, not stale cached content.
  3. Final Answer:

    To keep cached data fresh and up-to-date -> Option C
  4. Quick Check:

    Cache invalidation = fresh data [OK]
Hint: Cache invalidation means keeping data fresh [OK]
Common Mistakes:
  • Thinking cache invalidation disables caching
  • Confusing cache invalidation with permanent storage
  • Believing it increases CPU usage intentionally
2. Which of the following is the correct way to set a Cache-Control header in Express to prevent caching?
easy
A. res.set('Cache-Control', 'max-age=3600')
B. res.set('Cache-Control', 'no-store')
C. res.set('Cache-Control', 'public, max-age=86400')
D. res.set('Cache-Control', 'private, max-age=600')

Solution

  1. Step 1: Understand Cache-Control values

    'no-store' tells browsers not to cache the response at all.
  2. Step 2: Identify the option that prevents caching

    res.set('Cache-Control', 'no-store') uses 'no-store', which disables caching completely.
  3. Final Answer:

    res.set('Cache-Control', 'no-store') -> Option B
  4. Quick Check:

    Prevent caching = 'no-store' [OK]
Hint: Use 'no-store' to disable caching in Cache-Control [OK]
Common Mistakes:
  • Using 'max-age' which allows caching
  • Confusing 'private' with disabling cache
  • Missing quotes around header value
3. Consider this Express middleware code snippet:
app.use((req, res, next) => {
  res.set('Cache-Control', 'public, max-age=10');
  next();
});

app.get('/data', (req, res) => {
  res.json({ time: Date.now() });
});
What will happen if a user requests /data twice within 10 seconds?
medium
A. The second request will return cached data from the first request
B. The second request will always fetch fresh data from the server
C. The server will throw an error on the second request
D. The cache will be cleared after the first request

Solution

  1. Step 1: Analyze Cache-Control header

    'public, max-age=10' means cache is valid for 10 seconds.
  2. Step 2: Effect on repeated requests

    Within 10 seconds, the browser or proxy can serve cached response without contacting server.
  3. Final Answer:

    The second request will return cached data from the first request -> Option A
  4. Quick Check:

    max-age=10 caches for 10 seconds [OK]
Hint: max-age sets cache duration in seconds [OK]
Common Mistakes:
  • Assuming server always sends fresh data
  • Confusing 'public' with disabling cache
  • Thinking cache clears immediately after first request
4. You wrote this Express route to disable caching:
app.get('/info', (req, res) => {
  res.set('Cache-Control', 'no-cache');
  res.json({ message: 'Hello' });
});
But clients still see cached responses. What is the likely problem?
medium
A. Express does not support Cache-Control headers
B. The header name "Cache-Control" is misspelled
C. res.json() automatically overrides Cache-Control headers
D. Using "no-cache" allows caching but requires revalidation

Solution

  1. Step 1: Understand "no-cache" meaning

    'no-cache' means caches can store response but must revalidate before reuse.
  2. Step 2: Why clients see cached data

    If revalidation is skipped or proxy ignores it, cached data may be served.
  3. Final Answer:

    Using "no-cache" allows caching but requires revalidation -> Option D
  4. Quick Check:

    'no-cache' means revalidate before reuse [OK]
Hint: "no-cache" means revalidate, not disable caching [OK]
Common Mistakes:
  • Thinking 'no-cache' disables caching completely
  • Assuming header name is wrong without checking
  • Believing res.json() removes headers
5. You want to cache user profile data in Express but ensure it updates immediately after a user changes their info. Which cache invalidation strategy is best?
hard
A. Set a long max-age and manually clear cache on user update
B. Use 'no-store' to never cache user profiles
C. Set a short max-age and rely on automatic expiration
D. Cache indefinitely and ignore updates

Solution

  1. Step 1: Understand caching user profiles

    User profiles benefit from caching for speed but must update after changes.
  2. Step 2: Choose invalidation strategy

    Long max-age improves performance; manual cache clearing on update ensures fresh data.
  3. Final Answer:

    Set a long max-age and manually clear cache on user update -> Option A
  4. Quick Check:

    Manual invalidation + long cache = fresh and fast [OK]
Hint: Use manual cache clear after updates for fresh user data [OK]
Common Mistakes:
  • Using 'no-store' loses caching benefits
  • Relying only on short max-age causes frequent reloads
  • Ignoring cache invalidation leads to stale data
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