Design a Hospitality Platform Wallet with Authorizations and Payouts
System DesignModel answerLast updated
Design a robust multi-currency ledger and wallet architecture supporting holds, captures, host payouts, idempotent processing, and automated reconciliation.
Design an end-to-end wallet and ledger infrastructure for a two-sided marketplace (such as a lodging/rental platform).
System Scope and Requirements
-
Account Structure & Ledger Core:
- Implement an append-only, double-entry financial ledger.
- Maintain total vs. spendable balances across multiple fiat currencies.
- Never allow spendable balances to drop below zero.
-
Transaction Lifecycle:
- Holds / Authorizations: Reserve funds when a guest creates a booking request.
- Captures: Settle held funds upon guest check-in.
- Cancellations / Releases: Expire or release holds if a reservation is canceled.
- Refunds: Support partial and complete post-capture refunds to guests.
- Payouts & Split Clearing: Deduct platform service fees and taxes before executing host disbursements.
-
Multi-Currency & FX:
- Handle foreign currency conversions (e.g., guest pays in EUR, host receives USD).
- Define exact handling for exchange rate lock-ins, fixed-point integer arithmetic, and currency rounding rules.
-
Consistency & Reliability:
- Ensure idempotency for all mutating requests using unique client-provided keys.
- Maintain safety against high-concurrency race conditions (e.g., dual capture or double spend attempts).
- Design a background reconciliation engine to verify mathematical integrity across accounts and sub-ledgers.
-
Architecture Specifications:
- Detail data models (tables, schemas, relational constraints, and database isolation levels).
- Outline API interface definitions and state transitions for holds and captures.
Hints
Hint 1
Use double-entry bookkeeping rules: every movement of funds consists of balanced debit and credit entries across immutable entries. Never rely on mutating balance rows without an underlying ledger record.
Hint 2
Distinguish clearly between 'Total Balance', 'Pending Hold Amount', and 'Spendable Balance'. Spendable balance is calculated as (Total - Pending Holds).
Hint 3
Ensure idempotency at the database level by placing a UNIQUE constraint on (client_id, idempotency_key) paired with transaction-level locking (e.g., SELECT ... FOR UPDATE or serializable isolation).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level System Architecture
A multi-currency marketplace ledger requires strict guarantees: immutability, auditability, strict idempotency, and exact floating-point precision. The architecture separates the transactional core (Ledger & Wallet Engine) from external payment processors (Payment Gateways / Banking APIs) and asynchronous settlement pipelines.
+------------------+ +-----------------------+ +------------------------+
| | ---> | API Gateway | ---> | Idempotency Middleware |
| Marketplace Client| +-----------------------+ +------------------------+
| (Guest/Host App) | |
+------------------+ v
+------------------------+
| Wallet & Ledger Service|
+------------------------+
/ | \
v v v
+------------+ +--------+ +------------+
| Primary DB | | FX Svc | | Gateways |
| (Postgres) | +--------+ | (Stripe/ |
+------------+ | Banking) |
| +------------+
v
+------------+
| Rec Engine |
+------------+
2. Double-Entry Core & Data Model
Every financial event consists of at least one debit and one credit. Debits and credits must balance to zero (sum(debits) - sum(credits) = 0).
Core Ledger Schema (PostgreSQL)
-- Currency amounts are always stored as 64-bit integers in the smallest currency unit (e.g., cents).
CREATE TYPE account_type AS ENUM ('asset', 'liability', 'equity', 'revenue', 'expense');
CREATE TABLE accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
owner_id VARCHAR(64) NOT NULL,
account_type account_type NOT NULL,
currency VARCHAR(3) NOT NULL, -- ISO 4217 code (USD, EUR, JPY)
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE ledger_entries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
idempotency_key VARCHAR(128) UNIQUE NOT NULL,
reference_id VARCHAR(128) NOT NULL, -- e.g., booking_id or payout_id
description TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE journal_postings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
ledger_entry_id UUID NOT NULL REFERENCES ledger_entries(id),
account_id UUID NOT NULL REFERENCES accounts(id),
amount BIGINT NOT NULL, -- Positive for Credit, Negative for Debit (or vice-versa, as long as sum = 0)
currency VARCHAR(3) NOT NULL,
sequence_number BIGSERIAL NOT NULL
);
CREATE TABLE authorizations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
account_id UUID NOT NULL REFERENCES accounts(id),
booking_id VARCHAR(128) NOT NULL UNIQUE,
amount BIGINT NOT NULL,
currency VARCHAR(3) NOT NULL,
status VARCHAR(32) NOT NULL, -- 'PENDING', 'CAPTURED', 'RELEASED', 'EXPIRED'
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX idx_postings_entry_account ON journal_postings(ledger_entry_id, account_id);
CREATE INDEX idx_postings_account ON journal_postings(account_id);
Balance Interpretation
- Total Balance: Sum of all committed journal postings for the account.
- Spendable Balance:
Total Balance - Sum(Active Holds).
3. Lifecycle Protocols & State Transitions
A. Guest Booking Hold (Authorization)
When a guest requests a booking:
- Verify
Spendable Balance >= Hold Amount. - Insert a record into
authorizationswithstatus = 'PENDING'. - Do not create host revenue entries yet; funds are escrowed in a
Guest_Encumbered_Liabilitiesaccount.
Guest Asset Account ---> (Debit)
Guest Encumbered Escrow Liability ---> (Credit)
B. Check-In Settlement (Capture)
When check-in occurs:
- Transition authorization status from
PENDINGtoCAPTUREDinside a database transaction. - Execute multi-split entries for platform fees, local occupancy taxes, and host payout liabilities.
Example Split for $100 Booking (Guest pays $100 in USD; Platform Fee = $10, Tax = $5, Host Earns = $85):
| Account | Entry Type | Amount |
|---|---|---|
Escrow_Liabilities:Guest | Debit | $100.00 |
Platform_Revenue:Fees | Credit | $10.00 |
Platform_Payable:Taxes | Credit | $5.00 |
Host_Payable_Liabilities:Host_A | Credit | $85.00 |
C. Cancellation & Partial Refunds
- Pre-Check-In Cancellation: Transition
authorizationstatus toRELEASED. Release the hold on the guest's spendable balance. No settlement posting occurs. - Post-Check-In Partial Refund: Create a adjusting journal posting reversing funds from Platform Revenue / Host Payable back to Guest Account.
4. Multi-Currency & FX Rate Lock-In
- Fixed-Point Arithmetic: All amounts are represented as standard integer units (e.g., $100.00 USD =
10000). For micro-currencies or sub-cent precision (such as gas/tax calculations), internal representation uses base-10^6 fixed points. - Rate Lock Guarantee: When a guest initiates a hold in Currency A (e.g., EUR) for a host listing priced in Currency B (e.g., USD), the system fetches the spot rate from an FX provider and persists the rate with an expiration time (
fx_rate_quote_id). - Conversion Split Ledger: FX spreads or conversions are written explicitly to a dedicated
FX_Gain_Lossplatform account to ensure multi-currency balanced postings.
5. Idempotency & Concurrency Guarantees
High-Concurrency Hold/Capture Protection
To avoid double spending or concurrent duplicate captures:
- Idempotency Keys: Clients pass
X-Idempotency-Keyheaders. An idempotency middleware intercepts requests, recording the key in DB with aPENDINGstatus before logic execution. - Optimistic/Pessimistic Locking: Account balance modifications run inside
READ COMMITTEDorSERIALIZABLEtransactions using explicit row locking on the primary account:
BEGIN;
-- Lock account record to serialize operations on this account
SELECT id FROM accounts WHERE id = $1 FOR UPDATE;
-- Calculate current spendable balance
SELECT
COALESCE(SUM(jp.amount), 0) - COALESCE(auths.held_amount, 0) AS spendable_balance
FROM accounts a
LEFT JOIN journal_postings jp ON jp.account_id = a.id
LEFT JOIN (
SELECT account_id, SUM(amount) AS held_amount
FROM authorizations
WHERE status = 'PENDING' AND expires_at > NOW()
GROUP BY account_id
) auths ON auths.account_id = a.id
WHERE a.id = $1
GROUP BY a.id, auths.held_amount;
-- If spendable_balance >= requested_amount:
INSERT INTO authorizations (account_id, booking_id, amount, currency, status, expires_at)
VALUES ($1, $2, $3, $4, 'PENDING', $5);
COMMIT;
6. Automated Reconciliation Engine
An independent background worker continuously validates accounting integrity across system boundaries.
- Internal Imbalance Detection:
- Query:
SELECT ledger_entry_id, SUM(amount) FROM journal_postings GROUP BY ledger_entry_id HAVING SUM(amount) != 0; - Any returned rows indicate a critical systemic integrity violation.
- Query:
- External Gateway Reconciliation:
- Compare daily settlement batch files (e.g., Stripe/Bank CSV files) against local transaction tables.
- Match transactions via
reference_idand flag discrepancies into anunreconciled_discrepanciestable for human audit.
7. Core Class Implementations (Python Model)
from decimal import Decimal
from datetime import datetime, timezone
from enum import Enum
from typing import Dict, List, Optional
import uuid
class AccountType(Enum):
ASSET = "asset"
LIABILITY = "liability"
REVENUE = "revenue"
EXPENSE = "expense"
class Currency(Enum):
USD = "USD"
EUR = "EUR"
class Account:
def __init__(self, account_id: str, owner_id: str, account_type: AccountType, currency: Currency):
self.account_id = account_id
self.owner_id = owner_id
self.account_type = account_type
self.currency = currency
class AuthorizationStatus(Enum):
PENDING = "PENDING"
CAPTURED = "CAPTURED"
RELEASED = "RELEASED"
class Authorization:
def __init__(self, auth_id: str, account_id: str, booking_id: str, amount: int, currency: Currency):
self.auth_id = auth_id
self.account_id = account_id
self.booking_id = booking_id
self.amount = amount
self.currency = currency
self.status = AuthorizationStatus.PENDING
class Posting:
def __init__(self, account_id: str, amount: int, currency: Currency):
self.account_id = account_id
self.amount = amount # Positive = Credit, Negative = Debit
self.currency = currency
class WalletService:
def __init__(self):
self.accounts: Dict[str, Account] = {}
self.postings: List[Posting] = []
self.authorizations: Dict[str, Authorization] = {}
self.idempotency_store: Dict[str, dict] = {}
def get_total_balance(self, account_id: str) -> int:
return sum(p.amount for p in self.postings if p.account_id == account_id)
def get_spendable_balance(self, account_id: str) -> int:
total = self.get_total_balance(account_id)
held = sum(
a.amount for a in self.authorizations.values()
if a.account_id == account_id and a.status == AuthorizationStatus.PENDING
)
return total - held
def create_hold(self, idempotency_key: str, account_id: str, booking_id: str, amount: int) -> Authorization:
if idempotency_key in self.idempotency_store:
return self.idempotency_store[idempotency_key]
spendable = self.get_spendable_balance(account_id)
if spendable < amount:
raise ValueError("Insufficient spendable balance")
auth = Authorization(
auth_id=str(uuid.uuid4()),
account_id=account_id,
booking_id=booking_id,
amount=amount,
currency=self.accounts[account_id].currency
)
self.authorizations[auth.auth_id] = auth
self.idempotency_store[idempotency_key] = auth
return auth
def capture_hold(
self,
idempotency_key: str,
auth_id: str,
host_account_id: str,
platform_fee_account_id: str,
fee_amount: int
):
if idempotency_key in self.idempotency_store:
return self.idempotency_store[idempotency_key]
auth = self.authorizations.get(auth_id)
if not auth or auth.status != AuthorizationStatus.PENDING:
raise ValueError("Invalid or already processed authorization")
host_amount = auth.amount - fee_amount
if host_amount < 0:
raise ValueError("Fee exceeds hold amount")
# Atomic double-entry settlement
guest_account_id = auth.account_id
c_currency = auth.currency
# Create Postings: Guest pays auth.amount, Host gets host_amount, Platform gets fee_amount
self.postings.append(Posting(account_id=guest_account_id, amount=-auth.amount, currency=c_currency))
self.postings.append(Posting(account_id=host_account_id, amount=host_amount, currency=c_currency))
self.postings.append(Posting(account_id=platform_fee_account_id, amount=fee_amount, currency=c_currency))
auth.status = AuthorizationStatus.CAPTURED
self.idempotency_store[idempotency_key] = True
return True
8. Trade-Off Analysis & Performance Considerations
| Component / Choice | Trade-Off | Mitigations |
|---|---|---|
On-the-Fly Balance Aggregation (SUM(amount)) | Highly consistent and audit-friendly, but becomes slow as journal volume grows ($O(N)$ postings). | Maintain a materialised snapshot summary table per account, periodically updated via batch triggers or background jobs. |
| Strict Serializability vs. Read Committed | SERIALIZABLE isolation prevents write skew during hold checks, but creates frequent transaction retry aborts under heavy concurrency. | Use explicit row-level locks (SELECT ... FOR UPDATE) on target account_id rows under default READ COMMITTED isolation. |
| Single Cross-Currency Ledger | Storing multi-currency amounts in a single table without normalization complicates summation queries. | Strictly isolate accounts to a single native currency; enforce FX conversions at journal boundaries via external bridge accounts. |