SQL Server / Intermediate / Lesson 14
Detect stale writes with rowversion
Guard a synthetic inventory update with the version observed by the caller.
On this page
Lesson goals
- Explain rowversion as a change token rather than a clock.
- Use an expected version and business predicate in an update.
- Handle no match and uncertain outcomes deliberately.
- Use key-and-rowversion predicates to detect stale SQL Server writes.
- Interpret zero-row outcomes and coordinate conflict handling with transaction and authorization rules.
Identify a stale update
Two clients can read the same quantity and later attempt conflicting changes. A rowversion column is an automatically generated binary change token, not a date or time. A caller can send the token it observed with an update and require it to match the current row. The update should also include the business condition, such as sufficient quantity, rather than relying on the token alone.
Create a disposable row
The following T-SQL is illustrative for a new disposable SQL Server 2019 lab. It creates one synthetic inventory row and reads its generated token. The token value depends on the database and is not predicted here. Do not run this example against a configured application database. A nonnegative check is a useful constraint but does not itself provide an idempotent reservation workflow.
CREATE TABLE dbo.lab_stock (id int PRIMARY KEY, quantity int NOT NULL CHECK (quantity >= 0), rv rowversion);
INSERT INTO dbo.lab_stock (id, quantity) VALUES (1, 10);
SELECT id, quantity, rv FROM dbo.lab_stock WHERE id = 1;
The initial quantity is ten. SQL Server generates rv; it is not a timestamp to interpret as a clock. The public lesson does not execute the statements or assert a token value.
Apply a guarded update
The example captures the current token in a variable and uses it in a conditional UPDATE. In a real client, the expected token must be the value previously read by that caller, passed as a typed parameter. The batch also requires at least three units. OUTPUT illustrates affected-row information, but the client must still respect transaction outcome and the documented handling of errors.
DECLARE @expected binary(8) = (SELECT rv FROM dbo.lab_stock WHERE id = 1);
UPDATE dbo.lab_stock
SET quantity = quantity - 3
OUTPUT inserted.id, inserted.quantity, inserted.rv
WHERE id = 1 AND rv = @expected AND quantity >= 3;
If no other writer changes the fixture between the read and update, quantity becomes seven and a new token is returned. The token and actual outcome are environment-dependent. Keep the DECLARE and UPDATE in the same batch.
Interpret a missing match
No matching row can mean the product is absent, the token is stale, or the quantity is insufficient. Use an authorized follow-up read if the application must distinguish those cases; do not overwrite a newer state automatically. A version guard detects concurrent changes but does not identify repeated business requests. Stable operation identity and a separate reconciliation policy are needed for uncertain retries.
Test two clients and a lost response
In an isolated lab, let two clients read the same token and then attempt the guarded update. Verify that only one can update using that original token and that the quantity invariant remains true. Separately simulate a response lost after submission and reconcile before retrying. Test transaction rollback and external side effects as distinct boundaries; OUTPUT alone is not proof that a transaction later committed.
Define the optimistic update contract
An optimistic update lets a client read a row and its version token, then attempt a write only if the row has not changed in the meantime. In SQL Server, a rowversion column supplies an automatically generated binary change token; it is not a wall-clock date or time. The client must return the exact token it read along with the row key. A WHERE clause matching both key and old token detects an intervening update when the token no longer matches.
Define the business operation and any additional conditions, such as positive quantity and sufficient stock, separately from the version check. A successful one-row update is evidence that the predicates matched for that statement, not by itself proof that an enclosing transaction committed. The examples are synthetic T-SQL scenarios with reasoned outcomes; no SQL Server instance or application data was accessed.
Treat the token as opaque binary data
A rowversion value is generated by the database and should be treated as an opaque binary token. Do not parse it as a date, calculate elapsed time from it or assume contiguous values identify consecutive business events. A row can receive a new token when it is updated even if a column is assigned its existing value. If the application needs an update timestamp, store a separate date/time value with a documented time convention.
A client representation such as a hexadecimal string or encoded value must round-trip the exact bytes without truncation or conversion errors. Test the actual provider parameter type and serialization path. A token is not an authorization secret: possession of it does not grant access to the row. Enforce user and tenant scope independently in the same operation or a reviewed security boundary.
Interpret zero affected rows carefully
A stale token is one possible reason a guarded update affects zero rows. The row may also have been deleted, the key may be wrong, tenant scope may exclude it or a stock condition may be false. A zero count alone does not establish which reason occurred. Apply the API’s documented conflict or not-found policy, and use an authorized follow-up read if distinguishing cases is required. That read is another observation and can race with further changes.
Do not respond to a conflict by removing the token predicate and blindly overwriting the newer row. Reload and present a conflict, merge permitted fields under an explicit policy or ask the user to retry with fresh data. Capture @@ROWCOUNT immediately or use an appropriate OUTPUT result, accounting for the driver and trigger behavior. Preserve the other writer’s update and the complete business invariant.
Coordinate the whole operation and result
When an optimistic write is part of a larger order or transfer, treat it as one transaction with a clear owner. A zero-row required update must lead to the documented failure path rather than a partial commit of related records. OUTPUT can return the newly generated token for the changed row, subject to SQL Server’s documented restrictions, but a returned row is not proof that the surrounding transaction ultimately committed. Return durable success only after the transaction outcome is known.
A connection failure during COMMIT can leave the client unsure whether the write succeeded. Preserve a stable request identity and reconcile the durable result before retrying; a new request key can duplicate a business effect. Rowversion detects changes to a row but is not an idempotency key, a business timestamp or a substitute for constraints and authorization. External effects need their own durable handoff or idempotent processing.
Rehearse competing writers and boundaries
Test a two-client schedule: A reads token v1, B updates the row and receives v2, then A attempts an update using v1. Predict zero affected rows for A, verify that B’s value remains intact, and exercise the conflict response. Also test an unchanged current token, a deleted row, an insufficient quantity and a caller outside the authorized tenant. Use an isolated fixture and record the actual SQL Server version and client binding types.
Test a same-value update as well: the token can change even when the assigned business value appears unchanged. Verify that the client preserves the exact returned bytes and obtains the new token only after a successful committed write. Compare expected keys, values, row counts and transaction state; a green response or one aggregate does not prove that the intended row was protected. These examples do not access production or learner data.
20 worked examples
1. Read key and token
Problem: What does the client need for an optimistic update?
- The key identifies the intended product row.
- The token records the version read by the client.
SELECT ProductId,Stock,VersionToken FROM dbo.LabProduct WHERE ProductId=7;
-- Synthetic result: 7 | 5 | v1.
The key 7 and exact token v1, along with the observed stock.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Matching both on the later write detects an intervening update.
2. Current token
Problem: What happens when the token still matches?
- The key identifies the row and v1 is still current.
- The update subtracts one from the stated stock.
-- Product 7 has Stock=5 and VersionToken=v1; no intervening write.
UPDATE dbo.LabProduct SET Stock=Stock-1 WHERE ProductId=7 AND VersionToken=@v1;
One row can change to stock 4, subject to transaction outcome.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: A matching token permits the guarded write to attempt the update.
3. Stale token
Problem: What happens after another writer changes the token?
- The row still has key seven.
- Its current token v2 does not match A’s old v1.
-- A reads product 7 at v1.
-- B updates it and commits; current token becomes v2.
-- A updates WHERE ProductId=7 AND VersionToken=@v1.
A affects zero rows.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: The token predicate detects the intervening update.
4. Preserve newer value
Problem: What should A do after its stale update fails?
- B’s committed value is newer than A’s observation.
- A’s old-token predicate correctly prevents its write.
-- A read Stock=5 at v1.
-- B commits Stock=4 with token v2.
-- A update using v1 affects 0 rows.
Return or resolve a conflict without overwriting B’s stock.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: An unconditional retry would discard the protection the token provides.
5. Deleted row
Problem: Why can a token update affect zero rows after deletion?
- The key no longer identifies an existing row.
- No row can satisfy both key and token predicates.
-- A reads product 7 at v1.
-- B deletes product 7 and commits.
-- A updates WHERE ProductId=7 AND VersionToken=@v1.
Zero rows because product 7 is absent.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: A zero count does not by itself prove a competing update.
6. Insufficient stock
Problem: Why can a current token still produce zero rows?
- The version token matches in the fixture.
- The independent sufficient-stock predicate is false.
-- Product 7 has Stock=2 and current token v1.
UPDATE dbo.LabProduct SET Stock=Stock-4 WHERE ProductId=7 AND VersionToken=@v1 AND Stock>=4;
Zero rows; stock remains 2.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: All write predicates must match for the reservation to succeed.
7. Wrong key
Problem: What does an incorrect key do even with a copied token?
- The requested key eight is absent.
- The token belongs to product seven instead.
-- Product 7 has token v1; no product 8 exists.
UPDATE dbo.LabProduct SET Stock=Stock-1 WHERE ProductId=8 AND VersionToken=@v1;
Zero rows
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: The row key and token jointly identify the intended version.
8. Tenant scope
Problem: Why is a token not an authorization credential?
- The token identifies a row version, not user membership.
- The requested row lies outside the trusted tenant scope.
-- Caller is authorized for tenant A.
-- Product 7 belongs to tenant B; caller presents its token v1.
Deny the cross-tenant operation under the security contract.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Authorization must be enforced independently of optimistic concurrency.
9. Same-value update
Problem: Can assigning the existing value change rowversion?
- The row is updated by the successful statement.
- The assigned business value happens to equal its prior value.
-- Product 7 has Price=10 and token v1.
UPDATE dbo.LabProduct SET Price=10 WHERE ProductId=7;
-- Statement succeeds.
The rowversion changes despite the same Price value.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: The token records an update rather than proving a particular field changed.
10. Token is not time
Problem: What does this binary token tell the client?
- The rowversion value is an automatically generated binary number.
- It does not encode the stated date or time of an update.
-- VersionToken = 0x00000000000007D3.
-- No timestamp column is supplied.
It is a change token, not a wall-clock timestamp.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Store a separate date/time when the business needs a time value.
11. Exact byte round-trip
Problem: Why preserve every byte of a token?
- The optimistic predicate compares the stored token with the returned value.
- Truncation changes the represented bytes.
-- Client reads binary token v1.
-- Serialization truncates the token before sending it back.
The returned value is not the exact token and cannot reliably match.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Token serialization and parameter binding must preserve the exact value.
12. Immediate count
Problem: When should the update result be captured?
- The UPDATE establishes the row-count state.
- Later statements can replace that diagnostic value.
UPDATE dbo.LabProduct SET Price=@price WHERE ProductId=@id AND VersionToken=@oldToken;
DECLARE @changed int=@@ROWCOUNT;
Capture @@ROWCOUNT immediately after the update.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: An immediate capture associates the count with the intended guarded write.
13. Output new token
Problem: How can an updated token be returned?
- The guarded predicate selects the intended version.
- The inserted logical row exposes post-update values.
UPDATE dbo.LabProduct SET Price=@price
OUTPUT inserted.ProductId,inserted.VersionToken
WHERE ProductId=@id AND VersionToken=@oldToken;
The output can contain the updated row’s key and new token, subject to restrictions.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: OUTPUT can return the next token but must be used under its documented conditions.
14. Output then rollback
Problem: Does a returned token prove durable success?
- OUTPUT is produced during the statement.
- The later rollback undoes the transactional update.
-- Product 7 initially has token v1.
BEGIN TRANSACTION;
UPDATE dbo.LabProduct SET Price=11 OUTPUT inserted.VersionToken WHERE ProductId=7 AND VersionToken=@v1;
ROLLBACK;
The transaction rolls back despite a returned OUTPUT row.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: The final transaction outcome determines durable business success.
15. Required multi-step operation
Problem: What if a guarded update fails after another required write?
- The stock update did not satisfy the required condition.
- The owner ends the complete business transaction with rollback.
-- One transaction inserts an order and attempts a required stock update.
-- Stock update affects zero rows.
-- Owner rolls back.
The order insert is rolled back with the failed attempt.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: A zero-row required write must not leave a partial order committed.
16. Fresh token retry
Problem: How can a user retry after resolving a conflict?
- The client has explicitly reloaded and reviewed the newer value.
- A further concurrent change could still make v2 stale.
-- A’s v1 update fails; authorized reload returns value 4 and token v2.
-- User reviews the change and submits a new guarded update with v2.
The new attempt uses v2 and succeeds only if all predicates still match.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Conflict resolution requires a new checked attempt, not an unconditional overwrite.
17. Additional business guard
Problem: Why include a stock condition as well as rowversion?
- The token condition holds in the fixture.
- The quantity condition fails because two is less than four.
-- Product 7 has token v1 and Stock=2.
UPDATE dbo.LabProduct SET Stock=Stock-4 WHERE ProductId=7 AND VersionToken=@v1 AND Stock>=4;
Zero rows despite a current token.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Version matching and business validity are independent requirements.
18. Two rows
Problem: Which row does a key-and-token predicate target?
- The key restricts the target to product seven.
- The old token also matches that row in the scenario.
-- Product 7: token v1. Product 8: token v2.
UPDATE dbo.LabProduct SET Price=11 WHERE ProductId=7 AND VersionToken=@v1;
Only product 7 can match under the stated fixture.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Verify the affected key as well as the count.
19. No blind overwrite
Problem: Why is this fallback unsafe?
- The fallback removes the stale-token condition.
- It can match the row regardless of B’s intervening change.
-- A’s update using v1 affects zero rows after B commits v2.
-- Proposed fallback: UPDATE dbo.LabProduct SET Price=@price WHERE ProductId=7.
The fallback can overwrite B’s newer value.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Removing the guard discards the conflict detection mechanism.
20. Ambiguous commit
Problem: What if the client disconnects during COMMIT?
- The client cannot know from the lost response whether commit succeeded.
- A new request key may duplicate a committed effect.
-- Request key req-7 was submitted with token v1.
-- Connection drops before the commit response.
Reconcile req-7 before retrying the business operation.
This synthetic schedule and outcome are reasoned; SQL Server was not accessed.
Why this result follows: Rowversion and request idempotency solve different problems.
Common errors and fixes
A stale writer overwrites a newer quantity.
- Why it happens
- The update did not check the previously observed rowversion.
- How to fix it
- Use a typed expected token in the guarded predicate.
- Prevent it next time
- Test two clients reading the same version.
A zero-row result is reported as a successful reservation.
- Why it happens
- The application ignores the update outcome.
- How to fix it
- Handle no match and investigate the failed condition when needed.
- Prevent it next time
- Test missing, stale, and insufficient-stock paths.
A timeout leads to a duplicate business action.
- Why it happens
- The caller retries without reconciling an uncertain prior outcome.
- How to fix it
- Use a stable operation identity and check authoritative state.
- Prevent it next time
- Test lost responses and idempotency.
20 practice exercises
1. Is rowversion a timestamp showing when the row changed?
Show hint
Distinguish a binary change token from a date/time value.
Show worked solution
No. It is an automatically generated binary change token; it does not record a wall-clock date or time.
rowversion is an automatically generated binary change token, not a wall-clock timestamp. Store and document a separate date/time value if the application needs to know when a row changed.
Check your solution
- rowversion is not a date or time.
- A separate time field is needed for wall-clock information.
2. Why can an update with the old token match no rows?
Show hint
List all predicates that can make the update match no row.
Show worked solution
Another update may have changed the token, the row may be absent, or the quantity condition may be false. An authorized read can help distinguish the cases.
A stale token, deleted row, wrong key or false quantity condition can each lead to zero affected rows. Follow the API conflict or not-found contract and use an authorized read if the cases must be distinguished.
Check your solution
- A changed token is one possible cause.
- Deletion or a false quantity condition can also cause zero rows.
3. A reads product 7 with token v1; B updates it to v2. What does A’s update using v1 affect?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
It affects zero rows in the stated sequence because v1 no longer matches the current token. Return a conflict or reload and reconcile under the API contract rather than overwriting B’s work.
Check your solution
- A changes zero rows
- Preserve B’s newer value
4. A reads token v1 and no other update occurs. Can a key-and-v1 update match?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Yes, it can match the stated row if all other conditions also hold. Check the affected row and final commit; a token match does not guarantee every business precondition.
Check your solution
- The current token can match
- Verify other predicates and commit
5. An optimistic update affects zero rows after the row was deleted. Is a concurrent update the only explanation?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. Deletion leaves no row matching the key, which also yields zero. A wrong key or failed quantity condition can do the same; follow the documented conflict or not-found policy.
Check your solution
- Deletion can yield zero rows
- Interpret other predicates too
6. A token matches but stock is 2 and the request is 4. What does a Stock>=4 guard do?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
It prevents the update because the independent stock predicate is false, leaving stock two. The current token does not prove sufficient stock or make an invalid reservation safe.
Check your solution
- The update affects zero rows
- Stock remains 2
7. Is a SQL Server rowversion value a wall-clock timestamp recording the update time?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. It is an automatically generated binary change token and does not record the date or time of the update. Store a separate date/time field with an agreed convention if that information is needed.
Check your solution
- Token is not a time value
- Use a separate timestamp field
8. A successful UPDATE sets Price to its existing value. Can rowversion change?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Yes. SQL Server can generate a new rowversion for an update even if the assigned value is unchanged. The token marks an update, not proof that a specific business value differs.
Check your solution
- Token can change
- Same price does not imply same token
9. Why must the client preserve the exact rowversion bytes?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
The later predicate compares the old token with the stored binary value. Truncation or an incorrect serialization can produce a different token and a false conflict; test the provider binding and round trip.
Check your solution
- Preserve the complete binary value
- Test serialization and binding
10. Does possession of a rowversion token authorize access to a tenant’s product?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. The token is a concurrency marker, not an authorization credential. Enforce trusted tenant and user scope independently, even when the supplied key and token are valid.
Check your solution
- Token does not grant access
- Enforce tenant authorization
11. An UPDATE OUTPUT returns a new token, then the transaction rolls back. Is success durable?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. OUTPUT can return statement values before the outer transaction outcome, and a rollback can undo the update. Confirm final commit before reporting a durable business result.
Check your solution
- OUTPUT alone does not prove commit
- Rollback undoes the update
12. An order insert succeeds but its required optimistic stock update affects zero rows. What should the owner do?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Treat the failed stock condition as a business failure and roll back the complete transaction, including the order insert. Do not commit a partial order that has no corresponding reservation.
Check your solution
- Roll back the order insert
- Do not commit a partial reservation
13. A stale update fails, then the client reloads token v2. Is an unconditional update now safe?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. Another writer can change the row again after the reload. Review or merge according to policy and submit a new update guarded by v2 and the other required predicates.
Check your solution
- Use the fresh token as a guard
- Another change can occur after reload
14. Why capture @@ROWCOUNT immediately after the guarded update?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
A later statement can replace the session row-count value. Capture it immediately or use an appropriate OUTPUT result, then interpret zero according to the documented conflict and not-found policy.
Check your solution
- Capture the intended update count
- Interpret zero rather than assuming success
15. A user has key 7 and old token v1. What two conditions should the optimistic predicate include?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Match ProductId=7 and VersionToken=v1, along with any required tenant and business conditions. The key selects the entity and the token verifies that its observed version is still current.
Check your solution
- Match the intended key
- Match the exact observed token
16. A stale update affects zero rows. Why should the application not remove the token and retry?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Removing the predicate can overwrite a newer committed change, defeating conflict detection. Return a conflict or reload and reconcile the user’s intended change under an explicit policy.
Check your solution
- Do not overwrite the newer value
- Use a documented conflict policy
17. A client disconnects during COMMIT of request req-7. What should be done before retry?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Retain req-7 and reconcile its durable result because the commit outcome is uncertain. A new request identity can create a duplicate effect even though rowversion guarded the first write.
Check your solution
- Commit outcome is uncertain
- Reconcile the same request key
18. Does rowversion enforce a unique external request key?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
No. Rowversion tracks row updates, while a request key identifies a logical operation. Use an appropriate unique constraint and duplicate-payload policy separately when idempotent requests are required.
Check your solution
- Token is not a request key
- Enforce request uniqueness separately
19. A token is current but a tenant predicate fails. What should the result reveal to an unauthorized caller?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Follow the API’s security and conflict policy without exposing another tenant’s data. The authorization predicate can yield zero rows even with a valid token; do not use the token to bypass tenant scope.
Check your solution
- Tenant scope remains enforced
- Avoid leaking unauthorized row details
20. Design a two-client stale-write test with A and B. What outcomes should be verified?
Show hint
Trace the key, exact token, other predicates and final transaction outcome.
Show worked solution
Have A read v1, let B update and commit v2, then attempt A’s guarded write with v1. Verify A affects zero rows and B’s committed value remains intact, followed by the intended conflict response.
Check your solution
- A’s old-token write affects zero
- B’s value remains intact
Key takeaways
- rowversion is a change token, not a clock.
- Guard the write with the observed token and business condition.
- Reconcile uncertain outcomes and transaction state separately.
- rowversion is an opaque binary change token, not a wall-clock time.
- A zero-row guarded update can have multiple causes.
- Never discard the token guard to overwrite a newer change blindly.