Bird
Raised Fist0
Rest APIprogramming~20 mins

Cache invalidation strategies in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Cache Invalidation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this cache invalidation simulation?

Consider a REST API cache that stores user data. The cache invalidation is triggered when a user updates their profile. What will be the output of the following Python simulation code?

Rest API
cache = {'user_1': 'John Doe', 'user_2': 'Jane Smith'}

# User 1 updates profile
cache['user_1'] = 'John A. Doe'

# Invalidate cache for user_2
cache.pop('user_2', None)

print(cache)
A{'user_1': 'John A. Doe', 'user_2': 'Jane Smith'}
B{'user_1': 'John Doe', 'user_2': 'Jane Smith'}
C{'user_1': 'John A. Doe'}
D{'user_2': 'Jane Smith'}
Attempts:
2 left
💡 Hint

Think about what happens when you update a cache entry and then remove another.

🧠 Conceptual
intermediate
1:30remaining
Which cache invalidation strategy is demonstrated here?

A REST API cache is set to expire entries automatically after 10 minutes. Which cache invalidation strategy does this represent?

ATime-to-live (TTL) expiration
BWrite-through caching
CManual invalidation
DCache aside
Attempts:
2 left
💡 Hint

Think about automatic expiration based on time.

🔧 Debug
advanced
2:30remaining
Why does this cache invalidation code fail to remove the stale entry?

Look at the code below that tries to invalidate a cache entry after updating the database. Why does the stale cache entry remain?

Rest API
cache = {'item_1': 'old_value'}

def update_database():
    # Simulate database update
    return 'new_value'

new_val = update_database()

# Later code tries to remove stale cache but fails
if 'item_1' in cache:
    pass  # supposed to remove stale cache but does nothing

print(cache)
AThe cache invalidation code does not remove the entry; it only checks existence.
BThe cache dictionary is immutable, so assignment fails.
CThe cache entry is overwritten, so no stale entry remains.
DThe update_database function returns null, so cache is not updated.
Attempts:
2 left
💡 Hint

Look carefully at the 'if' block that is supposed to remove the cache entry.

📝 Syntax
advanced
1:30remaining
Which option causes a runtime error in cache invalidation code?

Identify the option that will cause a runtime error when trying to invalidate a cache entry in Python.

Rest API
cache = {'key1': 'value1', 'key2': 'value2'}
Acache.pop('key1')
Bdel cache['key2']
Ccache['key1'] = None
Dcache.remove('key1')
Attempts:
2 left
💡 Hint

Check which method is not valid for Python dictionaries.

🚀 Application
expert
3:00remaining
How many cache entries remain after this sequence of invalidations?

Given the following cache invalidation sequence, how many entries remain in the cache?

Rest API
cache = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Invalidate entries where value is even
cache = {k: v for k, v in cache.items() if v % 2 != 0}

# Add new entry
cache['e'] = 5

# Remove entry 'a'
cache.pop('a', None)

print(len(cache))
A1
B2
C4
D3
Attempts:
2 left
💡 Hint

Count entries after filtering, adding, and removing.

Practice

(1/5)
1. Which cache invalidation strategy automatically removes cached data after a set period of time?
easy
A. Manual invalidation
B. Event-based invalidation
C. Time-based invalidation
D. Versioning invalidation

Solution

  1. Step 1: Understand time-based invalidation

    Time-based invalidation removes cached data after a fixed time, ensuring data freshness automatically.
  2. Step 2: Compare with other strategies

    Manual invalidation requires user action, event-based depends on data changes, and versioning uses data versions.
  3. Final Answer:

    Time-based invalidation -> Option C
  4. Quick Check:

    Automatic removal after time = Time-based invalidation [OK]
Hint: Time-based means cache expires after set time [OK]
Common Mistakes:
  • Confusing manual with automatic removal
  • Thinking event-based triggers on time
  • Mixing versioning with time expiry
2. Which of the following is the correct way to manually invalidate a cache entry in a REST API?
easy
A. Send a PUT request to update cached data
B. Send a GET request to the cache endpoint
C. Send a POST request to retrieve cached data
D. Send a DELETE request to the cache endpoint

Solution

  1. Step 1: Identify HTTP method for deletion

    DELETE requests are used to remove resources, including cache entries.
  2. Step 2: Understand other methods

    GET retrieves data, POST creates, and PUT updates; none remove cache.
  3. Final Answer:

    Send a DELETE request to the cache endpoint -> Option D
  4. Quick Check:

    DELETE removes cache entry manually [OK]
Hint: DELETE method removes resources like cache entries [OK]
Common Mistakes:
  • Using GET to remove cache
  • Confusing POST with deletion
  • Thinking PUT deletes cache
3. Consider this pseudo-code for event-based cache invalidation:
if (dataChangedEvent) {
  invalidateCache(key);
}
return getCachedData(key);
What will happen if dataChangedEvent is true?
medium
A. Cache is invalidated and fresh data is fetched next time
B. Cache remains unchanged and stale data is returned
C. Cache is updated without invalidation
D. An error occurs because cache cannot be invalidated

Solution

  1. Step 1: Analyze the condition

    If dataChangedEvent is true, invalidateCache(key) runs, removing cached data.
  2. Step 2: Understand cache behavior after invalidation

    After invalidation, next data fetch will get fresh data, not stale cache.
  3. Final Answer:

    Cache is invalidated and fresh data is fetched next time -> Option A
  4. Quick Check:

    Event triggers invalidation = fresh data next fetch [OK]
Hint: Event true means cache cleared for fresh data [OK]
Common Mistakes:
  • Assuming cache stays after invalidation
  • Thinking cache updates automatically
  • Believing invalidation causes errors
4. You have this code snippet for versioning cache invalidation:
cache = { 'v1': data1 }
function getData(version) {
  return cache[version];
}

// Later
cache['v2'] = newData;
What is the main bug if the client still requests v1 after update?
medium
A. Cache throws an error because version key is missing
B. Client gets stale data because old version is still cached
C. Cache automatically updates old version to new data
D. Client cannot access any cached data

Solution

  1. Step 1: Understand versioning cache behavior

    Old version 'v1' remains in cache, so requests for it get stale data.
  2. Step 2: Identify bug impact

    Client requesting 'v1' does not see 'v2' data, causing stale responses.
  3. Final Answer:

    Client gets stale data because old version is still cached -> Option B
  4. Quick Check:

    Old version key returns stale data [OK]
Hint: Old version keys keep stale data unless removed [OK]
Common Mistakes:
  • Assuming cache auto-updates old versions
  • Expecting errors on missing keys
  • Thinking client loses all cache access
5. You want to design a cache invalidation strategy for a REST API where data changes frequently but must stay fresh within 5 minutes. Which combined strategy is best?
hard
A. Use time-based invalidation with 5-minute expiry plus event-based invalidation on data changes
B. Use manual invalidation only, requiring user to clear cache
C. Use versioning only without time limits
D. Use time-based invalidation with 1-hour expiry only

Solution

  1. Step 1: Analyze freshness requirement

    Data must be fresh within 5 minutes, so time-based expiry should be 5 minutes or less.
  2. Step 2: Combine with event-based invalidation

    Event-based invalidation clears cache immediately on data changes, improving freshness.
  3. Step 3: Evaluate other options

    Manual invalidation is slow, versioning alone may keep stale data, and 1-hour expiry is too long.
  4. Final Answer:

    Use time-based invalidation with 5-minute expiry plus event-based invalidation on data changes -> Option A
  5. Quick Check:

    Combine time and event for fresh cache [OK]
Hint: Combine time and event for best freshness [OK]
Common Mistakes:
  • Relying only on manual invalidation
  • Using too long expiry times
  • Ignoring event triggers for changes
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