Locking and concurrency control
18 questions in 5 subtopics.
Optimistic locking with @Version
How does optimistic locking with@Version work in JPA, and what exception does a Spring application see on a conflict?How would you force a version increment on an Order when one of its OrderLines changes, so that concurrent edits of different lines are detected as conflicts on the order aggregate?In a REST API, a user loads a product, edits it for five minutes and saves it with PUT. How do you prevent overwriting changes made by others in the meantime?Concurrency bugs (lost updates, double bookings) are found years after systems go live and are expensive to fix. What organisational practices reduce this risk over the long term?Pessimistic locking
Write a Spring Data JPA method that loads an account with SELECT ... FOR UPDATE and explain when you would use it.Implement a job queue in PostgreSQL that several worker instances poll without processing the same job twice. What SQL and Spring setup would you use?A flash sale on one product causes thousands of transactions to queue on a single row lock for its stock count, and latency explodes. What designs would you consider?Your company is evaluating a move from a single-primary relational database to a distributed SQL database for global scale. How would existing locking and concurrency patterns be affected, and how would you assess the risk?Lost updates
Two requests run this code at the same time for the same account:Account a = repo.findById(id).get();
a.setBalance(a.getBalance().add(amount));
repo.save(a);
@Version, one change is lost. Explain why, and discuss the options.Across services, lost updates appear in counters, balances and inventory. Define a standard set of concurrency patterns teams should choose from, with guidance on when to use each.Deadlocks in the database
What is a database deadlock, how does the database resolve it, and how does it appear in a Spring application?In MySQL InnoDB under REPEATABLE READ, two transactions that each run SELECT ... FOR UPDATE for a non-existent row and then INSERT it deadlock. Why?Deadlocks appear daily in a service that transfers money between two accounts by locking them in the order (from, to). How do you diagnose and fix them?Deadlock and lock-timeout errors are rising across many services that share a database. How would you organise the investigation and long-term fix?Idempotent writes
A Kafka consumer inserts payments and may receive the same message twice. Make the write idempotent using the database.Design an idempotent 'apply discount to order' operation that may be retried by clients and redelivered by a message broker, where applying twice would double the discount.Exactly-once processing is often promised by vendors. How would you guide an organisation's long-term thinking about duplicates, ordering and correctness in data pipelines and services?No question matches these choices.