Quick revision
The short answer
I would define five patterns and when to use each: atomic conditional updates for counters and simple invariants, optimistic locking for user edits and low-contention aggregates, pessimistic locks for short critical sections under high contention, serializable transactions with retry for invariants that span several rows, and single-writer designs, such as a queue partitioned by key, for very hot keys. Each pattern comes with a worked example, a shared retry helper and a test template, so teams pick from a short catalogue instead of inventing their own.
What to remember
In this answer, we built a standard set of five concurrency patterns: atomic conditional updates for counters and simple rules, optimistic locking for user edits and quiet aggregates, pessimistic locks for short contended sections, serializable transactions with retry for multi-row invariants, and single writers per key for very hot data. A decision guide, worked examples, shared retry helpers and test templates make the catalogue easy to use, and design reviews and incident checks keep it current.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would define five patterns and when to use each: atomic conditional updates for counters and simple invariants, optimistic locking for user edits and low-contention aggregates, pessimistic locks for short critical sections under high contention, serializable transactions with retry for invariants that span several rows, and single-writer designs, such as a queue partitioned by key, for very hot keys. Each pattern comes with a worked example, a shared retry helper and a test template, so teams pick from a short catalogue instead of inventing their own.
Why this question is asked
When lost updates appear in counters, balances and inventory across many services, the problem is not one team's mistake; it is that every team is solving concurrency from scratch. A standard catalogue turns a hard topic into a choice among known patterns with known costs. Interviewers ask for it at this level to see whether we can give clear guidance that engineers can apply without being experts. In this answer, we will recap why lost updates happen, go through each pattern with an example and its trade-offs, and then look at how to make the catalogue usable through a decision guide and shared code.
1A Quick Recap: Where Lost Updates Come From
A lost update happens when code reads a value, computes a new one in the application, and writes it back, while another request does the same in between. The default isolation level in PostgreSQL, READ COMMITTED, does not prevent it. Every pattern in the catalogue prevents it in a different way: by letting the database compute the change, by detecting the conflict, by making requests wait, by having the database abort one transaction, or by making sure only one writer ever touches the data.
2Pattern 1: Atomic Conditional Updates
When the change is arithmetic or a simple condition, the database does it in one statement. update stock set qty = qty - :n where id = :id and qty >= :n both decrements and enforces that stock never goes negative; zero rows updated means the rule failed. The lock is held only for that statement, so throughput is high. This is the default for counters, balances, quotas and inventory decrements. Its limit is logic: it only fits rules that a WHERE clause can express.
3Pattern 2: Optimistic Locking
A @Version column makes every update check that the row has not changed since it was read; a conflict raises ObjectOptimisticLockingFailureException. No locks are held while the user or the code works, so it suits user edits through a form, where the read and write are minutes apart, and aggregates that are rarely changed at the same time. Conflicts are either retried, when the work can be recomputed, or reported to the user. For REST APIs the version travels as an ETag with If-Match. Under high contention it degrades, because most attempts fail and retry.
4Pattern 3: Pessimistic Locks for Short Critical Sections
When the same row is changed often and the logic is more than a single statement, a row lock with SELECT ... FOR UPDATE, or @Lock(PESSIMISTIC_WRITE) in Spring Data, makes competing requests wait in line instead of failing. The rules are strict: the transaction must be short, contain no remote calls, set a lock timeout, and lock multiple rows in a fixed order, such as ascending id, to avoid deadlocks. Typical uses are transfers between two accounts or allocating a resource with several checks.
5Pattern 4: Serializable Transactions With Retry
Some invariants span several rows and no single row lock protects them. The classic example is a rule that at least one doctor must be on call: two doctors each check that the other is on call and both go off duty. This is write skew, and neither optimistic locking on each row nor a single atomic update prevents it. Running that transaction at SERIALIZABLE isolation makes PostgreSQL detect the dangerous pattern and abort one transaction with a serialization failure, which we retry. The cost is retries under contention and the discipline to keep side effects out of the retried block.
The retry must wrap the transaction from outside, which is why the catalogue ships a shared helper for it rather than asking each team to write one.
6Pattern 5: Single Writer per Key
For very hot keys, such as one product during a flash sale or one popular account receiving thousands of events per second, even short locks become a queue. The single-writer pattern removes contention entirely: all changes for a key are sent to a queue partitioned by that key, such as a Kafka topic keyed by product id, and exactly one consumer processes each partition in order. Because only one thread ever writes a given key, no locking is needed. The costs are asynchrony, since callers learn the result later, and the operational work of running the queue.
With the five patterns described, the catalogue needs a way to pick one quickly. A decision guide and a summary table on one page do that.
| Pattern | Use for | Avoid when | Shared helper |
|---|---|---|---|
| Atomic conditional update | Counters, balances, stock | Rule needs more than a WHERE clause | Update-and-check template |
| Optimistic locking | User edits, quiet aggregates | Many writers on one row | Retry helper, ETag filter |
| Pessimistic lock | Short hot sections, transfers | Long or remote work in the tx | findForUpdate convention |
| Serializable with retry | Multi-row invariants | High contention, side effects | Serializable retry helper |
| Single writer per key | Very hot keys | Caller needs a sync result | Partitioned consumer starter |
7Making the Catalogue Usable
A catalogue only works if it is easier to follow than to ignore. Each pattern gets a worked example from one of our own incidents, a short code sample, and a shared library piece: a retry helper that wraps a TransactionTemplate with backoff for optimistic and serialization failures, a lock-timeout default for pessimistic queries, and a test template that releases many threads at once against a Testcontainers database and asserts the invariant. The design review template asks which pattern a write path uses, and the answer is one of the five names. Deviations are allowed with a written reason, and every concurrency incident is checked against the catalogue to see whether it needs a new example or a new pattern.
- Can one SQL statement express the change and rule?YesAtomic conditional updateNoContinue
- Does the rule span several rows?YesSerializable with retryNoContinue
- Is the key extremely hot?YesSingle writer per keyNoContinue
- Are conflicts frequent and the section short?YesPessimistic lockNoOptimistic locking
4 steps in order. Play them, or step through them one at a time.
Most write paths stop at the first question.
8Follow-up questions
Why not pick one pattern for everything?
Because each fails somewhere. Optimistic locking collapses under contention, pessimistic locks hurt with long transactions, serializable everywhere causes retries all over the system, and single writers make every operation asynchronous. A small catalogue with clear rules is simpler than one pattern that half the cases misuse.
Where do database constraints fit in?
Under all of them. Unique keys, check constraints and foreign keys remain the last line of defence, so that if a team picks the wrong pattern, the result is an error rather than corrupted data. The catalogue should require them for every invariant that can be expressed as one.
How do you roll this out across existing services?
Start with the services where lost updates were found, map each affected write path to a pattern, fix them using the shared helpers, and add the concurrency test. Then make the pattern question part of design reviews for new work, so the catalogue spreads with each change.
9Conclusion
In this answer, we built a standard set of five concurrency patterns: atomic conditional updates for counters and simple rules, optimistic locking for user edits and quiet aggregates, pessimistic locks for short contended sections, serializable transactions with retry for multi-row invariants, and single writers per key for very hot data. A decision guide, worked examples, shared retry helpers and test templates make the catalogue easy to use, and design reviews and incident checks keep it current.
Open with
I would give teams a short catalogue of five patterns with clear guidance, instead of letting each team improvise. First, atomic conditional updates, like update stock set qty = qty minus n where id = ? and qty >= n, for counters, balances and inventory; this is the default whenever one statement can express the rule, because it holds a lock only for that statement.
Then, if they want more
Second, optimistic locking with @Version for user edits and aggregates that rarely change concurrently, with the version as an ETag in REST, and a retry or a 409 on conflict.
Third, pessimistic locks with FOR UPDATE for short critical sections under high contention, such as transfers, with strict rules: short transactions, no remote calls, lock timeouts and a fixed locking order. Fourth, serializable transactions with retry for invariants across several rows, like keeping one doctor on call, which is write skew that the other patterns miss.
Fifth, a single writer per key, a queue partitioned by key, for extremely hot keys where even short locks queue up.
To make it stick, I would ship a decision guide, a shared retry helper, a concurrency test template using Testcontainers, and worked examples from our own incidents, require database constraints underneath every pattern, and ask in design reviews which of the five a write path uses.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Across services, lost updates appear in counters, balances and inventory. Define a...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/7017f4fc7f/