Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Implement Compare-and-Swap for Safe Client Status Updates

Use an observed ETag or row version as a write precondition so stale client status updates fail safely instead of overwriting newer changes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To prevent one client from silently overwriting another client’s status change, make each write conditional on the version the client last read. In an HTTP API, return an ETag and require it in an If-Match header; in a database, update the row only when its version still equals the client’s expected version. Compare and mutation must happen together on the server. If the comparison fails, reject the write as a conflict rather than applying stale data.

What compare-and-swap prevents

A lost update occurs when two clients read the same earlier state, then each submits a change. Without a concurrency check, the later write can overwrite newer work—even if that client never saw it. Compare-and-swap (CAS) makes a write conditional: apply the requested change only if the resource is still at the version the client observed.

As an Amazon Associate I earn from qualifying purchases.

The client’s version is an expectation, not authority. The server remains responsible for current state, authorization, validation, and whether the requested status transition is allowed. CAS detects stale writes; it does not enforce business rules such as whether pending may transition to approved.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Implement CAS in an HTTP API with ETags

Read the status and its validator

When the client fetches a status resource, return its representation with an ETag that changes whenever the relevant representation changes. For example:

GET /items/42
HTTP/1.1 200 OK
ETag: "v17"
Content-Type: application/json

{"status":"pending"}

An ETag is useful as a validator only if the server’s generation and comparison rules reliably reflect changes relevant to the update. Treat it as opaque on the client: store the value and send it back rather than deriving or editing it.

Require the observed ETag on the write

For a state-changing request, send the ETag from the read in If-Match:

PATCH /items/42
If-Match: "v17"
Content-Type: application/json

{"status":"approved"}

RFC 9110 specifies strong comparison for If-Match and requires the condition to be evaluated before performing the method. Do not use a weak ETag for this concurrency check. If the current selected representation no longer matches, the server must not perform the requested method; 412 Precondition Failed is the standard response for a failed precondition. See RFC 9110, Section 13.1.1.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Return the new validator or report the conflict

On success, return the updated representation and its new ETag so the client can make a later conditional change using the latest version. If another write changed the resource first, leave the current state unchanged by this request and return the precondition failure. You may include current state when appropriate, or require the client to fetch it again.

The client should then refresh and decide what the requested change means against current state. It may present the conflict, merge or recompute an intent-based change, or retry a bounded number of times if recomputation is safe. It should not blindly resend a stale whole-resource replacement.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Implement CAS for a database record

For a versioned row, make the version comparison and mutation part of one atomic conditional write. Generic SQL pseudocode:

UPDATE items
SET status = :new_status,
    version = version + 1
WHERE id = :id
  AND version = :expected_version;

Inspect the affected-row count. One affected row means the expected version matched and the update was applied. Zero means either the record does not exist or its version changed; handle the stale-version case as a conflict, distinguishing a missing record if your API’s information-disclosure policy calls for it. Exact syntax and transaction behavior vary by database.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A check performed in application memory followed by a separate unconditional update is not CAS: another write can slip between the check and mutation. Keep the comparison and change indivisible in a conditional write or transaction.

Best Value
Sale
Cracking the Coding Interview: 189 Programming Questions and Solutions
  • Careercup, Easy To Read
  • Condition : Good
  • Compact for travelling

DynamoDB version checks

DynamoDB’s documented pattern uses a version attribute and a ConditionExpression, for example requiring Version = :expected_v as part of the write. A mismatch produces ConditionalCheckFailedException. The application can report a conflict, or fetch current state and recompute a safe update. AWS advises limiting retries because each retry adds a read. See Optimistic locking with version number.

Handle conflicts without creating new ones

  • Validate the transition independently. A matching version does not make an otherwise forbidden status transition valid.
  • Separate conflict responses from other errors. Authorization failures, invalid requests, missing resources, and infrastructure failures are not stale-version conflicts.
  • Bound retries. Refresh before retrying and recompute from current state. Do not loop indefinitely under contention.
  • Protect side effects. If a status update triggers non-idempotent work, such as sending a notification or initiating a payment, a failed or repeated write must not accidentally duplicate that work. Design side effects with suitable transactional, outbox, or idempotency safeguards.
  • Choose a clear client recovery path. After a conflict, let the client refresh and then present, merge, or deliberately recompute the change rather than silently overwriting.

Choose the concurrency strategy for the work

Situation Approach Trade-off
Conflicts are infrequent, retries are inexpensive, and one item is being updated Optimistic locking with a version and conditional write Detects a conflict at write time without coordinating a lock in advance. AWS describes optimistic locking as detecting conflicts at write time rather than preventing them: DynamoDB documentation.
Several items must change together Use a database transaction Provides all-or-nothing semantics for the grouped changes.
Long-running critical work or high contention makes retries costly Evaluate locking or another coordination strategy Coordination adds complexity but may be preferable to repeated failed writes.
DynamoDB global tables receive writes in multiple Regions Use explicit application-level conflict handling Global tables reconcile with last-writer-wins, so version-based optimistic locking does not provide the expected cross-region protection. See AWS guidance on concurrent updates.

Implementation checklist

  • Return a validator or version with the state clients read.
  • Require the observed value on every relevant write.
  • Compare and mutate atomically on the server.
  • Advance the version whenever the relevant state changes.
  • Reject mismatches without applying the stale request.
  • Refresh and resolve conflicts deliberately; retry only when bounded and safe.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.