MediumStateful DesignPython 3

Idempotent Ledger

Apply account mutations exactly once while preserving retry-safe request semantics.

30m1 sample tests1 hidden tests

Idempotent Ledger

Implement a small account ledger that applies deposits and withdrawals exactly once per request ID.

Requirements

  • Define Ledger.
  • apply(request_id, account_id, amount) applies amount to the account and returns the resulting balance.
  • Positive amounts are deposits. Negative amounts are withdrawals.
  • A duplicate request_id returns the same result as the first successful application and must not apply twice.
  • Withdrawals that would make the balance negative raise ValueError.
  • balance(account_id) returns the current account balance, defaulting to zero.

Example

python
1ledger = Ledger() 2assert ledger.apply("d1", "acct", 100) == 100 3assert ledger.apply("d1", "acct", 100) == 100 4assert ledger.apply("w1", "acct", -30) == 70 5assert ledger.balance("acct") == 70

Constraints

  • Use standard-library Python only.
  • Keep all state in memory.

Editor
1
2
3
4
5
6
7
8
9
Sample Tests
deduplicates successful requests
from solution import Ledger

ledger = Ledger()
assert ledger.apply("deposit-1", "acct", 100) == 100
assert ledger.apply("deposit-1", "acct", 100) == 100
assert ledger.apply("withdraw-1", "acct", -30) == 70
assert ledger.balance("acct") == 70
Results
Run sample tests or submit all tests.