HLD: Payment System & Gateway (Razorpay / Stripe)
1. Architectural Overview & System Goals
Architecting a resilient, highly consistent financial payment processing platform like Razorpay, Stripe, or Adyen requires solving some of the most unforgiving challenges in distributed engineering. The system must process millions of real-time transactions across volatile, third-party banking legacy infrastructure while maintaining infallible financial ledger accuracy, zero double-spend vulnerabilities, and total compliance with rigorous payment industry security standards (PCI-DSS).
Functional Requirements
- Omnichannel Payment Execution: Interop with multi-method payment instruments (Credit/Debit Cards, UPI, Open Banking NetBanking, Mobile Wallets) executing authorization, capture, void, and refunds.
- Merchant Settlement & Ledgering: Immutable internal double-entry financial ledger accounting, calculating dynamic processing fees, tax holds, and executing scheduled payout disbursements into merchant bank accounts.
- Webhooks & Asynchronous Notification: Highly reliable event callback propagation alerting external merchant e-commerce backend servers of asynchronous transaction status mutations.
- Tokenization & Vaulting: Compliant vaulting and cryptographic tokenization of sensitive cardholder credentials to minimize regulatory compliance exposure footprint.
Non-Functional & Operational Goals
- Strict ACID Consistency & Zero Double-Spend: Absolute prohibition of eventual consistency across core financial ledger write transitions; duplicate money creation or undetected balance destruction is completely unacceptable.
- System-Wide Idempotency: Guaranteed execution safety permitting external network clients and internal daemons to retry timed-out payment requests infinitely without triggering duplicate monetary debit captures.
- High Availability & Fallback Routing: Five-nines () availability across payment ingestion routing gates, utilizing automated smart acquisition switching to bypass failed acquiring banking institutions in real-time.
2. Capacity Planning & Back-of-the-Envelope Estimation
Let us dimension infrastructure constraints for a nation-scale enterprise payment facilitator executing 10 Million Transactions Per Day (TPD) across tens of thousands of online merchant ecosystems.
Transaction Volumetrics & Throughput Modeling
- Average Operational Transaction Throughput:
- Peak Surge Volume (Flash Sales / Holiday Traffic): Payment traffic exhibits extreme, concentrated volumetric spikes during retail flash sales (e.g., Diwali or Black Friday shopping rushes). Applying a peak amplification multiplier: Note: Unlike lossless video streaming or read-heavy chat reads, a single payment authorization initiates an arduous synchronous computational chain involving cryptographic HSM operations, dynamic fraud scoring evaluation engines, and multiple slow cross-network bank API calls ( round trips).
Ledger Storage & Database Sizing
- Double-Entry Ledger Ingestion: Every successful financial event necessitates at least two atomic accounting rows inside immutable ledger tables (Debit account and Credit account), plus supplemental rows capturing platform transaction fee splits and municipal tax reservations ( ledger database insertions per payment).
- Storage Sizing Computation: Assuming each cryptographic financial audit row with detailed JSON metadata requires of physical storage: Note: Regulatory financial audit norms mandate retention of transactional ledgers for a minimum of ( minimum archival footprint).
3. High-Level Architecture Design
To satisfy PCI-DSS Compliance mandates, the physical infrastructure strictly partitions into two network zones: a heavily quarantined Cardholder Data Environment (CDE) operating specialized tokenization HSM vaults, and the Non-CDE Application Zone processing general accounting and orchestration logic.
graph TD
subgraph Merchant Client Edge
Browser[Checkout Browser JS / Mobile App]
MerchantBackend[Merchant E-Commerce Backend Server]
end
subgraph PCI-DSS Cardholder Data Environment CDE
TokenGateway[Secure Tokenization Gateway]
HSM[(PCI Vault & Hardware Security Modules)]
end
subgraph Core Non-CDE Payment Architecture
API[API Gateway / Idempotency Layer]
PaymentEngine[Payment State Machine Orchestrator]
RiskSvc[AI Anti-Fraud & Risk Assessment Engine]
RouterSvc[Smart Bank Router & Acquirer Switch]
LedgerSvc[Immutable Double-Entry Ledger Service]
WebhookSvc[Asynchronous Webhook Dispatch Engine]
end
subgraph External Financial Infrastructure
BankA[Acquirer Bank Tier-1 Gateway HDFC/ICICI]
CardNetworks[Visa / Mastercard / NPCI Network]
end
subgraph Persistent Storage & Queues
TxnDB[(Master Sharded OLTP DB PostgreSQL/Spanner)]
Redis[Redis Cluster: Idempotency Keys & Locks]
Kafka[Apache Kafka Financial Event Logs]
end
Browser -->|1. Direct Sensitive Card Embed| TokenGateway
TokenGateway <--> HSM
TokenGateway -->|2. Return Safe Card Token 'tok_xyz'| Browser
Browser -->|3. Transmit Payment Submit with Token| MerchantBackend
MerchantBackend -->|4. Charge Request + Idempotency-Key| API
API -->|Verify Idempotency Lock| Redis
API --> PaymentEngine
PaymentEngine <--> TxnDB
PaymentEngine --> RiskSvc
PaymentEngine --> RouterSvc
RouterSvc -->|5. Secure Financial Routing| BankA
BankA <--> CardNetworks
PaymentEngine -->|6. Record Final Accounting| LedgerSvc
LedgerSvc -->|ACID Ledger Commit| TxnDB
PaymentEngine -->|7. Emit Async Status Mutation| Kafka
Kafka --> WebhookSvc
WebhookSvc -->|8. Signed HTTP POST Webhook| MerchantBackend
Architectural Component Interaction
- Tokenization Gateway (PCI Vault): Sensitive RAW card numbers never cross normal application boundaries. The end-user's checkout browser communicates directly with the quarantined Vault, which injects card details into encrypted Hardware Security Modules (HSM) and substitutes an irreversible surrogate random string (
tok_49182ab9). - Idempotency Execution Filter: An intercepting middleware layer mapping external merchant-supplied unique HTTP request headers (
Idempotency-Key: req_uuid_9912) to fast Redis distributed locks and persistent transactional logs, guaranteeing exact-once processing semantics regardless of network disconnect re-retries. - Payment State Machine Orchestrator: An engine modeled via deterministic Finite State Machines (FSM). It arbitrates transition states (
CREATEDPENDINGAUTHORIZEDCAPTUREDorFAILED), ensuring asynchronous network timeouts trigger safe polling reconciliation workflows rather than undefined hanging states.
4. In-Depth Component Mechanics & Protocols
4.1 Idempotency & Distributed Race Condition Prevention
When a merchant application initiates an authorization command to capture \100.00$, but a transient networking router failure drops the HTTP response packet while the backend processing succeeded, the merchant server will deterministically execute an automatic retry. Without mathematical idempotency enforcement, the customer account suffers an unlawful duplicate charge debit.
- Distributed Locking Protocol (Redlock / Redis): When a payment execution API payload hits the gateway bearing an
Idempotency-Key, the controller immediately asserts an atomic Compare-and-Set locking operation against Redis:SETNX idempotency:req_uuid_9912 "LOCKED_IN_PROGRESS" EX 60IfSETNXreturns0(key exists), an identical concurrent execution transaction is currently processing; the gateway holds the secondary incoming thread or discards it with an HTTP409 Conflictexception. - Permanent Transaction Outcome Caching: Once the primary transaction concludes via external bank responses, the exact raw HTTP response status code and JSON output body are serialized directly into an immutable database tracking table against the idempotency key. Subsequent retries spanning weeks later bypass execution engines completely, instantly returning the precise historically archived payload response.
sequenceDiagram
autonumber
participant Merchant as Merchant Backend Server
participant Gateway as API Gateway / Idempotency Filter
participant Redis as Redis Cache Cluster
participant Engine as Payment State Orchestrator
participant Bank as External Bank Acquirer Gateway
participant DB as Postgres Relational Ledger
Merchant->>Gateway: POST /v1/charges (Idempotency-Key: 7a82b-99f1, Amt: $150)
Gateway->>Redis: SETNX idempotency:7a82b-99f1 "LOCKED" (TTL: 60s)
alt Key Already Present in Cache / DB
Redis-->>Gateway: Return 0 (Lock Failed - Duplicate)
Gateway->>DB: Fetch existing completed Transaction Result
DB-->>Gateway: Return historically archived charge JSON (Status: SUCCESS)
Gateway-->>Merchant: Respond HTTP 200 OK (Zero duplicate charge incurred)
else Key Successfully Acquired (First execution attempt)
Redis-->>Gateway: Return 1 (Lock Acquired Successfully)
Gateway->>Engine: Execute Authorization State Sequence
Engine->>Bank: Call external bank payment switching networks
Note over Bank: Bank process takes 2,500ms...
Bank-->>Engine: Bank returns authorization approval (AuthCode: 9811A)
Engine->>DB: Commit ACID double-entry ledger & mark Charge Status = CAPTURED
Engine->>Redis: UPDATE Key -> Cache finalized JSON Response (TTL: 24h)
Gateway-->>Merchant: Respond HTTP 200 OK (Charge CAPTURED)
end
4.2 Immutable Double-Entry Ledgering & ACID Isolation
Payment ledgers refuse to rely on mutable variable balances (UPDATE accounts SET balance = balance - 100 WHERE id = 1). Mutable operations induce severe concurrency race hazards and completely extinguish critical audit traceability trails.
- Double-Entry Architectural Immutable Pattern: Every monetary transition constitutes an append-only creation of balanced accounting journal rows where .
- Database Isolation Configuration: To prevent phenomenon like Dirty Reads or Non-Repeatable Phantom queries during simultaneous concurrent balance evaluations, primary storage engines (such as PostgreSQL or Google Cloud Spanner) run strictly at Serializable or Repeatable Read isolation levels, utilizing robust Optimistic Concurrency Control (OCC) combined with version fencing tokens (
SELECT ... FOR UPDATErow-level pessimistic locking during rapid payout deductions).
4.3 Automated Asynchronous Reconciliation Loop
External bank gateways inevitably experience localized hardware crashes, silent fiber cut drops, or batch processing delays causing internal Payment Gateway records (PENDING) to decouple from true real-world bank state (CAPTURED).
- The Reconciliation Daemon (EOD / Continuous Sync): High-reliability architectures orchestrate automated background cron jobs and streaming SFTP log ingestion engines. Every night, partner acquiring banking institutions deposit standardized encrypted structural settlement files (NFS / CSV formats) detailing all physical inter-bank clearing movements.
- Reconciliation Difference Engine: Distributed mapping parsing workers cross-reference every financial transaction row inside internal operational ledgers against external banking statement dumps via specialized matching algorithms. Un-matched orphan transactions flag instantly for human risk mitigation review or trigger automated corrective system ledger adjusting journal entries.
5. Production-Grade Implementation: Idempotence FSM Engine & Double-Entry Ledger
The following enterprise Python reference implementation architectures an atomic Idempotent Request Intercept Engine, deterministic Payment Finite State Machine (FSM), and an immutable Double-Entry ACID accounting ledger.
import time
import uuid
import threading
import logging
from typing import Dict, List, Optional, Tuple
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
class IdempotencyLockException(Exception):
pass
class IdempotencyRegistry:
"""In-memory Redis distributed locking lock and historical response simulation."""
def __init__(self):
self._locks: Dict[str, str] = {}
self._responses: Dict[str, Dict[str, any]] = {}
self._mutex = threading.Lock()
def acquire_lock(self, key: str) -> Tuple[bool, Optional[Dict[str, any]]]:
with self._mutex:
if key in self._responses:
# Historical completion found! Return cached execution outcome instantly
return False, self._responses[key]
if key in self._locks:
# Concurrent identical execution attempt is actively in progress
raise IdempotencyLockException(f"Concurrent processing lock active for key: {key}")
# Acquire execution lock
self._locks[key] = "LOCKED"
return True, None
def store_response_and_release(self, key: str, response_data: Dict[str, any]) -> None:
with self._mutex:
self._responses[key] = response_data
if key in self._locks:
del self._locks[key]
class LedgerEntry:
"""Immutable single accounting line item inside a balanced double-entry journal transaction."""
def __init__(self, txn_id: str, account_id: str, entry_type: str, amount_cents: int):
self.entry_id = str(uuid.uuid4())
self.txn_id = txn_id
self.account_id = account_id
self.entry_type = entry_type # 'DEBIT' or 'CREDIT'
self.amount_cents = amount_cents
self.timestamp = time.time()
class DoubleEntryLedgerService:
"""Strict append-only immutable financial accounting database engine."""
def __init__(self):
self._entries: List[LedgerEntry] = []
self._db_lock = threading.Lock()
def record_balanced_transaction(self, txn_id: str, debits: List[Tuple[str, int]], credits: List[Tuple[str, int]]) -> bool:
with self._db_lock:
# 1. Enforce mathematical balanced double-entry invariance
total_debit = sum(amount for _, amount in debits)
total_credit = sum(amount for _, amount in credits)
if total_debit != total_credit or total_debit <= 0:
raise ValueError(f"CRITICAL: Unbalanced accounting journal! Debits: {total_debit} != Credits: {total_credit}")
# 2. Append immutable record rows to persistent financial storage
for acc_id, amt in debits:
self._entries.append(LedgerEntry(txn_id, acc_id, "DEBIT", amt))
for acc_id, amt in credits:
self._entries.append(LedgerEntry(txn_id, acc_id, "CREDIT", amt))
logging.info(f"[LEDGER COMMIT] ACID double-entry journal written for Txn {txn_id} | Total Volume: ${total_debit/100:.2f}")
return True
def get_account_balance_cents(self, account_id: str) -> int:
"""Calculates balance dynamically via O(N) sweep of immutable historical log rows."""
with self._db_lock:
balance = 0
for entry in self._entries:
if entry.account_id == account_id:
if entry.entry_type == "CREDIT":
balance += entry.amount_cents
else:
balance -= entry.amount_cents
return balance
class PaymentStateMachine:
"""Deterministic Finite State Machine guiding transaction outcomes."""
VALID_TRANSITIONS = {
"INITIATED": ["AUTHORIZING", "FAILED"],
"AUTHORIZING": ["AUTHORIZED", "REJECTED", "GATEWAY_TIMEOUT"],
"AUTHORIZED": ["CAPTURED", "VOIDED"],
"GATEWAY_TIMEOUT": ["AUTHORIZING", "RECONCILED"],
"CAPTURED": ["REFUNDED"]
}
def __init__(self, txn_id: str):
self.txn_id = txn_id
self.current_state = "INITIATED"
self._state_lock = threading.Lock()
def transition_to(self, new_state: str) -> None:
with self._state_lock:
allowed = self.VALID_TRANSITIONS.get(self.current_state, [])
if new_state not in allowed:
raise Exception(f"[FSM VIOLATION] Invalid payment state transition: {self.current_state} =/=> {new_state} for Txn {self.txn_id}")
logging.info(f"[FSM TRANSITION] Txn {self.txn_id}: {self.current_state} ---> {new_state}")
self.current_state = new_state
class PaymentGatewayOrchestrator:
"""Unified application gateway executing idempotency checks, FSM mutations, bank routing, and ledgering."""
def __init__(self, registry: IdempotencyRegistry, ledger: DoubleEntryLedgerService):
self.registry = registry
self.ledger = ledger
def execute_payment(self, idempotency_key: str, merchant_id: str, customer_id: str, amount_cents: int) -> Dict[str, any]:
logging.info(f"\n[INCOMING REQUEST] Executing charge for Key: {idempotency_key} | Amount: ${amount_cents/100:.2f}")
# 1. Evaluate Distributed Idempotency Lock Layer
try:
lock_acquired, cached_resp = self.registry.acquire_lock(idempotency_key)
if not lock_acquired and cached_resp:
logging.warning(f"[IDEMPOTENT INTERCEPT] Duplicate request detected for key {idempotency_key}! Bypassing bank execution; returning historical payload.")
return cached_resp
except IdempotencyLockException as exc:
logging.error(f"[LOCK CONFLICT] {exc}")
return {"status": "HTTP_409_CONFLICT", "error": str(exc)}
# 2. Instantiate Transaction State Machine
txn_id = f"pay_{uuid.uuid4().hex[:10]}"
fsm = PaymentStateMachine(txn_id)
try:
# 3. Authorize via simulated Acquirer Bank Switch
fsm.transition_to("AUTHORIZING")
time.sleep(0.1) # Simulating cross-network banking gateway handshake
bank_approved = True # Simulated positive authorization response
if bank_approved:
fsm.transition_to("AUTHORIZED")
fsm.transition_to("CAPTURED")
# 4. Compute financial processing fee structures ($0.30 + 2% standard platform fee)
platform_fee_cents = 30 + int(amount_cents * 0.02)
merchant_payout_cents = amount_cents - platform_fee_cents
# 5. Commit atomic double-entry ledger accounting rows
debits = [(f"acc_customer_{customer_id}", amount_cents)]
credits = [
(f"acc_merchant_{merchant_id}", merchant_payout_cents),
("acc_platform_revenue", platform_fee_cents)
]
self.ledger.record_balanced_transaction(txn_id, debits, credits)
response_payload = {
"status": "SUCCESS",
"transaction_id": txn_id,
"state": fsm.current_state,
"gross_cents": amount_cents,
"net_merchant_payout_cents": merchant_payout_cents,
"platform_fee_cents": platform_fee_cents
}
else:
fsm.transition_to("REJECTED")
response_payload = {"status": "DECLINED", "transaction_id": txn_id, "state": fsm.current_state}
# 6. Commit final transactional payload into Idempotency Registry & unlock
self.registry.store_response_and_release(idempotency_key, response_payload)
return response_payload
except Exception as err:
fsm.transition_to("FAILED")
logging.error(f"[SYSTEM ERROR] Payment failed during orchestration: {err}")
self.registry.store_response_and_release(idempotency_key, {"status": "ERROR", "message": str(err)})
raise
# --- Execution Simulation ---
if __name__ == "__main__":
redis_idempotent_db = IdempotencyRegistry()
immutable_ledger = DoubleEntryLedgerService()
gateway = PaymentGatewayOrchestrator(redis_idempotent_db, immutable_ledger)
# 1. Merchant executes valid initial payment authorization request ($100.00)
tx1 = gateway.execute_payment("req_key_8921", merchant_id="m_nike", customer_id="c_alice", amount_cents=10000)
print(f"Outcome 1: {tx1}")
# 2. Simulate Network Disconnect Recovery: Merchant resubmits IDENTICAL request with SAME idempotency key
tx2 = gateway.execute_payment("req_key_8921", merchant_id="m_nike", customer_id="c_alice", amount_cents=10000)
print(f"Outcome 2 (Retry Intercept): {tx2}")
# 3. Execute another separate valid transaction to build financial balance
tx3 = gateway.execute_payment("req_key_4402", merchant_id="m_nike", customer_id="c_bob", amount_cents=5000)
# 4. Verify balanced ledger accounting
print("\n--- [AUDIT REPORT] Immutable Ledger Account Balances ---")
print(f"Merchant Nike Balance : ${immutable_ledger.get_account_balance_cents('acc_merchant_m_nike')/100:10.2f}")
print(f"Platform Revenue Acc : ${immutable_ledger.get_account_balance_cents('acc_platform_revenue')/100:10.2f}")
print(f"Customer Alice Acc : ${immutable_ledger.get_account_balance_cents('acc_customer_c_alice')/100:10.2f}")
print(f"Customer Bob Acc : ${immutable_ledger.get_account_balance_cents('acc_customer_c_bob')/100:10.2f}")
6. Failure Modes, Edge Cases, & Resiliency Engineering
| Failure Vector | Architectural Symptom | Engineering Mitigation Strategy |
| :--- | :--- | :--- |
| Acquirer Bank Gateway Down | Primary Tier-1 Bank (e.g., HDFC or Chase) network connectivity terminates; authorization attempts uniformly return HTTP 503 or timeout. | Automated Smart Acquirer Switching: Payment engines operate continuous synthetic canary polling against multiple redundant acquiring banks. If Bank-A drop rates exceed within a rolling 60-second window, automated routing circuits switch internal authorization routing dynamically to backup Acquirer Bank-B (e.g., ICICI or Citi) without client user interruption. |
| Webhook Delivery Exhaustion | A merchant e-commerce backend goes offline during deployment; asynchronous capture confirmation webhooks fail (HTTP 500). | Exponential Backoff with Jitter & Dead-Letter Queues (DLQ): Webhook dispatchers apply randomized exponential retries () across a delivery window. Unacknowledged messages ultimately transition to an inspected DLQ database table where automated alert emails compel merchant operational attention. |
| Split-Brain Bank Timeout | A customer initiates a \500$ charge; the internal network connection breaks exactly after the external bank processed the capture, leaving internal systems in state AUTHORIZING. | The Asynchronous Reconciliation Protocol (No Silent Voids): Systems are forbidden from automatically marking timed-out transactions as FAILED or triggering automatic instant voids without bank consensus. The FSM parks the transaction in an intermediate GATEWAY_TIMEOUT state and enqueues a background polling task to repeatedly invoke the bank's API verification status endpoint (GET /bank/v1/status?tx=xxx) until definitive resolution lands. |
| Idempotency Cache Eviction | An idempotency locking hash key purges from volatile Redis RAM due to high memory pressure before an asynchronous delayed network retry arrives. | Persistent Hybrid Tiered Locking: Redis serves merely as an ultra-fast first-line concurrent memory shield. Every idempotency key and resulting outcome payload simultaneously commits asynchronously into a permanent, highly resilient relational Database storage partition (with a mandatory 30-day retention lock) before operational execution initiates. |
7. Deep-Dive Interview Question & Answer Bank
Q1: How do you mathematically guarantee that an internal database server hardware outage occurring precisely between charging the user's credit card and writing the double-entry accounting row doesn't destroy general ledger balance integrity?
A: We utilize Two-Phase Commit (2PC) Architectural Saga Patterns combined with Outbox Pattern persistence. External banking APIs cannot participate in internal SQL database ACID atomic locks; therefore, we decouple financial capture from ledgering via an atomic database Outbox Table. Before calling the external bank API, a transaction intent record commits locally within an ACID database transaction. Once the external bank gateway returns approval, an internal database transaction atomico-writes BOTH the final double-entry accounting rows AND an Outbox event marking completion. If the server crashes mid-flight, crash-recovery daemons sweep incomplete pending Outbox intent logs, querying external bank status validation APIs and resuming the incomplete journal ledgering sequence deterministically.
Q2: Describe how to engineer an automated fraud detection latency budget without causing user payment checkout shopping cart abandonment.
A: Modern payment gateways operate under a strictly enforced SLA Fraud Scoring Budget. We bifurcate risk evaluation into synchronous and asynchronous processing layers.
- Synchronous Fast-Path (): Before network bank transmission, the charge passes through an ultra-low latency rules engine evaluating localized real-time in-memory features (e.g., Is IP blacklisted? Has this card attempted 5 transactions in 2 minutes?). If high-risk thresholds exceed, an instantaneous pre-bank block occurs.
- Asynchronous Heavy AI/ML Deep Inspection: Concurrently with external bank routing, complex deep neural networks ingest behavioral graph anomalies across global network nodes. If asynchronous AI models flag severe fraud after bank authorization succeeds but before merchant dispatch, the FSM instantly fires an automated Payment Reversal / Auth Void API command to the acquiring bank, neutralizing fraud without penalizing standard checkout user latency.
Q3: How do payment architectures accommodate regional regulations like India's RBI Mandate for Multi-Factor Authentication (MFA / 3D-Secure / OTP) or Europe’s PSD2 SCA norms?
A: Payment workflows transition from simple one-step synchronous authorizations into Multi-Step Asynchronous Redirect Redirect Workflows (3D-Secure 2.0 / SCA). When an initial charge is initiated, the smart routing gateway interrogates the card BIN (Bank Identification Number). If 3D-Secure authentication is legally mandated, the payment orchestrator aborts immediate capture and returns an interactive authentication challenge payload containing an iframe redirect URL (HTTP 202 Accepted). The consumer's client application redirects to the card-issuing bank's secured SMS OTP validation web-portal. Upon successful OTP verification, the Issuing Bank redirects the user back via an authenticated Cryptographic 3DS Accounter Verification Value (CAVV) token, allowing the backend FSM to legally execute final financial settlement capture.
Q4: What specific architectural mechanisms protect a multi-tenant payment gateway against catastrophic SQL injection or horizontal privilege escalation where Merchant A reads or executes payouts against Merchant B’s ledger balance?
A: We execute Cryptographic Row-Level Security (RLS) combined with Zero-Trust Multi-Tenant Partitioning. Database queries never depend purely on application developers manually appending WHERE merchant_id = 'm_123' statements. Instead, application connection pools utilize scoped ephemeral database user roles that inject an cryptographic Session Context variable (SET LOCAL application.current_merchant_id = 'm_123';) upon every database transaction initiation. Database table definitions enforce rigid internal OS-level Row-Level Security policies (CREATE POLICY merchant_isolation ON ledger_entries USING (merchant_id = current_setting('application.current_merchant_id'));), physically barring database SQL engines from reading or updating adjacent tenant records even if an application-layer injection vulnerability is exploited.
Q5: Why do credit card authorizations expire after 7 days, and how does an e-commerce architecture handle delayed physical merchant shipping workflows (such as pre-ordering an iPhone 3 months before launch)?
A: Card network association bylaws (Visa/Mastercard) stipulate that initial authorization holds (reserving customer credit limit) automatically release after a rigid temporal window (typically for general retail, for lodging/car rental) to prevent unjustified indefinite customer balance lockups. For long-delay fulfillment e-commerce workflows, the architecture implements a Bifurcated Auth-then-Re-Auth pattern. At pre-order placement, the payment gateway executes either a zero-dollar account verification ($0.00 Auth) or a standard authorization that is deliberately permitted to expire gracefully after 7 days. When the physical warehouse scans the barcode initiating box shipment months later, an asynchronous background orchestration daemon initiates an off-session Merchant-Initiated Transaction (MIT) using vaulted cryptographic network tokens (tok_49182ab9) to execute a fresh, real-time capture directly against the account without requiring the consumer to interactively re-enter credit card credentials or clear MFA OTP hurdles.