In American Express payment and account systems, concurrent updates to balances, authorizations, and ledger entries must be handled safely. Interviewers ask this to assess whether you understand how databases prevent lost updates and inconsistent transaction states.
Explain the difference between optimistic locking and pessimistic locking in the context of a banking transaction. Your answer should cover:
Keep the discussion practical rather than academic. The interviewer expects you to connect the concepts to real transaction flows like debits, credits, balance updates, or payment authorization, and to explain why one approach may be safer or more scalable depending on contention levels.
Pessimistic locking assumes conflicts are likely, so a transaction locks the row before updating it. Other transactions must wait, which reduces concurrency but prevents two sessions from modifying the same balance at the same time.
BEGIN;
SELECT account_id, balance
FROM amex_accounts
WHERE account_id = 101
FOR UPDATE;
UPDATE amex_accounts
SET balance = balance - 100.00
WHERE account_id = 101;
COMMIT;
Optimistic locking assumes conflicts are relatively rare, so transactions proceed without taking an early lock. At update time, the application checks whether the row changed since it was read, usually with a version number or last_updated value.
UPDATE amex_accounts
SET balance = balance - 100.00,
version = version + 1
WHERE account_id = 101
AND version = 7;
Both approaches aim to prevent lost updates, where two concurrent transactions read the same starting balance and one overwrites the other's change. In banking, this can lead to incorrect balances, duplicate debits, or broken ledger reconciliation.
With pessimistic locking, a conflicting transaction usually waits for the lock to be released. With optimistic locking, the conflicting transaction typically fails its version check and must retry or return an error to the application.
PostgreSQL supports pessimistic locking through row-level locks such as FOR UPDATE. It supports optimistic locking through application-managed version columns, conditional UPDATE statements, and transaction isolation rules.
SELECT *
FROM amex_accounts
WHERE account_id = 101
FOR UPDATE;