← Building blocks

Detect conflicting updates

Consistency & coordinationfundamental

Two users edit the same record; the last write silently wins.

Say it like this

Conflicts are rare but must not be silent, so every row carries a version and each update is conditional on the version it read; a zero-row update means someone else won and the client retries.

Basic solution

Store a version; update WHERE version = expected and reject if zero rows changed (compare-and-set).

version columnsETags / If-MatchDynamoDB conditional writesRedis WATCH

Two writers, one version check

Both clients read version 7. The first update matches and bumps the row to 8; the second update finds version 8, changes zero rows, and the client must re-read and retry.

How it works

  1. The client reads the record and receives its current version along with the data: a counter column, an updated_at timestamp, or an ETag header.
  2. It makes its changes locally, holding no lock, so nothing in the database is blocked while the user thinks.
  3. It sends the update together with the version it read: UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?. The WHERE clause is the check; the SET bumps the version for the next writer.
  4. The database reports how many rows changed. One row means the version still matched and the write won. Zero rows means another writer changed the record first, so the version no longer matches and nothing was written.
  5. On a conflict the client re-reads the record to get the new version and data, re-applies its change on top (or shows the user both versions to merge), and retries, giving up after a bounded number of attempts.

Where the version lives

  • A version column in SQL; a ConditionExpression on the stored version in DynamoDB; an ETag header on HTTP resources sent back with If-Match; WATCH on the key followed by MULTI in Redis.

Worked example

Trip state machine in ride matching

  • A trip row moves requested → matched → arriving → in_progress → completed, and can be cancelled from several states.
  • Driver app and rider app both send events, and a late or duplicated event must not corrupt the state, so every transition must check which state it is leaving.
  • Every transition is a conditional update: UPDATE trips SET state = 'arriving', version = 8 WHERE id = ? AND state = 'matched' AND version = 7. If the row is no longer in matched at version 7, zero rows change and the event is rejected.
  • At 200 matches/s each trip sees roughly 6 transitions, ~1,200 conditional updates/s across the fleet, ordinary load for one database. Conflicts: a handful per minute, typically the driver's "arrived" racing the rider's "cancel".
  • A rejected transition returns 409 with the current state so the client can decide: a cancel after arrival is refused with a fee rule, a duplicate "arrived" is a no-op.

Variants and when each wins

Version counter

  • An integer column incremented on every write and checked in the WHERE clause. It is exact and cheap and is the default for application tables.

Timestamp as version

  • The existing updated_at column doubles as the version, so no extra column is needed. It loses when two writes land in the same millisecond, or when clock skew between app servers misorders them, so it wins only for low-write tables.

ETag / If-Match over HTTP

  • The server returns an ETag with each resource; the client sends it back in If-Match on the update; a mismatch is 412 Precondition Failed. It is the same check for REST APIs and wins whenever the client is a browser or a third party.

Conditional writes in key-value stores

  • DynamoDB ConditionExpression, Cassandra lightweight transactions and Redis WATCH all write only if a stored value matches what you expect. They win when there is no relational database to add a WHERE clause to.

Pessimistic locking as the alternative

  • SELECT ... FOR UPDATE holds the row so other writers wait in line instead of failing. It wins when contention is high and optimistic retries would mostly fail.

Use a version counter by default; switch to pessimistic locking when the retry rate on one hot row climbs above a few percent.

Failure modes

Retry storm on a hot row

  • Most updates to one record fail their version check and retry, again and again. It happens because so many writers hit the same row that the version changes between every read and write. Fix it with a pessimistic lock on that row, or by serialising its updates through a single owner or a queue.

Lost update through a stale version

  • A change disappears without any error. It happens because a client cached the version from an earlier read and, after a conflict, retried with the old version and old data; when that eventually matched it overwrote someone else's change. Fix it by always re-reading the record on conflict before retrying.

Version not checked on every path

  • An admin script overwrites edits users made moments ago. It happens because one code path runs an UPDATE without the WHERE version clause. Fix it by enforcing the version check in the data access layer so no update can bypass it.

Timestamp collisions

  • Two writes both succeed and one is silently lost. It happens because updated_at was used as the version and both writes carried the same millisecond. Fix it with an integer counter that changes on every write.

Unbounded retries

  • A request runs for seconds under load, retrying a conflicting update over and over. It happens because the retry loop has no limit. Fix it by capping attempts at three to five and returning 409 so the client decides what to do.

Interviewer follow-ups

Answer out loud before you open each one.

When would you choose pessimistic locking instead?

When the same row is updated so often that optimistic retries mostly fail, such as a single inventory counter during a flash sale. Locking makes writers wait in line instead of repeatedly failing, which wastes less work. The trade is that lock waits add latency and risk deadlocks.

How does this interact with retries from a network timeout?

A timed-out update may have actually committed. On retry, the version check fails because the row moved on, which is the correct outcome: re-read, see your change applied, and stop. Pair it with an idempotency key if the write has side effects outside the database.

What does the client do on a conflict?

Re-read the current record, then either reapply automatically when the change is additive (increment a counter, append to a list) or show the user both versions when the fields overlap. Never blindly resubmit the old payload.

How is this different from a compare-and-swap in Redis?

It is the same primitive at a different layer. CAS compares the stored value or version and writes only if it matches, in one atomic step. Optimistic concurrency does that with a database WHERE clause; WATCH plus MULTI does it in Redis.

Connections

Pairs with
Do read-modify-write atomically · Make retries safe · Retry transient failures carefully
Pulls against
Lock the row before changing it · Make sure only one worker does it
Used in
Ride Matching (Uber / Lyft) · Distributed Key-Value Cache (Redis / Memcached-like)