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 FundamentalsIdempotencypredict14 / 105
+100 XP
Task
📝 **Task:** Predict the four-line log. The server uses an idempotency-key cache; same key returns the cached result, new key processes a fresh charge. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

class ChargeService:
    def __init__(self):
        self.balance = 0           # running ledger
        self.seen = {}             # idempotency-key → cached response
        self.log = []

    def charge(self, key, amount):
        if key in self.seen:
            self.log.append(f"cached {self.seen[key]}")
            return self.seen[key]
        self.balance += amount
        receipt = f"OK {self.balance}"
        self.seen[key] = receipt
        self.log.append(f"processed {receipt}")
        return receipt

svc = ChargeService()
svc.charge("idem-A", 100)    # first attempt — processes
svc.charge("idem-A", 100)    # retry SAME key — should return cached
svc.charge("idem-A", 100)    # another retry — still cached
svc.charge("idem-B", 50)     # new key — fresh charge

print("\n".join(svc.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…