MySQL / Reliable applications and analytical queries / Lesson 14
Guarded updates and optimistic concurrency
Use an expected version and a business condition to detect a stale inventory update.
On this page
Lesson goals
- Explain a lost update and a version guard.
- Interpret a guarded write using the driver’s affected-row contract.
- Design bounded conflict handling and verify the inventory invariant.
- Trace guarded writes and stale retries across explicit two-client schedules.
- Distinguish version conflicts, business preconditions and operation idempotency.
Identify the stale-read problem
Two clients can read the same stock value and independently decide to change it. If each later writes a value calculated from its old read without a guard, the later write can overwrite the first client’s work. A version column records the state a caller observed. A guarded update asks the server to change the row only if that expected version and the business precondition still hold.
Create a disposable stock row
The following illustrative SQL creates a small InnoDB table only for a new disposable MySQL 8.4 lab. Its nonnegative check is a second line of defense, while the update condition expresses that this particular reservation requires enough stock. The initial quantity is ten and its version is zero. The public example does not connect to a configured database.
CREATE TABLE lab_stock (
product_id INT PRIMARY KEY,
quantity INT NOT NULL,
version INT NOT NULL,
CHECK (quantity >= 0)
) ENGINE=InnoDB;
INSERT INTO lab_stock VALUES (1, 10, 0);
SELECT product_id, quantity, version FROM lab_stock WHERE product_id = 1;
The fixture contains one product with quantity 10 and version 0. The explicit check guards nonnegative stored quantities; it does not provide an application-level reservation identifier or coordinate any external service.
Change the row only from the expected state
A caller that observed version zero asks to reserve three units with one conditional UPDATE. The server evaluates the condition as part of that write, so another successful version change prevents the same stale condition from matching. The following SELECT is a separate inspection, not a substitute for checking the UPDATE response in application code.
UPDATE lab_stock
SET quantity = quantity - 3, version = version + 1
WHERE product_id = 1 AND version = 0 AND quantity >= 3;
SELECT product_id, quantity, version FROM lab_stock WHERE product_id = 1;
Starting with the fixture, one successful update leaves quantity 7 and version 1. Repeating the same version-zero update matches no row. This deterministic reasoning assumes no other changes; inspect the driver’s documented matched and changed row reporting.
Handle no match deliberately
Zero affected rows can mean a stale version, insufficient stock, a missing product, or another predicate failure. The application must distinguish those cases with an authorized follow-up read if its response needs that distinction. Do not automatically overwrite the newer version. A bounded retry may reread and reapply the business rule, but a repeated reservation also needs an operation identifier if duplicate requests must be prevented.
Test concurrency and uncertain outcomes
In a disposable lab, let two clients read version zero and then attempt the guarded update. Verify that only one succeeds with that expected version, and that quantity never becomes negative. Separately simulate a timeout after sending a request: the outcome may be unknown, so reconcile authoritative state and the operation identifier before retrying. Transaction boundaries and external payment or messaging effects need their own explicit contract.
Trace stale decisions
Optimistic concurrency starts by identifying the state a caller observed and requiring that state to remain current at the write. In the lesson fixture, product 1 begins with quantity 10 and version 0. If two clients read 10 and independently compute new absolute quantities, a later unguarded assignment can overwrite the earlier result. For example, a three-unit reservation writes 7, then a stale two-unit reservation writes 8; the final quantity 8 records only one deduction even though both clients may believe they succeeded.
A version column is a change token, not an operation identifier. A guarded update compares product_id and the expected version in the WHERE clause, checks the business condition quantity >= requested, and changes quantity and version in the same statement. Once one write increments the version, another write expecting the old version no longer matches. Every writer participating in this scheme must update the token consistently; an unguarded writer that leaves version unchanged can defeat the stale-state detection.
Combine the preconditions atomically
Validate that the requested quantity is a positive integer before writing. A negative reservation can turn subtraction into an unintended increase, even if the stored quantity remains nonnegative. For a valid request of three from quantity 10/version 0, UPDATE sets quantity to 7 and version to 1 when product_id = 1, version = 0 and quantity >= 3 all match. The arithmetic uses the current row in the statement; a separate earlier SELECT is useful for reading state but is not a lock or a guarantee that the state remains unchanged.
The CHECK (quantity >= 0) in the fixture is a backstop for stored values, while the guarded predicate expresses the business rule for this request. Neither alone checks customer authorization, identifies a reservation or coordinates a payment. Include an order or reservation record in the same transactional business unit when those changes must commit together. Check the write result immediately using the driver’s documented matched-versus-changed row behavior; the version increment ensures a successful guarded update changes the row in these examples.
Interpret no match without guessing
A zero affected-row result is an outcome, not a complete explanation. The product id may not exist, the expected version may be stale, the available quantity may be too small, or another predicate may have failed. A follow-up read in an authorized context can help diagnose the current state, but that read is a later observation and may itself race with another writer. If the response does not need a precise distinction, a generic conflict can be safer and simpler than inventing a cause from zero alone.
A bounded retry must reread the current row, revalidate the request and business rule, then attempt a fresh guarded transaction. Never silently replace the expected version with the latest one and blindly replay an old absolute value. Choose a retry limit and deadline and report an unresolved conflict when the bound is reached. If the state change makes the request invalid, such as remaining stock below the requested quantity, stop rather than retrying indefinitely.
Handle duplicate and uncertain requests
Version checks prevent two writes from succeeding against the same observed row version, but they do not by themselves prevent the same business request from being applied again after a reread. A stable operation identifier, protected by a unique constraint and recorded with the reservation in the same transaction, supports idempotent handling. Repeating the same request id should return or reconcile the existing outcome according to the application’s policy; a new id represents a different attempt only when the business intends a distinct operation.
If a connection times out during COMMIT, the client may not know whether the server committed. Do not infer failure from a missing response and immediately subtract again. Reconnect through the authorized application path, look up the durable operation identifier and reconcile the authoritative result. External payment or messaging effects need coordinated delivery and their own idempotency strategy. A database rollback cannot retract an already delivered external effect.
Test the invariant under a schedule
Use an isolated InnoDB lab with synthetic rows and two separate connections. Label each read, update and commit, and record the expected version and quantity at every step. For two clients that both observed version 0, have one commit first and verify that the second version-0 update changes zero rows. Then test an insufficient quantity, an absent product, a stale token, a nonpositive request and a duplicate operation id. Verify that no committed result is negative and that each accepted operation has exactly one durable record.
Driver APIs may report matched or changed rows differently depending on configuration, so document and test the actual connector’s contract rather than assuming a universal interpretation. Also test rollback after a later insert failure and the uncertain-commit reconciliation path. SQL and labeled schedules below are illustrative MySQL 8.4 material; results are reasoned from stated ordering, not observed engine output. Never rehearse them against production or learner data.
20 worked examples
1. First guarded reservation
Problem: What does a three-unit reservation do to quantity 10 and version 0?
- The row matches product 1, expected version 0 and sufficient quantity 10.
- The statement subtracts three and increments the version once.
UPDATE lab_stock SET quantity = quantity - 3, version = version + 1 WHERE product_id = 1 AND version = 0 AND quantity >= 3;
SELECT quantity, version FROM lab_stock WHERE product_id = 1;
7 | 1
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Quantity 7, version 1.
Why this result follows: The guard and arithmetic change are evaluated together for the matching current row.
2. Stale repeat
Problem: What happens when the same version-zero reservation is repeated after success?
- The row now has version 1 rather than the expected version 0.
- The version predicate fails, so the second statement cannot deduct again.
-- Starting state after first success: product 1, quantity 7, version 1.
UPDATE lab_stock SET quantity = quantity - 3, version = version + 1 WHERE product_id = 1 AND version = 0 AND quantity >= 3;
0 rows changed; quantity 7, version 1.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Zero rows; state remains 7/1.
Why this result follows: The version increment invalidates a second write based on the earlier observation.
3. Insufficient quantity
Problem: Can version 0 reserve eleven units from the original quantity ten?
- The id and version match but quantity 10 is less than the requested 11.
- The quantity predicate fails before any subtraction or version increment.
UPDATE lab_stock SET quantity = quantity - 11, version = version + 1 WHERE product_id = 1 AND version = 0 AND quantity >= 11;
0 rows changed; quantity 10, version 0.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Zero rows; state remains 10/0.
Why this result follows: The business guard prevents this reservation even when the version is current.
4. Exact stock
Problem: What happens when a current request reserves exactly ten available units?
- The initial quantity equals the inclusive threshold of ten.
- The update subtracts ten and increments version from zero to one.
UPDATE lab_stock SET quantity = quantity - 10, version = version + 1 WHERE product_id = 1 AND version = 0 AND quantity >= 10;
SELECT quantity, version FROM lab_stock WHERE product_id = 1;
0 | 1
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Quantity 0, version 1.
Why this result follows: An inclusive sufficiency condition permits a reservation that exactly exhausts stock. This follows the stated row state and guarded condition.
5. Missing product
Problem: What does the guarded update do when product 9 has no row?
- The fixture contains only product 1, not product 9.
- The identity predicate matches no row regardless of quantity or version.
UPDATE lab_stock SET quantity = quantity - 1, version = version + 1 WHERE product_id = 9 AND version = 0 AND quantity >= 1;
0 rows changed.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Zero rows; no product is changed.
Why this result follows: The same zero outcome can indicate absence rather than a stale version or insufficient stock.
6. Two observed versions
Problem: Which of two clients can use version 0 after A commits first?
- A’s committed update changes the row to quantity 7 and version 1.
- B still expects version 0, so its later guard matches no row.
-- A and B both read quantity 10, version 0.
-- A: UPDATE lab_stock SET quantity=quantity-3, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=3; COMMIT;
-- B afterward: UPDATE lab_stock SET quantity=quantity-2, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=2;
A changes 1 row; B changes 0; final 7 | 1.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Only A succeeds with version 0.
Why this result follows: A shared expected token allows at most one of these ordered writes to succeed.
7. Reread and retry
Problem: Can B reserve two units after rereading the new state from A?
- B rereads quantity 7 and version 1 after A’s committed reservation.
- The fresh guard permits two units and increments the token to version 2.
-- Current committed state: product 1, quantity 7, version 1.
UPDATE lab_stock SET quantity=quantity-2, version=version+1 WHERE product_id=1 AND version=1 AND quantity>=2;
SELECT quantity, version FROM lab_stock WHERE product_id=1;
5 | 2
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Quantity 5, version 2.
Why this result follows: A retry is a new decision against current state, not a blind stale overwrite.
8. Reread insufficient
Problem: What if B needs eight units after rereading quantity seven and version one?
- The expected version is current, but seven units are fewer than eight.
- The quantity guard fails and no new version is written.
-- Current committed state: product 1, quantity 7, version 1.
UPDATE lab_stock SET quantity=quantity-8, version=version+1 WHERE product_id=1 AND version=1 AND quantity>=8;
0 rows changed; state remains 7 | 1.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Zero rows; quantity 7 and version 1.
Why this result follows: Revalidating the business condition prevents a stale retry from overselling. This follows the stated row state and guarded condition.
9. Lost absolute write
Problem: How can two unguarded stale assignments lose one reservation?
- A’s absolute value records a deduction of three from the original ten.
- B overwrites it with eight calculated from the same old ten, rather than deducting from seven.
-- Both clients read quantity 10.
-- A writes quantity 7 for a three-unit reservation and commits.
-- B later writes quantity 8 computed from its stale two-unit reservation and commits.
UPDATE lab_stock SET quantity = 8 WHERE product_id = 1;
Final quantity 8; one deduction is lost.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Final quantity 8 instead of the intended 5.
Why this result follows: A stale absolute assignment does not account for intervening committed work. This follows the stated row state and guarded condition.
10. Negative request
Problem: Why must a requested quantity of minus two be rejected before the update?
- The threshold 10 >= -2 is true and subtracting minus two adds two.
- The nonnegative CHECK would not reject the resulting quantity 12.
-- Invalid request quantity = -2; do not issue this update.
UPDATE lab_stock SET quantity=quantity-(-2), version=version+1 WHERE product_id=1 AND version=0 AND quantity>=-2;
If executed from 10/0, it would increase quantity to 12 and version to 1.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Reject the nonpositive request before SQL.
Why this result follows: The database quantity guard alone does not validate that a reservation amount is positive.
11. Zero request
Problem: Why should a zero-unit reservation be rejected by application validation?
- The quantity predicate is true and subtracting zero leaves quantity unchanged.
- The version increment still changes the row despite no meaningful reservation.
-- Invalid request quantity = 0; do not issue this update.
UPDATE lab_stock SET quantity=quantity-0, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=0;
If executed from 10/0, quantity stays 10 and version becomes 1.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Reject the zero request before SQL.
Why this result follows: Positive-quantity validation prevents a version change from masquerading as a useful reservation.
12. Check backstop
Problem: What prevents an unguarded subtraction from storing a negative quantity?
- Starting from ten, subtracting eleven proposes minus one.
- The fixture’s nonnegative CHECK rejects that value even without a sufficiency predicate.
UPDATE lab_stock SET quantity=quantity-11, version=version+1 WHERE product_id=1 AND version=0;
Rejected: CHECK (quantity >= 0) would be false.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: The statement is rejected.
Why this result follows: The check protects stored quantity, while a guard expresses the reservation precondition earlier.
13. Later insert failure
Problem: What happens if an order insert fails after a guarded deduction in one transaction?
- The guarded update temporarily produces quantity 7 and version 1.
- The explicit rollback reverses that uncommitted change after the simulated failure.
START TRANSACTION;
UPDATE lab_stock SET quantity=quantity-3, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=3;
-- Simulated order insert fails; abort the complete attempt.
ROLLBACK;
SELECT quantity, version FROM lab_stock WHERE product_id=1;
10 | 0
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Quantity 10, version 0.
Why this result follows: One transaction keeps the reservation and its dependent order from partially committing.
14. Operation key
Problem: What prevents two stored records for the same synthetic operation identifier?
- The first row already uses operation_id op-7.
- The primary key rejects another row with that same operation identity.
CREATE TABLE lab_operation (operation_id VARCHAR(40) PRIMARY KEY, product_id INT NOT NULL) ENGINE=InnoDB;
INSERT INTO lab_operation VALUES ('op-7',1);
INSERT INTO lab_operation VALUES ('op-7',1);
Second insert rejected: duplicate operation_id.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: The second insert is rejected.
Why this result follows: A unique operation key supplies a durable identity for reconciliation and deduplication.
15. Unknown commit
Problem: What should happen after a connection drops while committing operation op-7?
- The missing response does not establish whether the server committed.
- An authorized lookup of the stable operation id can reveal a recorded outcome.
-- Synthetic timeline: submit op-7; connection drops during COMMIT.
SELECT operation_id, product_id FROM lab_operation WHERE operation_id = 'op-7';
Reconcile the authoritative operation record before retrying.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Check op-7 before deciding whether to retry.
Why this result follows: A durable request identity distinguishes uncertain completion from a new business request.
16. Version not operation
Problem: Can an identical business request be applied again after rereading a newer version?
- The new version predicate matches the current row and stock is sufficient.
- Without an operation-id check the repeated business request can be applied a second time.
-- Current row after op-7: quantity 7, version 1.
-- A retry without checking op-7 uses the fresh version.
UPDATE lab_stock SET quantity=quantity-3, version=version+1 WHERE product_id=1 AND version=1 AND quantity>=3;
If executed, quantity becomes 4 and version 2.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: A fresh token alone does not deduplicate op-7.
Why this result follows: Version conflict detection and request idempotency protect different invariants. This follows the stated row state and guarded condition.
17. Unguarded writer
Problem: What happens if another writer changes quantity but does not increment version?
- The unguarded writer leaves the expected token at zero despite changing the row.
- The guarded update still matches and subtracts three from current quantity nine.
-- Initial state 10/0. Another writer sets quantity to 9 but leaves version 0.
UPDATE lab_stock SET quantity=quantity-3, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=3;
6 | 1
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Quantity 6, version 1; the intervening change was not detected.
Why this result follows: All participating writers must maintain the version token for stale-state detection. This follows the stated row state and guarded condition.
18. Current state diagnosis
Problem: What can an authorized follow-up read reveal after a zero-row update?
- A zero result alone could reflect missing id, stale version or insufficient quantity.
- The subsequent read can narrow the cause but another writer may change state again.
-- Synthetic follow-up after a zero-row write.
SELECT quantity, version FROM lab_stock WHERE product_id = 1;
The current row may reveal version and quantity; it is a later observation.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Inspect current state without claiming the original cause is permanently proven.
Why this result follows: A later read supplies diagnostic evidence rather than an atomic explanation of the earlier failure.
19. Distinct operations
Problem: Can two different operation ids reserve sequentially against fresh versions?
- The first valid operation changes 10/0 to 7/1.
- The second distinct request revalidates and changes 7/1 to 5/2.
-- Start 10/0. op-A reserves 3 with expected version 0 and commits.
-- op-B rereads 7/1, reserves 2 with expected version 1 and commits.
Final quantity 5, version 2; two distinct operation records.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: Both succeed in order, producing 5/2.
Why this result follows: Fresh versions allow separate authorized operations while unique ids distinguish their identities.
20. Driver row count
Problem: Why does the successful fixture update avoid an unchanged-value ambiguity?
- The matching row changes both quantity from 10 to 7 and version from 0 to 1.
- A successful match therefore changes the row, though application drivers must still document their reporting contract.
UPDATE lab_stock SET quantity=quantity-3, version=version+1 WHERE product_id=1 AND version=0 AND quantity>=3;
SELECT ROW_COUNT() AS affected;
1 in the stated successful MySQL SQL scenario.
Illustrative MySQL 8.4 InnoDB SQL or labeled synthetic schedule; results are reasoned and not executed locally.
Expected result: One row is changed.
Why this result follows: Incrementing the version makes a successful guarded update a real row change in this example.
Common errors and fixes
The second writer overwrites the first change.
- Why it happens
- It writes a stale calculated value without checking the observed version.
- How to fix it
- Use an atomic update guarded by the expected version and business condition.
- Prevent it next time
- Test two clients reading the same version.
A zero-row update is reported as a successful reservation.
- Why it happens
- The application ignores the driver’s affected-row result.
- How to fix it
- Interpret the documented result and investigate the failed predicate when needed.
- Prevent it next time
- Test missing, stale, and insufficient-stock paths.
A timeout causes a duplicate reservation.
- Why it happens
- The client assumes the first request did not commit and retries without an identity.
- How to fix it
- Reconcile using a stable operation identifier before another attempt.
- Prevent it next time
- Design and test idempotent request handling.
20 practice exercises
1. What happens when the shown guarded update runs twice from the fixture?
Show hint
Track both the quantity and version after the first write.
Show worked solution
The first successful update changes quantity from 10 to 7 and version from 0 to 1. The second version-zero predicate matches no row, so it cannot subtract three again.
The first update changes 10/0 to 7/1. Repeating the version-0 predicate matches no row, so quantity remains 7 and the version remains 1. The application must inspect the write result rather than count both statements as successful reservations.
Check your solution
- First write produces quantity 7 and version 1.
- Second version-0 write changes zero rows.
2. Does a zero-row result prove that stock was insufficient?
Show hint
List every predicate that can fail before assigning a cause.
Show worked solution
No. The row might be missing or its version might have changed, as well as having insufficient quantity. Use an authorized follow-up read if the application must report the specific reason.
Zero rows can mean that product 1 is missing, its version is no longer 0, or its quantity is below the requested amount. An authorized follow-up read may help explain the current state, but it is a later observation and can race with another writer.
Check your solution
- Include missing, stale and insufficient cases.
- Do not equate zero rows with insufficient stock alone.
3. From quantity 10 and version 0, reserve four units with a guard. Predict quantity and version.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Use a single update requiring product_id 1, version 0 and quantity >= 4, then subtract four and increment version. The matching row becomes quantity 6 and version 1. Validate that four is positive and inspect the driver’s affected-row result immediately.
Check your solution
- Quantity becomes 6
- Version becomes 1
4. After a successful update leaves 6/1, repeat a request expecting version 0. Predict the outcome.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The expected version 0 no longer matches the current version 1, so the update changes zero rows and leaves quantity 6/version 1. The application should report or diagnose a conflict rather than claim a second reservation. A later read can provide current state.
Check your solution
- Zero rows changed
- State remains 6/1
5. Quantity is 6 and version 1. A fresh request for seven units uses version 1. Predict the result.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The version matches but quantity >= 7 is false, so no row changes and the state remains 6/1. This is insufficient stock in the stated scenario. The application must not record a successful seven-unit reservation from the completed SQL statement alone.
Check your solution
- No row changes
- Quantity remains 6
6. Two clients read version 0; A reserves three and commits before B requests four with version 0. Trace both outcomes.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
A changes 10/0 to 7/1. B’s version-zero condition is then stale, so it changes zero rows even though seven units would otherwise cover four. B may reread and revalidate under a bounded retry policy, but must not silently overwrite A’s work.
Check your solution
- A produces 7/1
- B changes zero rows
7. After that conflict B rereads 7/1 and requests four units as a distinct operation. Predict the new state.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The fresh version and quantity guards both match, so the update leaves quantity 3 and increments version to 2. This is a new validated decision based on current state. Record a distinct operation identifier and related reservation atomically if the business requires both.
Check your solution
- Quantity 3
- Version 2
8. A zero-row guarded update occurs. Name three possible causes that require different business responses.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The product may be absent, its version may be stale, or its quantity may be insufficient; another predicate can fail too. Zero alone does not identify which cause occurred. An authorized follow-up read can provide current diagnostic evidence if a precise response is needed.
Check your solution
- Missing product
- Stale version or insufficient stock
9. A request asks to reserve minus two units. Explain why the nonnegative stock check does not suffice.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Subtracting minus two increases stock, so a nonnegative stored-quantity check can still pass while the operation is invalid. Reject nonpositive quantities before issuing the guarded update. Keep the database check as a separate backstop for negative stored results.
Check your solution
- Reject negative request
- CHECK can still pass
10. A request asks for zero units. Explain why version increment makes the write misleading.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The quantity would remain unchanged, but version = version + 1 would still change the row and could be reported as a successful update. A zero-unit reservation is not meaningful under a positive-quantity rule. Validate and reject it before sending SQL.
Check your solution
- Reject zero quantity
- Version would otherwise increment
11. A guarded deduction succeeds but inserting its reservation record fails in the same transaction. What should happen?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Roll back the complete transaction so the quantity and version return to their prior values and no successful reservation is reported. A failed statement does not necessarily undo earlier statements automatically. Verify both stock and operation record after the rollback in a disposable lab.
Check your solution
- Roll back deduction and version
- No successful operation record
12. Explain why every writer must increment the version when changing the protected inventory state.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
If a writer changes quantity but leaves the token unchanged, another client holding the old token can still match and fail to notice the intervening state change. Enforce a consistent write path or equivalent database rule for all participating writers and audit exceptions.
Check your solution
- Unchanged token hides a change
- All writers maintain the token
13. A client times out during COMMIT for operation op-9. What should it do before resending?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Treat the outcome as uncertain because the server may have committed despite the missing response. Reconnect and look up the durable unique operation id op-9 through an authorized path. Reconcile any existing result before deciding whether a safe retry is needed.
Check your solution
- Commit may have succeeded
- Look up op-9 first
14. A client repeats the same business operation with a fresh version but no operation key. Explain the risk.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
A fresh version can match current stock and allow a second deduction, even though the caller intended only one reservation. A version protects against stale state, not duplicate request identity. Record a stable unique operation id with the reservation in the same business transaction.
Check your solution
- Fresh version can deduct again
- Use a unique operation id
15. A driver can report matched or changed rows differently. Why does the application need its documented contract?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The application uses the reported count to distinguish a successful guarded change from a nonmatch, so it must know what the connector and configuration count. This example increments version on success, making a match a change, but verify behavior with the deployed driver.
Check your solution
- Understand matched versus changed
- Test the deployed driver
16. A later read shows version 4 after a version-2 update failed. What can and cannot be concluded?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The current version is newer than the expected version 2, so a stale token is consistent with the failure. The read occurred later and cannot by itself prove the exact original cause if other conditions or writers also changed. Treat it as diagnostic evidence.
Check your solution
- Current version is 4
- Later read is not an atomic explanation
17. Choose a bounded retry policy after a version conflict and describe what each attempt must refresh.
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Set a maximum attempt count and deadline, then reread current quantity and version and revalidate the positive requested amount and business authorization in each new attempt. Stop if stock is insufficient or the bound expires. Preserve the same operation identity for the same business request.
Check your solution
- Refresh quantity and version
- Enforce deadline and operation identity
18. Two different operation ids reserve three and two units from 10. What final state follows successful sequential writes?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The first guarded write changes quantity/version from 10/0 to 7/1. The second rereads that state and changes it to 5/2. Both operations need their own durable unique records and should commit their related reservation data atomically with the stock changes.
Check your solution
- Final quantity 5
- Final version 2
19. A stock update commits but an external confirmation is sent twice. Why does the version guard not solve this?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
The version guard controls changes to the inventory row; it does not guarantee exactly-once external message delivery. Coordinate messages with durable transaction state using an appropriate outbox or equivalent and make consumers idempotent. Track the operation identity across retries.
Check your solution
- Version protects inventory state
- Deduplicate external delivery separately
20. A client preview reads quantity 10/version 0, then another writer commits before its UPDATE. What must protect the write?
Show hint
Trace identity, expected version, quantity guard and operation outcome.
Show worked solution
Include the observed version and required quantity in the UPDATE predicate itself, then check its affected-row result. The earlier read did not lock or guarantee the row’s state. If the token no longer matches, reread and revalidate or report a conflict under a bounded policy.
Check your solution
- Guard version and quantity in UPDATE
- Preview is not a lock
Key takeaways
- A version guard detects an update based on stale state.
- Check the driver’s write result and handle each failed condition.
- Use operation identity and reconciliation for uncertain outcomes.
- A version token detects changes only when all relevant writers maintain it.
- Zero affected rows do not uniquely identify a failed predicate.
- Reconcile uncertain outcomes with a durable operation identity before retrying.