Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSystem Design for Python JuniorsModule 1 · System Design FundamentalsCaching: when, where, whatpredict5 / 105
+100 XP
Task
📝 **Task:** Predict the 7-line trace produced by four product-catalog reads against a cache-aside layer (each miss prints `miss` then `db`; a hit prints just `hit`). One invalidation in the middle resets the picture. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

class CacheAside:
    def __init__(self, db):
        self.cache = {}
        self.db = db
        self.log = []

    def read(self, key):
        if key in self.cache:
            self.log.append("hit")
            return self.cache[key]
        self.log.append("miss")
        # Fall back to DB.
        value = self.db[key]
        self.log.append("db")
        self.cache[key] = value
        return value

    def invalidate(self, key):
        self.cache.pop(key, None)

DB = {"product:1": "Widget", "product:2": "Gadget"}
c = CacheAside(DB)

c.read("product:1")    # first read — cold cache
c.read("product:1")    # second read — should hit
c.read("product:2")    # different key — cold
c.invalidate("product:1")
c.read("product:1")    # invalidated — back to db

print("\n".join(c.log))

# What does this print? Type your prediction.

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…