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?
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)Think about what happens when you update a cache entry and then remove another.
The cache updates the value for 'user_1' to 'John A. Doe'. Then it removes 'user_2' from the cache. So only 'user_1' remains with the updated value.
A REST API cache is set to expire entries automatically after 10 minutes. Which cache invalidation strategy does this represent?
Think about automatic expiration based on time.
TTL expiration means cache entries are invalidated automatically after a set time period.
Look at the code below that tries to invalidate a cache entry after updating the database. Why does the stale cache entry remain?
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)Look carefully at the 'if' block that is supposed to remove the cache entry.
The 'if' block only checks if 'item_1' is in cache but does not remove it. So the stale entry remains.
Identify the option that will cause a runtime error when trying to invalidate a cache entry in Python.
cache = {'key1': 'value1', 'key2': 'value2'}Check which method is not valid for Python dictionaries.
Dictionaries do not have a 'remove' method. Using cache.remove('key1') causes an AttributeError.
Given the following cache invalidation sequence, how many entries remain in the cache?
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))Count entries after filtering, adding, and removing.
After removing even values (b:2, d:4), cache has 'a':1, 'c':3 (2 entries). Then 'e':5 added (3 entries). Removing 'a' leaves 'c':3, 'e':5 (2 entries).