How to Implement Optimistic Concurrency Control with ETags
Use ETags and conditional requests to prevent lost updates in a REST API, returning 304 for reads and 412 for stale writes without locking rows.
On this page
Introduction
Optimistic concurrency control lets two clients edit the same resource without a database lock. Instead of taking a lock for the whole read-modify-write cycle, the server gives the client a version token with the read and requires that same token on the write. If the resource changed in between, the write is rejected and the client decides whether to refetch, merge, or retry. In HTTP the version token is the ETag, and the mechanism is the conditional request: If-None-Match for reads and If-Match for writes.
This tutorial builds an optimistic concurrency layer for a REST API. It covers how ETags are defined, how to generate a validator that is stable across servers, how to answer reads with 304 Not Modified, how to enforce writes with 412 Precondition Failed, how to store the version in the database, and how to test interleaved writes. The examples use TypeScript and a SQL version column, but the pattern applies to any store that can compare a version atomically.
How ETags and conditional requests work
An ETag is an opaque string the server attaches to a response, quoted and optionally marked weak. A strong ETag ("abc") asserts byte-level identity of the representation; a weak ETag (W/"abc") asserts semantic equivalence. For concurrency control you want a strong ETag, because a write must be rejected when the exact state changed, not merely when it changed in a compatible way.
The client stores the ETag from the response and sends it back on the next request. On a GET, If-None-Match: "abc" asks the server to send the body only if the current ETag differs; if it matches, the server replies 304 Not Modified with no body, saving bandwidth. On an update, If-Match: "abc" asks the server to apply the change only if the current ETag still equals "abc"; otherwise the server replies 412 Precondition Failed and the write is not applied. The If-Match check plus the write must happen atomically, or the precondition is checked against one version and applied to another.
// A conditional request handler: read the validator, compare, then act.
function currentEtag(version: number): string {
// Strong ETag derived from the row version, stable across instances.
return `"v${version}"`;
}
function clientEtag(headers: Record<string, string | undefined>): string[] {
const raw = headers['if-match'];
if (!raw) return [];
// If-Match may be a comma-separated list; compare against any of them.
return raw.split(',').map((s) => s.trim()).filter(Boolean);
}
Generate a stable ETag
The validator must be a pure function of the resource state. Three strategies work well. First, a monotonic version column that increments on every write; the ETag is "v<version>". Second, a hash of the canonical serialized representation, for example a SHA-256 of the sorted JSON; the ETag changes exactly when the data changes. Third, a combination of both, where the version is the fast path and the hash guards against a write that failed to bump the version.
Avoid validators that are not reproducible: a per-process counter, a random id, or a timestamp with second granularity. A per-process counter differs between load-balanced instances, so a client that reads from instance A and writes to instance B sees a mismatch it cannot resolve. A second-granularity timestamp misses two writes in the same second, which is exactly the lost-update case you are trying to prevent. The hash must be over a canonical form: sort keys, normalize numbers, and exclude volatile fields such as a lastAccessedAt that changes on every read.
Answer reads with 304
On a GET, compute the current ETag, compare it to If-None-Match, and return 304 Not Modified when they match. The 304 must not include a body, and it should repeat the ETag header so the client can keep caching. Handle the wildcard If-None-Match: * and comma-separated lists, and treat a weak validator on the client side as a match only if your ETag is also weak. Many caching layers and browsers will use 304 automatically, so this path is exercised constantly in production.
function getResource(id: string, ifNoneMatch: string[] | undefined) {
const row = store.find(id);
if (!row) return { status: 404 as const };
const etag = currentEtag(row.version);
if (ifNoneMatch?.includes(etag) || ifNoneMatch?.includes('*')) {
return { status: 304 as const, headers: { ETag: etag } };
}
return { status: 200 as const, headers: { ETag: etag }, body: row.data };
}
Enforce writes with If-Match
An update must require If-Match and compare it inside the same transaction as the write. The safe shape is a single SQL statement that updates the row only where the version matches, and reports how many rows changed; zero rows means the precondition failed.
-- Atomic compare-and-set: update only if the version still matches.
UPDATE documents
SET title = $1, body = $2, version = version + 1, updated_at = now()
WHERE id = $3
AND version = $4; -- the version parsed from If-Match: "v4"
-- Read the affected-row count. 0 -> the client's ETag is stale -> 412.
async function updateDocument(id: string, ifMatch: string[], body: DocInput) {
if (ifMatch.length === 0) {
return { status: 428 as const, message: 'If-Match required' };
}
const expected = parseVersion(ifMatch); // "v4" -> 4
const updated = await db.updateDocument({ id, version: expected, ...body });
if (!updated) {
// 412 without applying the change; the client refetches and retries.
return { status: 412 as const, message: 'precondition failed' };
}
return { status: 200 as const, headers: { ETag: currentEtag(expected + 1) } };
}
Do not fall back to a blind overwrite when If-Match is missing. If the endpoint must tolerate legacy clients, answer a missing precondition with 428 Precondition Required so the client learns to send one, and make the behavior explicit in the API docs. Returning 412 with the current ETag in the body or headers helps the client recover without an extra round trip.
Store the version in the database
The version lives with the row, not in application memory. A version INTEGER column, a xmin system column in PostgreSQL, or a store-native revision gives you a value to compare and increment atomically. In PostgreSQL, xmin is a special case: it changes on every update automatically, so you can read it without a schema change, but it is not guaranteed stable across a VACUUM FREEZE, so a dedicated version column is safer for a public contract.
-- Add a version column and keep it monotonic from zero.
ALTER TABLE documents ADD COLUMN version integer NOT NULL DEFAULT 0;
-- A default value means existing rows read as version 0 on the first request.
Whatever the source, the read that produces the ETag and the write that checks it must observe the same committed state. In a read-committed database, the compare-and-set statement above is sufficient because the AND version = $4 predicate is evaluated under the row lock the update acquires. Never compute the ETag from a cached copy of the row that might be older than the database.
Handle conflicts and retries
When a write returns 412, the client has three honest options: refetch the current version and let the user reapply the edit, merge the two versions field by field, or retry the same change against the fresh version if the fields do not overlap. What the client must not do is overwrite blindly, because that is the lost update the ETag was meant to prevent.
On the server, return the current ETag and, where useful, a diff or a Location to the latest version so the client can recover in one call. Idempotency keys and ETags solve different problems: an idempotency key prevents a duplicate create from a retried request, while an ETag rejects a stale update. Use both when a mutation is retryable and the resource is concurrently edited, and make the error taxonomy clear so a 412 is never confused with a 409 or a 500.
Testing concurrency
Test the interleaving directly. Read a resource, capture its ETag, update it once (bumping the version), then attempt the second update with the stale ETag and assert 412 and that the stored value did not change. Repeat with many clients in parallel and assert that exactly one update per version succeeds.
test('rejects the second writer with a stale ETag', async () => {
const created = await api.create({ title: 'a', body: 'x' });
const first = await api.get(created.id);
const second = await api.get(created.id); // both clients hold the same ETag
expect(first.headers.etag).toBe(second.headers.etag);
const win = await api.update(created.id, { title: 'b', body: 'y' }, first.headers.etag);
expect(win.status).toBe(200);
const lose = await api.update(created.id, { title: 'c', body: 'z' }, second.headers.etag);
expect(lose.status).toBe(412);
const latest = await api.get(created.id);
expect(latest.body.title).toBe('b'); // the second write did not clobber the first
});
Add a 304 test: a GET with the current ETag returns 304 and an empty body. Add an atomicity test with N parallel writers and assert that exactly one succeeds at each version. Run these against the real database, because the atomicity guarantee you are testing lives in the SQL statement, not in application code.
Common pitfalls
- Non-reproducible ETags. Per-process counters and random ids differ across instances and restarts.
- Checking and writing separately. A gap between the check and the write lets a concurrent update slip in.
- Accepting a missing If-Match as a full overwrite. This silently reintroduces lost updates.
- Weak ETags for writes. Weak validators match semantically equivalent but changed states.
- Second-granularity timestamps. Two writes in the same second collapse into one validator.
- Returning 500 for a conflict. A stale precondition is a
412, not a server error. - Caching the ETag in application memory. The validator must come from the committed store state.
Conclusion
Optimistic concurrency control is an ETag plus an atomic compare-and-set. Derive the validator from the resource state so it is stable, answer reads with 304 when the client is current, enforce writes with If-Match and 412 when it is not, and keep the version in the database so the check and the write are one operation. Tell clients how to recover from a conflict, and test interleaved writes against the real store. The result is an API that lets concurrent editors work safely without locks, while making the lost-update failure impossible to hide.
Sources: RFC 9110: HTTP Semantics, MDN: ETag, MDN: Conditional requests.
FAQ
- What is the difference between an ETag and the Last-Modified header?
- An ETag is an opaque validator derived from the resource state and is exact; Last-Modified is a timestamp with one-second granularity and can be wrong when two writes happen in the same second. Prefer ETags for concurrency control and use Last-Modified only as a fallback when no version is available.
- Should every update endpoint require If-Match?
- Yes for any resource where two clients can edit the same fields. If you are not willing to require it, use If-Match when present and treat a missing header explicitly, because silently allowing a full overwrite reintroduces lost updates. A common middle ground answers missing preconditions with 428 Precondition Required.
- Is an ETag deterministic across servers?
- Only if the validator is derived from data, not from a per-process counter or random value. A hash of the canonical resource representation, or a monotonic row version, produces the same ETag on every instance; a cached in-memory counter does not survive a restart or a load balancer.
Report a problem with this articleOpens a pre-filled issue on GitHub.