Design a credit-based purchase system with thread-safe wallet deductions

Quick Overview

Implement a credit wallet system where users buy credit plans, spend credits on services, and get sequential transaction IDs with a per-user history. It tests in-memory data modeling, exact return codes, and lock design that keeps balances from going negative under concurrent deductions.

Design a credit-based purchase system with thread-safe wallet deductions

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a **credit-based purchase system** where users buy credit plans to top up their wallets and then spend credits on services. The system manages wallets (a credit balance per user), transactions (records of all credit additions and deductions), and credit plans (predefined bundles of credits at a set price). When a user purchases a credit plan, the plan's credits are added to their wallet and a transaction is recorded. When a user buys a service, the service cost is deducted from their wallet if they have enough credits, and a transaction is recorded. The system must handle concurrent credit deductions safely using locking, so that a user's balance never goes negative. Each transaction is assigned a globally unique, sequentially increasing ID starting from 1. Transaction IDs are returned in the format `txn_<id>`. Implement a class `CreditPurchaseSystem` with these methods: - `addCreditPlan(planId: str, planName: str, credits: int, price: int) -> str` adds a credit plan with the given ID, name, credit amount and price. It returns `"plan_added"` on success or `"plan_exists"` if the plan ID already exists. - `createUser(userId: str) -> str` creates a new user with an empty wallet (0 credits). It returns `"user_created"` on success or `"user_exists"` if the user already exists. - `purchasePlan(userId: str, planId: str) -> str` adds the plan's credits to the user's wallet. It returns `"txn_<id>"` on success, `"user_not_found"` if the user does not exist, or `"plan_not_found"` if the plan does not exist. - `buyService(userId: str, serviceId: str, cost: int) -> str` spends credits on a service. It returns `"txn_<id>"` on success, `"user_not_found"` if the user does not exist, or `"insufficient_credits"` if the balance is less than the cost. - `getBalance(userId: str) -> int` returns the user's current credit balance, or -1 if the user does not exist. - `getTransactions(userId: str) -> List[str]` returns all of the user's transaction IDs in chronological order, or an empty list if the user does not exist. Example call sequence: ```text addCreditPlan("basic", "Basic", 100, 10) -> "plan_added" addCreditPlan("basic", "Basic v2", 50, 5) -> "plan_exists" createUser("alice") -> "user_created" createUser("alice") -> "user_exists" purchasePlan("alice", "basic") -> "txn_1" buyService("alice", "render", 30) -> "txn_2" buyService("alice", "render", 80) -> "insufficient_credits" getBalance("alice") -> 70 purchasePlan("bob", "basic") -> "user_not_found" createUser("bob") -> "user_created" purchasePlan("bob", "pro") -> "plan_not_found" purchasePlan("bob", "basic") -> "txn_3" buyService("bob", "export", 100) -> "txn_4" getBalance("bob") -> 0 getTransactions("alice") -> ["txn_1", "txn_2"] getTransactions("bob") -> ["txn_3", "txn_4"] getBalance("carol") -> -1 getTransactions("carol") -> [] ``` Alice ends at 70 because she bought 100 credits, spent 30, and the 80-credit purchase was rejected. Rejected calls record no transaction, so Bob's first purchase gets `txn_3`. Bob can spend exactly his balance of 100, which leaves him at 0. ```hint Find the race Picture two `buyService` calls for the same user arriving at the same moment. Work out which reads and writes have to happen as one indivisible step. ``` ```hint What is shared Balances of different users never interact, but the transaction ID counter is shared by everyone. Let that decide how many locks you need and what each one protects. ``` ### Constraints & Assumptions - `1 <= userId.length <= 20` - `1 <= planId.length <= 20` - `1 <= serviceId.length <= 20` - Credit amounts and service costs are positive integers. - At most 10,000 total operations. - `purchasePlan` checks the user before the plan, so a call where both are missing returns `"user_not_found"`. ### Clarifying Questions to Ask - Are the concurrent calls threads in one process, or several servers sharing one store? The answer decides between in-process locks and database-level guarantees. - Is `price` only stored with the plan, or does `purchasePlan` also have to charge a payment method? - Can users or plans be deleted, and can a plan's credit amount change after users have bought it? - Will callers later need the amount, type and resulting balance of each transaction, or only its ID? ### What a Strong Answer Covers - A data model for plans, wallets and per-user transaction records, with the exact return value for every success and error case. - An atomic check-and-deduct in `buyService` so the balance can never go negative under concurrent calls. - A global transaction ID sequence that only successful operations advance, with each user's history kept in ID order. - Lock scope: what each lock protects, why the lock order cannot deadlock, and how concurrent `createUser` and `addCreditPlan` calls stay safe. - Per-operation complexity and edge cases such as a cost equal to the balance and unknown users. ### Follow-up Questions - How would you keep `buyService` safe when wallets live in a SQL database and several application servers handle requests? - How would you make `purchasePlan` idempotent when a client retries after a timeout? - How would you add refunds or credit expiry while keeping the transaction log append-only? - How would you paginate `getTransactions` for a user with millions of entries?

Overview: Implement a credit wallet system where users buy credit plans, spend credits on services, and get sequential transaction IDs with a per-user history. It tests in-memory data modeling, exact return codes, and lock design that keeps balances from going negative under concurrent deductions.

General logo
General
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a credit-based purchase system where users buy credit plans to top up their wallets and then spend credits on services. The system manages wallets (a credit balance per user), transactions (records of all credit additions and deductions), and credit plans (predefined bundles of credits at a set price).

When a user purchases a credit plan, the plan's credits are added to their wallet and a transaction is recorded. When a user buys a service, the service cost is deducted from their wallet if they have enough credits, and a transaction is recorded. The system must handle concurrent credit deductions safely using locking, so that a user's balance never goes negative.

Each transaction is assigned a globally unique, sequentially increasing ID starting from 1. Transaction IDs are returned in the format txn_<id>.

Implement a class CreditPurchaseSystem with these methods:

  • addCreditPlan(planId: str, planName: str, credits: int, price: int) -> str adds a credit plan with the given ID, name, credit amount and price. It returns "plan_added" on success or "plan_exists" if the plan ID already exists.
  • createUser(userId: str) -> str creates a new user with an empty wallet (0 credits). It returns "user_created" on success or "user_exists" if the user already exists.
  • purchasePlan(userId: str, planId: str) -> str adds the plan's credits to the user's wallet. It returns "txn_<id>" on success, "user_not_found" if the user does not exist, or "plan_not_found" if the plan does not exist.
  • buyService(userId: str, serviceId: str, cost: int) -> str spends credits on a service. It returns "txn_<id>" on success, "user_not_found" if the user does not exist, or "insufficient_credits" if the balance is less than the cost.
  • getBalance(userId: str) -> int returns the user's current credit balance, or -1 if the user does not exist.
  • getTransactions(userId: str) -> List[str] returns all of the user's transaction IDs in chronological order, or an empty list if the user does not exist.

Example call sequence:

addCreditPlan("basic", "Basic", 100, 10)    -> "plan_added"
addCreditPlan("basic", "Basic v2", 50, 5)   -> "plan_exists"
createUser("alice")                         -> "user_created"
createUser("alice")                         -> "user_exists"
purchasePlan("alice", "basic")              -> "txn_1"
buyService("alice", "render", 30)           -> "txn_2"
buyService("alice", "render", 80)           -> "insufficient_credits"
getBalance("alice")                         -> 70
purchasePlan("bob", "basic")                -> "user_not_found"
createUser("bob")                           -> "user_created"
purchasePlan("bob", "pro")                  -> "plan_not_found"
purchasePlan("bob", "basic")                -> "txn_3"
buyService("bob", "export", 100)            -> "txn_4"
getBalance("bob")                           -> 0
getTransactions("alice")                    -> ["txn_1", "txn_2"]
getTransactions("bob")                      -> ["txn_3", "txn_4"]
getBalance("carol")                         -> -1
getTransactions("carol")                    -> []

Alice ends at 70 because she bought 100 credits, spent 30, and the 80-credit purchase was rejected. Rejected calls record no transaction, so Bob's first purchase gets txn_3. Bob can spend exactly his balance of 100, which leaves him at 0.

Constraints & Assumptions

  • 1 <= userId.length <= 20
  • 1 <= planId.length <= 20
  • 1 <= serviceId.length <= 20
  • Credit amounts and service costs are positive integers.
  • At most 10,000 total operations.
  • purchasePlan checks the user before the plan, so a call where both are missing returns "user_not_found" .

Clarifying Questions to Ask Guidance

  • Are the concurrent calls threads in one process, or several servers sharing one store? The answer decides between in-process locks and database-level guarantees.
  • Is price only stored with the plan, or does purchasePlan also have to charge a payment method?
  • Can users or plans be deleted, and can a plan's credit amount change after users have bought it?
  • Will callers later need the amount, type and resulting balance of each transaction, or only its ID?

What a Strong Answer Covers Guidance

  • A data model for plans, wallets and per-user transaction records, with the exact return value for every success and error case.
  • An atomic check-and-deduct in buyService so the balance can never go negative under concurrent calls.
  • A global transaction ID sequence that only successful operations advance, with each user's history kept in ID order.
  • Lock scope: what each lock protects, why the lock order cannot deadlock, and how concurrent createUser and addCreditPlan calls stay safe.
  • Per-operation complexity and edge cases such as a cost equal to the balance and unknown users.

Follow-up Questions Guidance

  • How would you keep buyService safe when wallets live in a SQL database and several application servers handle requests?
  • How would you make purchasePlan idempotent when a client retries after a timeout?
  • How would you add refunds or credit expiry while keeping the transaction log append-only?
  • How would you paginate getTransactions for a user with millions of entries?