What is a REST API ETag, and why does it have two jobs?
An ETag is an opaque validator the server attaches to a specific representation of a resource. Clients must not parse it. They store it and send it back in a precondition header, and the server compares it with the ETag of the current representation.
That comparison does two separate jobs:
- Conditional reads (
If-None-Match): if the client's cached copy is still current, the server returns304 Not Modifiedwith no body, which saves bandwidth. - Conditional writes (
If-Match): the server applies a change only if the resource hasn't changed since the client read it. Otherwise it returns412 Precondition Failed, which prevents lost updates.
A stale cache costs one extra download. A lost update silently discards someone's edit. Because the write side protects data, this article designs ETags around writes first. This matters for any API where several clients, users or background jobs edit the same resources.
ETags come in two strengths:
- Strong ETags (
"abc") promise byte-identical representations. - Weak ETags (
W/"abc") promise only semantic equivalence.
Weak comparison is fine for If-None-Match on GET. Serving a semantically equivalent cached copy harms nothing. If-Match requires strong comparison, so a weak ETag never satisfies it. A write must be based on the exact state it replaces, and "equivalent" could hide a real change.
| Header | Typical methods | Comparison | Precondition passes | Precondition fails |
|---|---|---|---|---|
If-None-Match: "tag" |
GET, HEAD | Weak | 200 OK with body |
304 Not Modified |
If-Match: "tag" |
PUT, PATCH, DELETE | Strong | Method runs (200/204) |
412 Precondition Failed |
If-None-Match: * |
PUT (create-only) | Existence check | 201 Created |
412 Precondition Failed |
How does If-Match prevent lost updates with optimistic concurrency?
Two clients read the same order and then both try to change it:
- A sends
GET /orders/42and receives200withETag: "v7". - B sends
GET /orders/42and also receivesETag: "v7". - A sends
PUT /orders/42withIf-Match: "v7". The server returns200withETag: "v8". - B sends
PUT /orders/42withIf-Match: "v7". The server returns412 Precondition Failed.
If step 4 had no precondition, the server would accept B's body and replace A's change without any error. Neither client would find out. This is a lost update. With If-Match, the server compares the client's tag with the current one before it writes. It refuses the request because B edited a version that no longer exists. B then re-fetches, merges or asks the user, and retries with "v8". This approach is called optimistic concurrency because the server holds no locks between the read and the write. It assumes conflicts are rare and detects them only when they happen.
The same rule covers the other methods that change state:
- PATCH: A diff applied to a stale base can corrupt the resource, so the precondition matters as much as it does for PUT.
- DELETE:
If-Matchstops a client from deleting a resource that someone else changed after the client last read it.
If-None-Match: * on PUT works the other way. It means "write only if nothing exists at this URI." If two clients race to create /users/alice, one gets 201 Created and the other gets 412. The second client can no longer replace the first client's resource without noticing.
# Client A writes using the ETag it read earlier ("v7" is still current)
PUT /orders/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "v7"
{"status":"shipped"}
# The tags match, so the server applies the write and returns the new version's tag
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "v8"
{"id":42,"status":"shipped"}
# Client B writes using the same tag it read before A's update, which is now stale
PUT /orders/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "v7"
{"status":"cancelled"}
# The current tag is "v8", so the server rejects the write and leaves A's change intact.
# B should GET /orders/42 again, reconcile the change, and retry with If-Match: "v8".
HTTP/1.1 412 Precondition Failed
Content-Type: application/problem+json
{"title":"Precondition Failed","status":412,"detail":"Order 42 has changed since you last read it."}
Two PUT requests with If-Match: the first carries the current ETag and gets 200 with a new ETag, and the second carries the stale ETag and gets 412 Precondition Failed instead of overwriting the first write.
How do conditional GETs and 304 Not Modified work?
On the read path, the ETag avoids resending a representation the client already has. The client stores the ETag from a 200 OK and sends it back in If-None-Match on the next GET. If the current representation still has that ETag, the server returns 304 Not Modified with no body, and the client reuses its cached copy.
Here is a typical exchange. The client requests GET /users/alice and gets 200 OK with ETag: "a1b2c3" and the JSON body. Later it sends the same request with If-None-Match: "a1b2c3". If nothing has changed, the response is 304 Not Modified with an empty body.
A 304 still has to carry the headers that would have appeared on the 200 and that affect caching:
ETagCache-ControlExpiresVaryContent-LocationandDate, where they apply
Caches use these headers to refresh the stored response's metadata. If you leave out Cache-Control, the client may keep using freshness rules that no longer apply.
Last-Modified with If-Modified-Since does a similar job, but HTTP dates only have one-second resolution. If two updates happen within the same second, both versions carry the same timestamp, and a client holding the first version gets a 304 for the second. An ETag that changes on every write does not have this problem.
The savings are limited. If the ETag is a hash of the response body, the server usually has to run the query, serialize the result and hash it before it can decide to return a 304. That saves bandwidth and client parsing, but not server CPU or database work.
# --- Request 1: client has no cached copy ---
GET /users/alice HTTP/1.1
Host: api.example.com
Accept: application/json
HTTP/1.1 200 OK
Date: Sat, 14 Nov 2026 10:00:00 GMT
Content-Type: application/json
Content-Length: 37
ETag: "a1b2c3"
Cache-Control: private, max-age=60
Vary: Accept
{"id":"alice","name":"Alice Example"}
# --- Request 2: client revalidates using the stored ETag ---
GET /users/alice HTTP/1.1
Host: api.example.com
Accept: application/json
If-None-Match: "a1b2c3"
# ETag still matches: no body is sent, but the caching headers are
# repeated so the client can refresh its stored metadata.
HTTP/1.1 304 Not Modified
Date: Sat, 14 Nov 2026 10:05:00 GMT
ETag: "a1b2c3"
Cache-Control: private, max-age=60
Vary: Accept
A raw HTTP exchange in which the first GET returns 200 with an ETag, and a later conditional GET with If-None-Match returns 304 with no body but with the ETag, Cache-Control, Vary and Date headers still present.
How should you generate ETags so the check-and-write is atomic?
Generating ETags from the response body is also hard to enforce at write time, because the database cannot compare a hash it never stores. The generation strategy decides both cost and correctness:
| Strategy | Per-request cost | Fast or clock-skewed writes | Schema work | Leak risk |
|---|---|---|---|---|
| Version counter / row version column | Read one column | Correct: increments on every write | Add column, backfill | Predictable edit count if exposed raw |
| Hash of serialized representation | Serialize and hash | Correct only if serialization is deterministic | None | Low |
updated_at timestamp |
Read one column | Two writes in one clock tick collide; skew across hosts can move it backwards | Often already present | Exposes modification time |
Do not read the version, compare it in application code and then write. Another request can commit between your comparison and your UPDATE, and both clients succeed, so one update is lost. Put the check in the write itself: UPDATE orders SET ..., version = version + 1 WHERE id = ? AND version = ?. The database evaluates the predicate and applies the change as one step. If zero rows are affected, either the row no longer exists (404) or the version changed (412 Precondition Failed). A follow-up read tells you which.
This only works if every write path increments the version, including migrations, admin tools, batch jobs and one-off SQL fixes. A database trigger can enforce that.
Keep ETags opaque. Encode the version with a keyed MAC or encryption so clients cannot see raw IDs or edit counts, and so the server can recover the version and reject tampered values.
A version column costs a schema change and a backfill. After that, each check is a single predicate on an UPDATE you already run, which costs almost nothing.
import hashlib, hmac, sqlite3
ETAG_KEY = b"placeholder-etag-key-rotate-me" # load from a secret store in practice
def make_etag(order_id: int, version: int) -> str:
# A keyed MAC hides the raw ID and edit count, and clients cannot forge it
msg = f"order:{order_id}:v{version}".encode()
return '"' + hmac.new(ETAG_KEY, msg, hashlib.sha256).hexdigest()[:32] + '"'
def update_status(conn: sqlite3.Connection, order_id: int,
if_match: str, new_status: str):
row = conn.execute("SELECT version FROM orders WHERE id = ?",
(order_id,)).fetchone()
if row is None:
return 404, None
version = row[0]
# This read only maps the opaque token back to a version.
# It is NOT the concurrency check. The WHERE clause below is.
if not hmac.compare_digest(if_match, make_etag(order_id, version)):
return 412, None
# The check and the write are one statement. If another writer
# committed after our SELECT, version no longer matches and 0 rows change.
cur = conn.execute(
"UPDATE orders SET status = ?, version = version + 1 "
"WHERE id = ? AND version = ?",
(new_status, order_id, version),
)
conn.commit()
if cur.rowcount == 0:
# The row changed or was deleted between the SELECT and the UPDATE.
# Re-read here if you need to return 404 for the deleted case.
return 412, None
return 200, make_etag(order_id, version + 1) # send as the new ETag header
Uses an HMAC-opaque ETag, turns it into a version, and puts the version check inside the UPDATE predicate so the compare-and-write is atomic. A zero affected-row count becomes 412 Precondition Failed.
Representation pitfalls: Vary, compression, field selection and collections
The rule: if the response bytes change, the ETag must change. A strong ETag promises byte-for-byte identity, so any parameter that alters the body has to feed into the tag. That includes Accept or Accept-Language negotiation, ?fields= selection, and ?expand= embedding.
Vary and per-variant tags
Vary: Accept, Accept-Encoding tells caches to key stored responses on those request headers as well as the URL. Each variant then needs its own ETag. That splits the cache: a client asking for a different field set or language misses, even when the underlying row hasn't changed. A single resource-level version (W/"v42") works for concurrency and for revalidation where semantic equivalence is enough. It does not work wherever byte-level identity is promised, such as range requests, or shared caches that would serve one variant's bytes in response to another's validator.
Compression
Gzip or brotli middleware changes the bytes, so a correct proxy has two options. It can mark the tag weak (W/"abc"), or it can append an encoding suffix. Some proxies remove the header entirely. If-Match uses strong comparison, so a weak tag never matches and a suffixed tag fails unless your origin normalizes it. Every write then returns 412 with no obvious cause. To diagnose, compare the ETag the origin emits with what the client receives, with and without Accept-Encoding. Then check what value the client echoes back.
Collections
A list ETag versions one page of one query. It changes when any member, the ordering or the page boundaries change. It is useful for 304s, but not as a write precondition. Put If-Match on individual resources.
How do you require If-Match with 428 and expose ETags to clients?
An optimistic concurrency scheme only protects you if clients use it. A client that sends PUT without If-Match skips the check and can overwrite someone else's change. For resources where lost updates matter, reject unconditional writes with 428 Precondition Required. Include a response body that names the missing header and explains how to get the current ETag.
Turning this on everywhere at once will break existing integrations, so roll it out in phases:
- Log. Record every unconditional write with its client identity and route. This tells you who would break.
- Warn. Contact those clients directly, and add a deprecation warning to their responses.
- Enforce narrowly. Start with high-contention resources or a new API version.
- Enforce broadly. Extend once the logs show unconditional writes have dropped to zero.
Browser clients need two CORS settings. Access-Control-Expose-Headers: ETag lets JavaScript read the ETag from the response. Access-Control-Allow-Headers: If-Match lets the preflight request permit it. If either is missing, browser clients fail even when the server logic is correct.
SDKs should make the read-modify-write cycle the default path:
get()returns the resource along with its ETag.update()requires that ETag.
API docs should show the full cycle, not isolated calls.
On 412, the client should:
- Re-fetch the resource.
- Merge non-overlapping changes, or report the conflict to the user.
- Retry with a bounded number of attempts, typically a small number with backoff.
This approach saves time. A silent overwrite usually comes to light weeks later as a support ticket and requires reconstructing history from logs. A 412 happens at write time, names the resource, and can be reproduced in a test.
// Server CORS response headers that browser clients need:
// Access-Control-Allow-Origin:
// Access-Control-Allow-Methods: GET, PUT, OPTIONS
// Access-Control-Allow-Headers: Content-Type, If-Match // preflight permits If-Match
// Access-Control-Expose-Headers: ETag // JS can read res.headers.get("ETag")
// Client read-modify-write loop with a bounded number of retries on 412.
// `modify` must reapply the user's change to fresh data. It should throw if the
// change can no longer be merged, so the conflict is reported to the user.
async function updateWithRetry<T>(
url: string,
modify: (current: T) => T,
maxAttempts = 3,
): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
// Read the current state and the version it was read at.
const res = await fetch(url);
if (!res.ok) throw new Error(`GET failed: ${res.status}`);
const etag = res.headers.get("ETag");
if (!etag) throw new Error("No ETag visible; check Access-Control-Expose-Headers");
const next = modify((await res.json()) as T);
// Write only if nobody has changed the resource since our read.
const put = await fetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json", "If-Match": etag },
body: JSON.stringify(next),
});
if (put.ok) return next;
if (put.status !== 412) throw new Error(`PUT failed: ${put.status}`);
// 412: another writer got there first. Back off, then re-fetch and merge again.
await new Promise((r) => setTimeout(r, 100 * 2 ** (attempt - 1)));
}
// Give up with an explicit, testable error instead of overwriting the other change.
throw new Error(`Conflict on ${url} persisted after ${maxAttempts} attempts`);
}
Shows the CORS headers that let a browser read ETag and send If-Match, and a client loop that re-fetches, merges and retries a conditional PUT a bounded number of times after a 412.
When should you avoid ETag concurrency, and what are the alternatives?
Optimistic concurrency assumes conflicts are rare. Where that assumption fails, it fails in predictable ways:
- Hot resources. With many clients writing one counter or shared settings document, each loser gets a
412, re-reads, retries and often collides again. Rising contention means more wasted round trips, not more completed writes. - Multi-resource invariants. An ETag protects only one representation. Debiting account A and crediting account B as two conditional writes can leave the pair inconsistent even though each write passed its check.
- Read-only or single-writer resources. With no concurrent writers there is nothing to protect. Enforcement only adds a read before every write and
428handling for clients to implement.
| Alternative | Fits when | Development and operating cost |
|---|---|---|
| Pessimistic or lease-based locks | Long edits, human workflows, sustained contention | Lock storage, expiry tuning, recovery from abandoned leases |
| Server-side atomic operations (increment, append-only) | Changes that commute, such as counters or event logs | Domain-specific endpoints, a less uniform API |
JSON Patch with test operations |
Preconditions on specific fields, not the whole document | Patch engine and validation; still covers one resource |
| Transactional or batch endpoints | Invariants spanning several resources | Server transaction scope, partial-failure semantics, harder retries |
Decision checklist:
- Adopt
If-Matchenforcement when several independent clients modify the same resource and conflicts are occasional. - Prefer atomic operations when the change can be expressed without first reading current state.
- Use locks or leases when
412rates stay high, or when edits take minutes. - Use a transactional endpoint when correctness depends on more than one resource.
- Skip enforcement for single-writer or read-only resources, but keep ETags for conditional GETs.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to rest api etag, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.