Payment Processing System
Ye ekmatra system hai jahan STRONG CONSISTENCY non-negotiable hai. Money movement DOUBLE-ENTRY LEDGER se track hota hai — har transaction do entries banata hai (ek debit, ek credit) aur dono ka jod hamesha zero rehta hai. Ledger APPEND-ONLY hota hai; entry kabhi update ya delete nahi hoti, correction bhi nayi entry se hoti hai.
Do concepts har payment interview mein aate hain. IDEMPOTENCY — network retry par double charge nahi hona chahiye, isliye har request ki unique key store hoti hai. Aur DISTRIBUTED TRANSACTION — payment, order aur inventory alag services mein hain, isliye 2PC ke bajaye SAGA pattern use hota hai jahan har step ka compensating action hota hai.
// Double-entry ledger — dono entries ka jod hamesha 0
INSERT INTO ledger (txn_id, account, amount) VALUES
('txn_123', 'user:alice', -500), -- debit
('txn_123', 'merchant:shop', 500); -- credit
// Saga: fail hone par ULTA chalo
// reserveInventory -> chargePayment -> confirmOrder
// ↓ fail ↓ fail
// releaseInventory <- refundPayment- Double-entry, append-only ledger — entry kabhi update nahi hoti
- Idempotency key se retry par double charge rukta hai
- Cross-service consistency ke liye Saga (compensating actions), 2PC nahi
Payment, order aur inventory alag services hain, isliye ek hi database transaction possible nahi. Two-phase commit theoretically kaam karta hai par practically avoid kiya jaata hai — wo blocking hai aur coordinator down hone par saare participants atak jaate hain.
SAGA pattern jawab hai: har step ka ek COMPENSATING action hota hai. Step 3 fail ho to step 2 aur step 1 ke compensating actions ulte order mein chalte hain. Dhyaan rakho — compensating action "undo" nahi hota, wo ek NAYA transaction hota hai (refund, cancellation) jo ledger mein dikhta hai.
// Forward
reserveInventory → chargePayment → confirmOrder
// chargePayment fail hua to:
releaseInventory ← (compensating action)
// Refund bhi ek NAYI ledger entry hai, purani entry delete nahi hotiCard numbers apne database mein kabhi store mat karo — PCI-DSS compliance ka bojh bahut bhaari hai. Iske bajaye TOKENIZATION use karo: card details seedhe payment provider ko jaati hain aur wo ek token lautaata hai. Tum sirf token store karte ho.
Token se future charges ho sakte hain (subscriptions ke liye) par token chori hone par bhi wo tumhaare merchant account ke bahar bekaar hai. Ye batana security awareness dikhata hai aur bahut kam candidates bolte hain.