Syllabus Lesson 37 of 141 · Ask a different question
Ask a different question

Move the work: read-heavy balances

Why it matters Where work happens is a design choice. Most code does it at the moment someone asks, because that is how the question is phrased. When asking is far more common than changing, that is the most expensive place to put it.

A credits service moves credits between team accounts. The dashboard, the API and the billing checks all read balances, about fifty reads for every transfer. The service runs on a step budget.

The interface

led = Ledger()
led.record("acme", "bolt", 500)   # acme sends 500 cents to bolt
led.balance("bolt")               # -> 500
led.balance("acme")               # -> -500  (balances may go negative)
led.balance("nobody")             # -> 0
Your turn

Write a class Ledger with record(src, dst, cents) (move a whole number of cents from src to dst; a transfer to yourself changes nothing) and balance(account) (received minus sent, 0 for an unknown account). Every read must reflect every earlier transfer. Budget: a workload of 50,000 reads and 1,000 transfers, interleaved, must take at most 1,000,000 steps of your own code.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.