wasAsked.

Explain SQL transaction isolation and choose an approach for inventory reservation under concurrency.

Flipkart · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, SQL, System Design

Community answers

Posted by wasAsked editorial collection

Isolation levels define how concurrent transactions see each other's changes. Anomalies - Dirty read: reading uncommitted changes. - Non-repeatable read: the same row returns different values within one transaction. - Phantom read: a repeated query returns new rows. - Lost update: two transactions read and write the same value; one write is lost. - Write skew: two transactions each read overlapping data and make changes that together break a rule. Standard levels - READ UNCOMMITTED: allows dirty reads. - READ COMMITTED: no dirty reads (the default in PostgreSQL, Oracle and SQL Server). - REPEATABLE READ: rows read stay stable (the default in MySQL InnoDB; in PostgreSQL it is snapshot isolation). - SERIALIZABLE: equivalent to running transactions one after another; may block or abort transactions with serialization failures that must be retried. Inventory reservation: preventing overselling The safest and most scalable approach is an atomic conditional update, which works under READ COMMITTED: @Modifying @Query("update Inventory i set i.available = i.available - :qty where i.productId = :id and i.available >= :qty") int reserve(@Param("id") long productId, @Param("qty") int qty); If it returns 0, there is not enough stock. The database locks the row during the update, so two concurrent reservations cannot both succeed for the last unit. Alternatives - Optimistic locking: a @Version field on the Inventory entity. Concurrent updates fail with OptimisticLockException, and the service retries (Spring Retry). Good when contention is low. - Pessimistic locking: SELECT ... FOR UPDATE through @Lock(LockModeType.PESSIMISTIC_WRITE) when the reservation logic needs to read several values before deciding. Keep transactions short to limit blocking and deadlocks. - SERIALIZABLE isolation: correct for complex multi-row rules, but expect retries on serialization failures and reduced throughput. Additional design points - Reservations with expiry: reserve stock when checkout starts, release it if payment does not complete within N minutes (a scheduled job or delayed message). - Idempotency keys so retried requests do not reserve twice. - For extremely hot items (flash sales), partition stock into buckets or use Redis atomic operations (Lua scripts) with periodic reconciliation to the database. - In Spring, set isolation with @Transactional(isolation = Isolation.READ_COMMITTED) when you need a non-default level, and keep transactions as short as possible.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics