Peer-to-Peer Wallet and Auditable Payments Service

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Design and implement a two-part peer-to-peer digital wallet library in Python: first as an in-memory core (Payments), and second as a persistent, concurrency-safe, idempotent, and auditable SQLite service (PaymentsDB).

Shared Money & Validation Rules

  • parse_amount(text: str) -> int: Convert a positive ASCII decimal string with up to two fractional digits (such as "15", "15.5", or "15.50") into exact integer cents (1500, 1550, 1550). Single-digit fractions denote tenths of a dollar. Raise InvalidRequest for non-strings (including float or int), whitespace, sign prefixes, scientific notation, more than two fractional places, zero, or amounts exceeding "10000.00" (1,000,000 cents).
  • format_amount(cents: int) -> str: Format non-negative integer cents with two fractional digits (for example 1550 -> "15.50", 5 -> "0.05").
  • Identifiers & notes: Valid user_id values are strings of 1 to 32 ASCII characters from A-Z, a-z, 0-9, _, ., - (any other value or type raises InvalidRequest). Optional payment note values are strings of at most 280 characters.
  • All-or-nothing error contract: Every rejected operation must raise the appropriate PaymentError subclass (InvalidRequest, UnknownUser, UserExists, InsufficientFunds, or IdempotencyConflict) without modifying any balance, history list, or database table.

Part 1 — In-Memory Wallet (Payments)

Implement Payments for single-threaded callers:

  • create_user(user_id) -> None: Register a new account with "0.00" balance; raise UserExists if user_id already exists.
  • deposit(user_id, amount) -> int: Credit external funds to user_id and return the new sequential transaction ID (1, 2, 3, ...).
  • pay(sender, recipient, amount, note="") -> int: Move amount from sender to recipient atomically. Raise InvalidRequest when sender == recipient, UnknownUser when either user is unregistered, and InsufficientFunds when sender's balance is below amount. Return the new sequential transaction ID.
  • balance(user_id) -> str: Return user_id's current formatted balance.
  • history(user_id) -> List[dict]: Return all transactions involving user_id ordered newest first (descending transaction ID). Each entry has shape {"id": int, "type": "deposit" | "sent" | "received", "amount": str, "counterparty": Optional[str], "note": str}, where counterparty is None for deposits.

Part 2 — Concurrent, Idempotent, Auditable Service (PaymentsDB)

Implement PaymentsDB(path: str) backed by an SQLite file at path, keeping cached balances in accounts (user_id TEXT PRIMARY KEY, balance_cents INTEGER):

  • Expose the same create_user, balance, and history methods, plus optional idempotency_key: Optional[str] = None on deposit and pay.
  • Concurrency safety: Simultaneous pay calls from multiple threads debiting the same sender must never allow balance_cents to drop below 0.
  • Idempotency: Repeating an identical deposit or pay call with the same idempotency_key (scoped to the initiating user: user_id for deposits, sender for payments) must return the original transaction ID and apply the transfer only once. Reusing the same key for a different operation, recipient, amount, or note by that user must raise IdempotencyConflict. Rejected calls must roll back without recording the key.
  • audit() -> List[str]: Recompute every user's expected balance from the stored ledger entries and verify ledger consistency, returning [] when everything matches or one diagnostic string per discrepancy when tampered with.

Examples

Example 1

Input:

wallet = Payments()
wallet.create_user("maya")
wallet.create_user("leo")
tx1 = wallet.deposit("maya", "40.00")
tx2 = wallet.pay("maya", "leo", "15.50", note="coffee beans")
# Next call raises InsufficientFunds because leo only holds "15.50":
# wallet.pay("leo", "maya", "20.00")

Output:

(tx1, tx2) == (1, 2)
wallet.balance("maya") == "24.50"
wallet.balance("leo") == "15.50"
wallet.history("maya") == [
    {"id": 2, "type": "sent", "amount": "15.50", "counterparty": "leo", "note": "coffee beans"},
    {"id": 1, "type": "deposit", "amount": "40.00", "counterparty": None, "note": ""},
]
wallet.history("leo") == [
    {"id": 2, "type": "received", "amount": "15.50", "counterparty": "maya", "note": "coffee beans"},
]

Explanation: maya deposits $40.00 (4000 cents, ID 1) and transfers $15.50 (1550 cents, ID 2) to leo, leaving "24.50" and "15.50". When leo attempts to send "20.00", InsufficientFunds is raised before any state changes. history("maya") lists transaction 2 ahead of transaction 1 (newest first).

Example 2

Input:

db = PaymentsDB("/tmp/wallet.db")
db.create_user("maya")
db.create_user("leo")
d1 = db.deposit("maya", "60.00", idempotency_key="dep-101")
d2 = db.deposit("maya", "60.00", idempotency_key="dep-101")
p1 = db.pay("maya", "leo", "18.00", note="taxi", idempotency_key="pay-202")
p2 = db.pay("maya", "leo", "18.00", note="taxi", idempotency_key="pay-202")
# Calling db.pay("maya", "leo", "25.00", note="taxi", idempotency_key="pay-202") raises IdempotencyConflict

Output:

d1 == d2 == 1
p1 == p2 == 2
db.balance("maya") == "42.00"
db.balance("leo") == "18.00"
db.audit() == []

Explanation: Retrying "dep-101" and "pay-202" with identical parameters returns the original transaction IDs (1 and 2) without duplicating credits or debits. Reusing "pay-202" with a changed amount ("25.00") raises IdempotencyConflict. Finally, audit() confirms every accounts.balance_cents row matches the sum of its double-entry ledger rows.

Constraints

  • Monetary strings represent positive amounts between "0.01" (1 cent) and "10000.00" (1,000,000 cents) inclusive, with at most 2 digits after ..
  • user_id matches [A-Za-z0-9_.-]{1,32}; note is a str with 0 <= len(note) <= 280; idempotency_key is either None or a str.
  • PaymentsDB must use only Python's standard library (sqlite3) and support concurrent calls across 20+ threads targeting the same SQLite database file.

Step-by-step walkthrough

  1. Agree on scope and design the error contract

    An open-ended prompt for a peer-to-peer digital wallet tests whether you lock down requirements before writing code. Spend the first few minutes stating crisp, concrete assumptions so the interviewer can confirm or adjust them:

    • Deliverable: Part 1 is an in-memory Python library (Payments) with unit tests. Part 2 puts the same API on top of a relational database (PaymentsDB using SQLite, which ships with Python's standard library) and defines the HTTP endpoints on top.
    • Balances and limits: Balances never go negative. Every deposit or transfer must be positive and at most $10,000.00.
    • Accounts and privacy: Only registered users can send or receive funds; user IDs are 1 to 32 ASCII characters (A-Z, a-z, 0-9, _, ., -). Each user sees only their own private history, in a single currency (USD with two decimal places).

    Define the public signatures, exception hierarchy, and specification tests before writing implementation code—that keeps invariants crystal clear and prevents subtle money or concurrency bugs from slipping past happy-path checks.

    Every rejected call raises a specific subclass of PaymentError and leaves all balances and histories untouched:

    Method                                        Returns     Possible errors
    --------------------------------------------  ----------  ---------------------------------------------
    create_user(user_id)                          None        InvalidRequest, UserExists
    deposit(user_id, amount)                      txn_id      InvalidRequest, UnknownUser
    pay(sender, recipient, amount, note="")       txn_id      InvalidRequest, UnknownUser, InsufficientFunds
    balance(user_id)                              "24.50"     InvalidRequest, UnknownUser
    history(user_id)                              [dict, ...] InvalidRequest, UnknownUser
    
  2. Store money as integer cents, never floats

    Computers store float values in base 2, and fractions like 0.10 or 19.99 have repeating binary expansions—just like 1/3 is 0.3333... in base 10. As a result, 0.1 + 0.2 evaluates to 0.30000000000000004, and int(19.99 * 100) silently becomes 1998 instead of 1999, losing a cent!

    Instead, accept amounts as strings ("15.50") and immediately convert them into integer cents (1550):

    Input string   Whole dollars   Fraction padded to 2 digits   Total integer cents
    ------------   -------------   ---------------------------   -------------------
    "15"           15              "0"  -> "00" -> 0             15 * 100 + 0  = 1500
    "15.5"         15              "5"  -> "50" -> 50            15 * 100 + 50 = 1550
    "0.05"         0               "05" -> "05" -> 5             0  * 100 + 5  = 5
    

    Notice two subtle details in the parser below: 1. "15.5" means fifteen dollars and fifty cents (tenths of a dollar), so fraction_digits.ljust(2, "0") pads on the right to "50". 2. [0-9]{1,9} restricts digits to ASCII 0-9 (unlike \d, which accepts Unicode digits) and caps length at 9 digits so int() can never hit Python's 4,300-digit ValueError limit on huge strings.

    from typing import Dict, List, Optional, Tuple
    import re
    
    MAX_AMOUNT_CENTS = 10_000_00
    MAX_NOTE_LENGTH = 280
    AMOUNT_RE = re.compile(r"([0-9]{1,9})(?:\.([0-9]{1,2}))?")
    USER_ID_RE = re.compile(r"[A-Za-z0-9_.-]{1,32}")
    
    
    def parse_amount(text: str) -> int:
        """'20', '20.5' or '20.50' -> cents (2000, 2050, 2050).
        Raise InvalidRequest unless text is a positive decimal string <= 10,000.00."""
        # Reject floats (like 0.1) and non-strings upfront so callers never lose precision.
        if not isinstance(text, str):
            raise InvalidRequest("amount must be a decimal string such as '20.00'")
    
        match = AMOUNT_RE.fullmatch(text)
        if match is None:
            raise InvalidRequest(f"bad amount {text!r}")
    
        whole_dollars = int(match.group(1))
        fraction_digits = match.group(2) or "0"
        # Pad on the right so a single decimal digit means tenths ("20.5" -> "50" cents, not 5).
        cents_part = int(fraction_digits.ljust(2, "0"))
        total_cents = whole_dollars * 100 + cents_part
    
        # Zero is matched by the regex ("0" or "0.00"), so enforce > 0 explicitly.
        if total_cents <= 0:
            raise InvalidRequest("amount must be positive")
        if total_cents > MAX_AMOUNT_CENTS:
            raise InvalidRequest("amount is above the limit")
        return total_cents
    
    
    def format_amount(cents: int) -> str:
        """2000 -> '20.00', 5 -> '0.05'. Balances and amounts are always non-negative."""
        whole_dollars = cents // 100
        remaining_cents = cents % 100
        return f"{whole_dollars}.{remaining_cents:02d}"
    
  3. Build Part 1 in memory: validate everything before changing anything

    A failed payment must never subtract from the sender without crediting the recipient or recording history. In single-threaded in-memory code, we get all-or-nothing behavior by splitting pay into two strict phases:

    1. Validation phase: Check user ID formats, amount format, note length, sender != recipient, that both users exist, and that self.balances[sender] >= cents. Any failure raises before a single dictionary or list is touched.
    2. Mutation phase: Subtract from sender, add to recipient, and append the transaction record. None of these simple dictionary/list operations can fail halfway.

    To support history(user_id) in newest-first order without relying on wall-clock timestamps (which can tie when two payments happen in the same millisecond), we assign each transaction a sequential ID 1, 2, 3, ... (len(self.transactions) + 1) and iterate each user's ID list in reverse.

    class Payments:
        """Users, balances, payments and history in memory, for one caller at a time."""
    
        def __init__(self) -> None:
            # balances: maps user_id -> integer balance in cents, e.g. {"maya": 2450}
            self.balances: Dict[str, int] = {}
            # transactions: append-only list of dicts; txn_id == list index + 1
            self.transactions: List[dict] = []
            # user_transactions: maps user_id -> chronological list of txn_ids, e.g. {"maya": [1, 2]}
            self.user_transactions: Dict[str, List[int]] = {}
    
        def pay(self, sender: str, recipient: str, amount: str, note: str = "") -> int:
            """Move money between two users all-or-nothing."""
            # Step 1: Validate all inputs and balances BEFORE changing any state.
            check_user_id(sender)
            check_user_id(recipient)
            cents = parse_amount(amount)
            check_note(note)
            if sender == recipient:
                raise InvalidRequest("cannot pay yourself")
            self._require_user(sender)
            self._require_user(recipient)
            if self.balances[sender] < cents:
                current_text = format_amount(self.balances[sender])
                raise InsufficientFunds(f"{sender} has {current_text}")
    
            # Step 2: Every check passed; these in-memory updates cannot fail halfway.
            self.balances[sender] -= cents
            self.balances[recipient] += cents
            return self._record("payment", sender, recipient, cents, note)
    
  4. Trace Example 1 step by step

    Let's trace all three internal data structures on Example 1 (maya and leo):

    Call                                             balances (cents)         transactions                 user_transactions
    -----------------------------------------------  -----------------------  ---------------------------  ------------------------
    create_user("maya"); create_user("leo")          {maya: 0, leo: 0}        []                           {maya: [], leo: []}
    deposit("maya", "40.00")                 -> 1    {maya: 4000, leo: 0}     [#1 deposit -> maya 4000]    {maya: [1], leo: []}
    pay("maya", "leo", "15.50", "coffee beans") -> 2 {maya: 2450, leo: 1550}  [#1 ..., #2 maya->leo 1550]  {maya: [1, 2], leo: [2]}
    pay("leo", "maya", "20.00")                      1550 < 2000 -> raises InsufficientFunds; state is completely unchanged!
    balance("maya") -> "24.50", balance("leo") -> "15.50"
    history("maya") walks reversed([1, 2]) -> [#2 sent 15.50 to leo ("coffee beans"), #1 deposit 40.00]
    
  5. See where concurrency and retries break Part 1

    When we expose our core over HTTP to multiple threads or multiple API servers in Part 2, two real-world failure modes break naive code:

    Failure 1 — Concurrent check-then-act race (Maya starts with $40.00):
      Request A (pay Leo $30):   reads Maya's balance = $40.00 >= $30.00 (passes check!)
      Request B (pay Nina $25):  reads Maya's balance = $40.00 >= $25.00 (also passes check!)
      Request A:                 subtracts $30.00 -> $10.00
      Request B:                 subtracts $25.00 -> -$15.00  (Maya spent $55 from a $40 balance!)
    
    Failure 2 — Client retry after a lost response:
      Client sends POST /v1/payments (pay Leo $18)  --->  Server commits $18 transfer
                                                    <--X  Network drops the 201 response!
      Client times out and resends the same POST    --->  Without an idempotency key, Leo gets $36!
    

    On the HTTP layer, the endpoints and security boundary look like this:

    POST /v1/users                        {"user_id": "maya"}                            -> 201 | 409
    POST /v1/deposits                     {"amount": "60.00"}  Idempotency-Key: <uuid>   -> 201 | 409 | 422
    POST /v1/payments                     {"to": "leo", "amount": "18.00", "note": ""}
                                          Idempotency-Key: <uuid>                        -> 201 | 404 | 409 | 422
    GET  /v1/me/balance                                                                  -> 200 {"balance": "42.00"}
    GET  /v1/me/transactions?before=<id>&limit=50                                        -> 200 newest first
    

    Notice that POST /v1/payments has no from field in the JSON body: the server always reads sender from the caller's authenticated session or token so one user can never spend another user's balance.

  6. Design an auditable double-entry database schema

    Storing only an accounts.balance_cents column makes fast reads easy, but if a bug ever corrupts a number, there is no way to prove what the balance should be. Financial systems solve this with a double-entry ledger: every transfer records two equal and opposite ledger rows (-cents on the source, +cents on the destination), with external deposits coming from a reserved @bank account.

    After Maya deposits $60.00 (transfer #1) and pays Leo $18.00 (transfer #2) in Example 2:
    
    accounts                        transfers                                          entries
    +---------+---------------+     +----+---------+-----------+--------+-----------+  +-------------+---------+-------------+
    | user_id | balance_cents |     | id | kind    | requester | sender | recipient |  | transfer_id | account | delta_cents |
    +---------+---------------+     +----+---------+-----------+--------+-----------+  +-------------+---------+-------------+
    | maya    |          4200 |     |  1 | deposit | maya      | NULL   | maya      |  |           1 | @bank   |       -6000 |
    | leo     |          1800 |     |  2 | payment | maya      | maya   | leo       |  |           1 | maya    |       +6000 |
    +---------+---------------+     +----+---------+-----------+--------+-----------+  |           2 | maya    |       -1800 |
                                                                                       |           2 | leo     |       +1800 |
                                                                                       +-------------+---------+-------------+
    

    Two accounting invariants must hold at every instant, and audit() checks both with SQL GROUP BY queries: 1. Account invariant: Every user's accounts.balance_cents equals SUM(entries.delta_cents) for that user (maya: +6000 - 1800 = 4200; leo: +1800). 2. Zero-sum transfer invariant: For every transfer_id, SUM(entries.delta_cents) == 0 (money is moved, never created out of thin air).

  7. Make payments atomic and idempotent inside one transaction

    To defeat both concurrency races and duplicate retries, PaymentsDB.pay wraps four steps inside one database transaction (BEGIN IMMEDIATE ... COMMIT):

    1. Check idempotency key: Query transfers for (requester, idempotency_key).
      • If found with the exact same request parameters, roll back the read transaction and return the original transfer_id without moving money again.
      • If found with different parameters (for example, same key "pay-202" reused for $25.00 instead of $18.00), raise IdempotencyConflict.
    2. Atomic check-and-debit in one SQL statement: sql UPDATE accounts SET balance_cents = balance_cents - ? WHERE user_id = ? AND balance_cents >= ? Because the balance_cents >= ? guard is inside the UPDATE itself (and BEGIN IMMEDIATE serializes writers in SQLite, while row locks serialize updates to the same row in PostgreSQL), no second request can sneak between checking the balance and subtracting from it. If rowcount != 1, we raise InsufficientFunds and ROLLBACK.
    3. Credit recipient and append ledger rows: Update the recipient's balance, insert the transfers row (protected by UNIQUE (requester, idempotency_key)), and insert the two entries rows.
    4. Commit or roll back: Only a COMMIT makes any of these writes visible—including the idempotency key! If a payment fails (for example InsufficientFunds), ROLLBACK leaves the idempotency key unused so the user can deposit funds and retry later.
        def pay(
            self,
            sender: str,
            recipient: str,
            amount: str,
            note: str = "",
            idempotency_key: Optional[str] = None,
        ) -> int:
            """Move money atomically. In an HTTP server, `sender` comes from auth, never the body."""
            check_user_id(sender)
            check_user_id(recipient)
            cents = parse_amount(amount)
            check_note(note)
            check_idempotency_key(idempotency_key)
            if sender == recipient:
                raise InvalidRequest("cannot pay yourself")
            request_tuple = ("payment", sender, recipient, cents, note)
    
            conn = self._connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                earlier_id = self._find_retry(conn, sender, idempotency_key, request_tuple)
                if earlier_id is not None:
                    conn.execute("ROLLBACK")
                    return earlier_id
    
                self._require_user(conn, sender)
                self._require_user(conn, recipient)
    
                debited_rows = conn.execute(
                    "UPDATE accounts SET balance_cents = balance_cents - ? "
                    "WHERE user_id = ? AND balance_cents >= ?",
                    (cents, sender, cents),
                ).rowcount
                if debited_rows != 1:
                    raise InsufficientFunds(sender)
    
                conn.execute(
                    "UPDATE accounts SET balance_cents = balance_cents + ? WHERE user_id = ?",
                    (cents, recipient),
                )
                transfer_id = self._insert_transfer(conn, sender, request_tuple, idempotency_key)
                self._insert_entries(conn, transfer_id, sender, recipient, cents)
                conn.execute("COMMIT")
                return transfer_id
            except BaseException:
                if conn.in_transaction:
                    conn.execute("ROLLBACK")
                raise
            finally:
                conn.close()
    
  8. Put it all together: the complete solution

    Here is the complete module combining shared money/input validation, the in-memory Payments class (Part 1), and the concurrent, idempotent, auditable PaymentsDB service (Part 2):

    from typing import Dict, List, Optional, Tuple
    import re
    import sqlite3
    
    # Maximum allowed amount for a single deposit or payment: $10,000.00 (1,000,000 cents).
    MAX_AMOUNT_CENTS = 10_000_00
    MAX_NOTE_LENGTH = 280
    
    # Special ledger account representing money entering from an external bank/card.
    # Because "@" is forbidden in normal user IDs, no real user can collide with "@bank".
    EXTERNAL = "@bank"
    
    # Strict ASCII digits: 1 to 9 whole digits (avoids Python's 4300-digit int() limit)
    # followed by an optional decimal point and 1 or 2 fractional digits.
    AMOUNT_RE = re.compile(r"([0-9]{1,9})(?:\.([0-9]{1,2}))?")
    USER_ID_RE = re.compile(r"[A-Za-z0-9_.-]{1,32}")
    
    
    class PaymentError(Exception):
        """A rejected request. Nothing was changed."""
    
    
    class InvalidRequest(PaymentError):
        """Bad amount, bad user id, bad note, or a payment to yourself."""
    
    
    class UnknownUser(PaymentError):
        pass
    
    
    class UserExists(PaymentError):
        pass
    
    
    class InsufficientFunds(PaymentError):
        pass
    
    
    class IdempotencyConflict(PaymentError):
        """The idempotency key was already used for a different request."""
    
    
    # ---- Phase 1: Exact money conversion and input validation (shared by Parts 1 & 2) ----
    
    def parse_amount(text: str) -> int:
        """'20', '20.5' or '20.50' -> cents (2000, 2050, 2050).
        Raise InvalidRequest unless text is a positive decimal string <= 10,000.00."""
        # Reject floats (like 0.1) and non-strings upfront so callers never lose precision.
        if not isinstance(text, str):
            raise InvalidRequest("amount must be a decimal string such as '20.00'")
    
        match = AMOUNT_RE.fullmatch(text)
        if match is None:
            raise InvalidRequest(f"bad amount {text!r}")
    
        whole_dollars = int(match.group(1))
        fraction_digits = match.group(2) or "0"
        # Pad on the right so a single decimal digit means tenths ("20.5" -> "50" cents, not 5).
        cents_part = int(fraction_digits.ljust(2, "0"))
        total_cents = whole_dollars * 100 + cents_part
    
        # Zero is matched by the regex ("0" or "0.00"), so enforce > 0 explicitly.
        if total_cents <= 0:
            raise InvalidRequest("amount must be positive")
        if total_cents > MAX_AMOUNT_CENTS:
            raise InvalidRequest("amount is above the limit")
        return total_cents
    
    
    def format_amount(cents: int) -> str:
        """2000 -> '20.00', 5 -> '0.05'. Balances and amounts are always non-negative."""
        whole_dollars = cents // 100
        remaining_cents = cents % 100
        return f"{whole_dollars}.{remaining_cents:02d}"
    
    
    def check_user_id(user_id: str) -> None:
        """Validate that user_id is a 1-32 char ASCII identifier before any dict/DB lookup."""
        if not isinstance(user_id, str) or USER_ID_RE.fullmatch(user_id) is None:
            raise InvalidRequest(f"bad user id {user_id!r}")
    
    
    def check_note(note: str) -> None:
        """Validate optional payment note type and 280-character cap."""
        if not isinstance(note, str) or len(note) > MAX_NOTE_LENGTH:
            raise InvalidRequest("note must be a string of at most 280 characters")
    
    
    def check_idempotency_key(key: Optional[str]) -> None:
        """Allow None (no retry protection) or a string key; reject other types cleanly."""
        if key is not None and not isinstance(key, str):
            raise InvalidRequest("idempotency_key must be a string or None")
    
    
    def build_history_entry(
        user_id: str,
        txn_id: int,
        kind: str,
        sender: Optional[str],
        recipient: str,
        cents: int,
        note: str,
    ) -> dict:
        """Format one stored transaction from the perspective of `user_id`."""
        if kind == "deposit":
            direction = "deposit"
            counterparty = None
        elif sender == user_id:
            direction = "sent"
            counterparty = recipient
        else:
            direction = "received"
            counterparty = sender
    
        return {
            "id": txn_id,
            "type": direction,
            "amount": format_amount(cents),
            "counterparty": counterparty,
            "note": note,
        }
    
    
    # ---- Phase 2: Part 1 — In-memory core for single-threaded callers ----
    
    class Payments:
        """Users, balances, payments and history in memory, for one caller at a time."""
    
        def __init__(self) -> None:
            # balances: maps user_id -> integer balance in cents, e.g. {"maya": 2450}
            self.balances: Dict[str, int] = {}
            # transactions: append-only list of dicts; txn_id == list index + 1
            # shape: {"id": 2, "kind": "payment", "sender": "maya", "recipient": "leo",
            #         "amount_cents": 1550, "note": "coffee beans"}
            self.transactions: List[dict] = []
            # user_transactions: maps user_id -> chronological list of txn_ids, e.g. {"maya": [1, 2]}
            self.user_transactions: Dict[str, List[int]] = {}
    
        def create_user(self, user_id: str) -> None:
            check_user_id(user_id)
            if user_id in self.balances:
                raise UserExists(user_id)
            self.balances[user_id] = 0
            self.user_transactions[user_id] = []
    
        def deposit(self, user_id: str, amount: str) -> int:
            """Add funds from outside. Validate everything before mutating state."""
            check_user_id(user_id)
            cents = parse_amount(amount)
            self._require_user(user_id)
    
            self.balances[user_id] += cents
            return self._record("deposit", None, user_id, cents, "")
    
        def pay(self, sender: str, recipient: str, amount: str, note: str = "") -> int:
            """Move money between two users all-or-nothing."""
            # Step 1: Validate all inputs and balances BEFORE changing any state.
            check_user_id(sender)
            check_user_id(recipient)
            cents = parse_amount(amount)
            check_note(note)
            if sender == recipient:
                raise InvalidRequest("cannot pay yourself")
            self._require_user(sender)
            self._require_user(recipient)
            # Strict `<` allows spending the exact full balance (`balance == cents`),
            # while rejecting any payment that is even 1 cent above the balance.
            if self.balances[sender] < cents:
                current_text = format_amount(self.balances[sender])
                raise InsufficientFunds(f"{sender} has {current_text}")
    
            # Step 2: Every check passed; these in-memory updates cannot fail halfway.
            self.balances[sender] -= cents
            self.balances[recipient] += cents
            return self._record("payment", sender, recipient, cents, note)
    
        def balance(self, user_id: str) -> str:
            check_user_id(user_id)
            self._require_user(user_id)
            return format_amount(self.balances[user_id])
    
        def history(self, user_id: str) -> List[dict]:
            """Return the user's transactions newest first using monotonic transaction IDs."""
            check_user_id(user_id)
            self._require_user(user_id)
            entries = []
            # Walk transaction IDs in reverse so newer transactions always appear first,
            # even when multiple transactions occur within the same clock millisecond.
            for txn_id in reversed(self.user_transactions[user_id]):
                txn = self.transactions[txn_id - 1]
                entries.append(
                    build_history_entry(
                        user_id,
                        txn["id"],
                        txn["kind"],
                        txn["sender"],
                        txn["recipient"],
                        txn["amount_cents"],
                        txn["note"],
                    )
                )
            return entries
    
        def _require_user(self, user_id: str) -> None:
            if user_id not in self.balances:
                raise UnknownUser(user_id)
    
        def _record(
            self,
            kind: str,
            sender: Optional[str],
            recipient: str,
            cents: int,
            note: str,
        ) -> int:
            txn_id = len(self.transactions) + 1
            self.transactions.append(
                {
                    "id": txn_id,
                    "kind": kind,
                    "sender": sender,
                    "recipient": recipient,
                    "amount_cents": cents,
                    "note": note,
                }
            )
            if sender is not None:
                self.user_transactions[sender].append(txn_id)
            self.user_transactions[recipient].append(txn_id)
            return txn_id
    
    
    # ---- Phase 3: Part 2 — SQLite service safe under concurrency and client retries ----
    
    SCHEMA = """
    CREATE TABLE IF NOT EXISTS accounts (
        user_id       TEXT PRIMARY KEY,
        balance_cents INTEGER NOT NULL CHECK (balance_cents >= 0)
    );
    CREATE TABLE IF NOT EXISTS transfers (
        id              INTEGER PRIMARY KEY,
        kind            TEXT NOT NULL,              -- 'deposit' or 'payment'
        requester       TEXT NOT NULL,              -- authenticated user who initiated the call
        sender          TEXT,                       -- NULL for a deposit
        recipient       TEXT NOT NULL,
        amount_cents    INTEGER NOT NULL CHECK (amount_cents > 0),
        note            TEXT NOT NULL,
        idempotency_key TEXT,
        UNIQUE (requester, idempotency_key)
    );
    CREATE TABLE IF NOT EXISTS entries (
        transfer_id INTEGER NOT NULL REFERENCES transfers (id),
        account     TEXT NOT NULL,                  -- user_id or '@bank'
        delta_cents INTEGER NOT NULL                -- negative for debit, positive for credit
    );
    CREATE INDEX IF NOT EXISTS entries_by_account ON entries (account, transfer_id);
    """
    
    
    class PaymentsDB:
        """Thread-safe and process-safe SQLite implementation with idempotency and auditing."""
    
        def __init__(self, path: str) -> None:
            self.path = path
            conn = self._connect()
            try:
                conn.executescript(SCHEMA)
            finally:
                conn.close()
    
        def _connect(self) -> sqlite3.Connection:
            # Open one connection per call so threads never share connection state.
            # isolation_level=None disables Python's implicit transactions so we control
            # BEGIN IMMEDIATE / COMMIT / ROLLBACK explicitly.
            conn = sqlite3.connect(self.path, timeout=10, isolation_level=None)
            conn.execute("PRAGMA foreign_keys = ON")
            return conn
    
        def create_user(self, user_id: str) -> None:
            check_user_id(user_id)
            conn = self._connect()
            try:
                conn.execute(
                    "INSERT INTO accounts (user_id, balance_cents) VALUES (?, 0)",
                    (user_id,),
                )
            except sqlite3.IntegrityError:
                raise UserExists(user_id) from None
            finally:
                conn.close()
    
        def deposit(
            self,
            user_id: str,
            amount: str,
            idempotency_key: Optional[str] = None,
        ) -> int:
            check_user_id(user_id)
            cents = parse_amount(amount)
            check_idempotency_key(idempotency_key)
            request_tuple = ("deposit", None, user_id, cents, "")
    
            conn = self._connect()
            try:
                # BEGIN IMMEDIATE grabs SQLite's write lock upfront so concurrent writers
                # queue cleanly instead of racing between SELECT and UPDATE.
                conn.execute("BEGIN IMMEDIATE")
                earlier_id = self._find_retry(conn, user_id, idempotency_key, request_tuple)
                if earlier_id is not None:
                    conn.execute("ROLLBACK")
                    return earlier_id
    
                credited_rows = conn.execute(
                    "UPDATE accounts SET balance_cents = balance_cents + ? WHERE user_id = ?",
                    (cents, user_id),
                ).rowcount
                if credited_rows != 1:
                    raise UnknownUser(user_id)
    
                transfer_id = self._insert_transfer(conn, user_id, request_tuple, idempotency_key)
                self._insert_entries(conn, transfer_id, EXTERNAL, user_id, cents)
                conn.execute("COMMIT")
                return transfer_id
            except BaseException:
                if conn.in_transaction:
                    conn.execute("ROLLBACK")
                raise
            finally:
                conn.close()
    
        def pay(
            self,
            sender: str,
            recipient: str,
            amount: str,
            note: str = "",
            idempotency_key: Optional[str] = None,
        ) -> int:
            """Move money atomically. In an HTTP server, `sender` comes from auth, never the body."""
            check_user_id(sender)
            check_user_id(recipient)
            cents = parse_amount(amount)
            check_note(note)
            check_idempotency_key(idempotency_key)
            if sender == recipient:
                raise InvalidRequest("cannot pay yourself")
            request_tuple = ("payment", sender, recipient, cents, note)
    
            conn = self._connect()
            try:
                conn.execute("BEGIN IMMEDIATE")
                # Check idempotency inside the same transaction as the balance movement.
                earlier_id = self._find_retry(conn, sender, idempotency_key, request_tuple)
                if earlier_id is not None:
                    conn.execute("ROLLBACK")
                    return earlier_id
    
                self._require_user(conn, sender)
                self._require_user(conn, recipient)
    
                # Atomic check-and-debit in a single SQL UPDATE: `balance_cents >= ?` ensures
                # no concurrent request can slip between checking the balance and subtracting.
                debited_rows = conn.execute(
                    "UPDATE accounts SET balance_cents = balance_cents - ? "
                    "WHERE user_id = ? AND balance_cents >= ?",
                    (cents, sender, cents),
                ).rowcount
                if debited_rows != 1:
                    raise InsufficientFunds(sender)
    
                conn.execute(
                    "UPDATE accounts SET balance_cents = balance_cents + ? WHERE user_id = ?",
                    (cents, recipient),
                )
                transfer_id = self._insert_transfer(conn, sender, request_tuple, idempotency_key)
                self._insert_entries(conn, transfer_id, sender, recipient, cents)
                conn.execute("COMMIT")
                return transfer_id
            except BaseException:
                if conn.in_transaction:
                    conn.execute("ROLLBACK")
                raise
            finally:
                conn.close()
    
        def balance(self, user_id: str) -> str:
            check_user_id(user_id)
            conn = self._connect()
            try:
                row = conn.execute(
                    "SELECT balance_cents FROM accounts WHERE user_id = ?",
                    (user_id,),
                ).fetchone()
            finally:
                conn.close()
            if row is None:
                raise UnknownUser(user_id)
            return format_amount(row[0])
    
        def history(self, user_id: str) -> List[dict]:
            check_user_id(user_id)
            conn = self._connect()
            try:
                self._require_user(conn, user_id)
                # Uses the (account, transfer_id) index to fetch this user's transfers newest first.
                rows = conn.execute(
                    "SELECT t.id, t.kind, t.sender, t.recipient, t.amount_cents, t.note "
                    "FROM entries e JOIN transfers t ON t.id = e.transfer_id "
                    "WHERE e.account = ? ORDER BY e.transfer_id DESC",
                    (user_id,),
                ).fetchall()
            finally:
                conn.close()
    
            entries = []
            for txn_id, kind, sender, recipient, cents, note in rows:
                entries.append(
                    build_history_entry(user_id, txn_id, kind, sender, recipient, cents, note)
                )
            return entries
    
        def audit(self) -> List[str]:
            """Verify cached account balances and zero-sum double-entry transfers."""
            conn = self._connect()
            try:
                # LEFT JOIN keeps users with zero transactions so COALESCE(SUM(...), 0) gives 0.
                account_sums = conn.execute(
                    "SELECT a.user_id, a.balance_cents, COALESCE(SUM(e.delta_cents), 0) "
                    "FROM accounts a LEFT JOIN entries e ON e.account = a.user_id "
                    "GROUP BY a.user_id"
                ).fetchall()
                unbalanced_transfers = conn.execute(
                    "SELECT transfer_id, SUM(delta_cents) FROM entries "
                    "GROUP BY transfer_id HAVING SUM(delta_cents) != 0"
                ).fetchall()
            finally:
                conn.close()
    
            problems = []
            for user_id, stored_cents, ledger_cents in account_sums:
                if stored_cents != ledger_cents:
                    problems.append(
                        f"{user_id}: balance {stored_cents} but ledger sums to {ledger_cents}"
                    )
            for transfer_id, total_delta in unbalanced_transfers:
                problems.append(f"transfer {transfer_id}: entries sum to {total_delta}, not 0")
            return problems
    
        # ---- Internal database helpers (run inside the caller's open transaction) ----
    
        def _require_user(self, conn: sqlite3.Connection, user_id: str) -> None:
            row = conn.execute(
                "SELECT 1 FROM accounts WHERE user_id = ?",
                (user_id,),
            ).fetchone()
            if row is None:
                raise UnknownUser(user_id)
    
        def _find_retry(
            self,
            conn: sqlite3.Connection,
            requester: str,
            key: Optional[str],
            request_tuple: Tuple,
        ) -> Optional[int]:
            """Return original transfer_id on exact retry, None if key is new, or raise conflict."""
            if key is None:
                return None
            row = conn.execute(
                "SELECT id, kind, sender, recipient, amount_cents, note FROM transfers "
                "WHERE requester = ? AND idempotency_key = ?",
                (requester, key),
            ).fetchone()
            if row is None:
                return None
            stored_request = tuple(row[1:])
            if stored_request != request_tuple:
                raise IdempotencyConflict(f"key {key!r} was used for a different request")
            return row[0]
    
        def _insert_transfer(
            self,
            conn: sqlite3.Connection,
            requester: str,
            request_tuple: Tuple,
            key: Optional[str],
        ) -> int:
            kind, sender, recipient, cents, note = request_tuple
            cursor = conn.execute(
                "INSERT INTO transfers "
                "(kind, requester, sender, recipient, amount_cents, note, idempotency_key) "
                "VALUES (?, ?, ?, ?, ?, ?, ?)",
                (kind, requester, sender, recipient, cents, note, key),
            )
            return cursor.lastrowid
    
        def _insert_entries(
            self,
            conn: sqlite3.Connection,
            transfer_id: int,
            source_account: str,
            target_account: str,
            cents: int,
        ) -> None:
            # Double-entry bookkeeping: every movement writes one negative debit and one
            # equal positive credit so the sum of delta_cents across every transfer is 0.
            conn.execute(
                "INSERT INTO entries (transfer_id, account, delta_cents) VALUES (?, ?, ?)",
                (transfer_id, source_account, -cents),
            )
            conn.execute(
                "INSERT INTO entries (transfer_id, account, delta_cents) VALUES (?, ?, ?)",
                (transfer_id, target_account, cents),
            )
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a peer-to-peer wallet service like a bank teller window backed by an ink-only paper ledger book. First, the teller counts everything in whole pennies rather than fractions so arithmetic is always exact. Second, only one change happens to an account at a moment, and every transfer writes two matching ink lines (-cents from one side, +cents to the other) inside a single database transaction—a group of reads and writes that either all succeed together or all undo completely (ROLLBACK) as if nothing happened. Third, each client request carries an idempotency key—a unique request ticket ID generated by the client—so if a phone loses signal and sends the same payment slip twice, the teller looks up the ticket and returns the original receipt instead of moving money a second time.

A naive implementation breaks in four ways. Storing money in binary floating point (numbers stored in base-2 fractions like Python's float) makes 0.10 + 0.20 equal 0.30000000000000004 and turns int(19.99 * 100) into 1998 cents. Checking if balance >= amount in Python and subtracting in a separate database write creates a race condition—a timing bug where two simultaneous requests both see $40.00 before either subtracts, letting a user spend $55.00 from a $40.00 balance. Without idempotency keys, retrying after a network timeout charges the sender twice; and storing only a mutable balance column without a double-entry ledger—an append-only log where every transfer records equal negative and positive entries summing to zero—leaves no way to audit or detect corrupted balances.

Walk through our sample sequence (maya and leo) to see all pieces working together: 1. deposit("maya", "60.00", idempotency_key="dep-101") parses "60.00" into 6000 cents, adds 6000 to Maya's accounts row, records transfer #1, and appends two ledger entries: (@bank, -6000) and (maya, +6000). 2. pay("maya", "leo", "18.00", note="taxi", idempotency_key="pay-202") runs one conditional SQL statement (UPDATE accounts SET balance_cents = balance_cents - 1800 WHERE user_id = 'maya' AND balance_cents >= 1800), sees rowcount == 1, credits Leo +1800, records transfer #2, and writes entries (maya, -1800) and (leo, +1800). 3. Maya's phone times out and repeats pay("maya", "leo", "18.00", note="taxi", idempotency_key="pay-202"): _find_retry finds transfer #2 under ("maya", "pay-202"), verifies the parameters match, rolls back, and returns 2 with balances still at 4200 ("42.00") and 1800 ("18.00"). 4. pay("leo", "maya", "25.00") runs the conditional UPDATE requiring balance_cents >= 2500; because Leo only holds 1800, rowcount is 0, raising InsufficientFunds and rolling back completely.

Complexity

  • Part 1 (Payments, in memory):
    • create_user, deposit, pay, and balance each run in O(1) average time because they perform a constant number of string checks, Python dictionary (dict) hash lookups, and list append calls.
    • history(user_id) runs in O(h) time, where h is the number of transactions involving that specific user, because we walk self.user_transactions[user_id] in reverse and look up each transaction in self.transactions by index in O(1) time without scanning unrelated users' payments.
    • Space is O(U + T) for U users and T total transactions, because each transaction dictionary is stored once and its integer ID appears in at most two per-user lists.
  • Part 2 (PaymentsDB, SQLite):
    • create_user, deposit, pay, and balance execute a constant number of indexed SQL queries; each lookup or insert on a B-tree index (a balanced tree structure databases use to keep keys sorted on disk) takes O(log(U + T)) time. Because SQLite uses a single database-wide write lock (BEGIN IMMEDIATE), concurrent writes execute one after another rather than in parallel; moving to PostgreSQL with row-level locks lets unrelated pairs of users pay in parallel.
    • history(user_id) runs in O(log E + h) time for E total ledger entries and h entries belonging to user_id, because the composite index (account, transfer_id) jumps straight to that user's rows in descending ID order.
    • audit() runs in O(U + E) time because it scans all U account rows and all E ledger entries to verify sums; in production it runs as a scheduled background check rather than on user requests.

Edge cases

  • Exact overdraft boundary: Paying every last cent of a balance ("25.00" from "25.00") succeeds and leaves "0.00"; "25.01" or a follow-up "0.01" raises InsufficientFunds.
  • Single-digit decimals and malformed amounts: "15.5" means $15.50 (1550 cents, padded on the right), whereas "0", "0.00", "-5", "1.005", "1e3", " 5", "10000.01", floats like 0.1, None, and strings of 5,000 digits all raise InvalidRequest before touching any state.
  • User ID and note boundaries: Paying yourself (sender == recipient), malformed or non-string user IDs ("", "has space", "@bank", None), and notes over 280 characters raise InvalidRequest; well-formed unknown IDs ("omar") raise UnknownUser.
  • Same-millisecond ordering: Ordering history by a monotonic integer ID (a counter 1, 2, 3, ... that only ever moves upward) prevents ties when several transactions happen within one clock tick.
  • Idempotency scoping and failures: Keys are scoped per requester (UNIQUE (requester, idempotency_key)), so Maya and Leo can both use "pay-202" independently. Reusing the same key for a different amount or recipient raises IdempotencyConflict, while a rejected request rolls back without saving its key so a later retry after depositing funds can succeed.
  • SQLite file vs :memory:: PaymentsDB opens a fresh connection per call for thread safety, so path must point to a file on disk (in SQLite, every plain sqlite3.connect(":memory:") creates an isolated, empty database).

Common mistakes

  • Using float for money: Writing int(float(amount) * 100) turns "19.99" into 1998 cents and causes totals to drift by pennies. Always convert decimal strings directly into integer cents (or decimal.Decimal) and reject float inputs at the boundary.
  • Check-then-act in application code: Running SELECT balance_cents, checking if balance >= cents in Python, and then running UPDATE accounts SET balance_cents = ... allows two concurrent threads to pass the check simultaneously and overdraw the account. Put AND balance_cents >= ? directly inside the UPDATE statement inside the transaction.
  • Recording idempotency outside the database transaction: Saving "key seen" in Redis or memory before or after the SQL COMMIT opens a crash window where a server restart either loses the payment permanently or applies it twice.
  • Trusting a "sender" field in the HTTP request body: If the API accepts {"from": "maya", "to": "leo"} from the client, anyone can drain Maya's wallet; the sender identity must always come from the authenticated session or token.
  • Storing only balances with no ledger: Without append-only transfers and entries tables written in the same transaction, you cannot explain how a balance reached its current value or catch silent data corruption with audit().
  • Deadlocking per-row locks in opposite directions: In databases with row-level locks, if maya -> leo locks Maya then Leo while leo -> maya locks Leo then Maya at the same instant, each transaction waits forever on the other (deadlock). Always lock accounts in a fixed canonical order (such as sorted([sender, recipient])).

Follow-up questions

  • How would you extend the data model to support bill-split or charge requests that a recipient can approve or reject? Add a payment_requests table storing id, requester, payer, amount_cents, note, and status ('pending', 'accepted', 'declined', 'cancelled'). When the payer clicks Approve, run one database transaction that first executes UPDATE payment_requests SET status = 'accepted' WHERE id = ? AND payer = ? AND status = 'pending' and checks rowcount == 1. Inside that exact same transaction, perform the atomic check-and-debit payment using f"req-{request_id}" as the idempotency key—so double-tapping Approve on two devices can never pay twice, and declined or cancelled requests cannot be settled.
  • How would you design a social activity stream showing peer transfers while enforcing public, contacts-only, and private visibility settings? Add a visibility column ('public', 'contacts', 'private') on transfers, defaulting to the user's privacy preference and allowing either participant to restrict it further (for example from 'public' down to 'private'). A viewer may see a transfer only if they are a participant, if visibility == 'public', or if visibility == 'contacts' and the viewer currently has an active contact edge with the sender or recipient. Even if you precompute feeds for fast reads, re-check contact edges and visibility at read time so removing a contact or marking an older transfer private takes effect immediately.
  • If a sender accidentally pays the wrong account, how can you reverse the transfer while keeping the ledger strictly append-only? Never UPDATE or DELETE existing transfers or entries rows, because an audit log must remain immutable. Instead, insert a new compensating transfer of kind = 'reversal' with a reverses_transfer_id column (UNIQUE so the same transfer can never be reversed twice) that debits the original recipient and credits the original sender through the same atomic balance_cents >= ? path. If the recipient has already withdrawn or spent the funds, the conditional UPDATE cleanly fails with InsufficientFunds, letting support workflows (such as requesting repayment or opening a dispute balance) handle the shortfall explicitly without rewriting history.
  • Pick one critical method in your implementation and explain how you verified its invariants beyond happy-path tests. Take PaymentsDB.pay: first inspect it line by line against every safety invariant—inputs validated before opening a connection, BEGIN IMMEDIATE acquiring the write transaction, _find_retry checked before any mutation, WHERE user_id = ? AND balance_cents >= ? enforcing rowcount == 1, transfer plus two zero-sum ledger entries inserted before COMMIT, and ROLLBACK guaranteed in except BaseException. Second, exercise it with adversarial specification tests: exact 1-cent overdraft boundaries, randomized operations cross-checked against an independent Decimal oracle, a 20-thread Barrier stress test attempting $10.00 transfers simultaneously from a $100.00 balance (asserting 10 successes and 10 rejections), and audit() verification after every run. Finally, apply mutation testing—temporarily removing AND balance_cents >= ?—to confirm the concurrency test fails immediately.

Follow-up questions

Similar questions

More Brex interview questions

All 9 Brex questions →