Understanding HTTP 412 Precondition Failed: If-Match, ETags, and Stopping Lost Updates
412 Precondition Failed is the one error code the client asks for. It only happens when the request itself said "do this only if…" and the server checked and found the condition false. It's easy to confuse with 409 Conflict, because both are about two clients stepping on each other's changes. But 412 is the HTTP-level version, triggered by conditional headers like If-Match and If-Unmodified-Since, while 409 is your application spotting a conflict in its own logic. This post covers what 412 means, which headers produce it, how ETags use it to prevent lost updates, how it compares to 304, 409 and 428, and how to return and handle it correctly.
What Is a 412?
A 412 means the server evaluated one or more preconditions the client sent in its request headers, found at least one of them false, and refused to perform the method.
The 412 (Precondition Failed) status code indicates that one or more conditions given in the request header fields evaluated to false when tested on the server (Section 13). This response status code allows the client to place preconditions on the current resource state (its current representations and metadata) and, thus, prevent the request method from being applied if the target resource is in an unexpected state. — RFC 9110, Section 15.5.13
In plain English: "You told me to do this only if the resource still looked a certain way. It doesn't, so I didn't." Nothing was written, deleted or changed. The 412 is the client's own safety catch working as intended.
The Lost Update Problem
412 exists to solve one problem: two clients reading the same resource, both editing it, and the second save silently wiping out the first. Here's how it plays out without preconditions:
- Alice
GETs/articles/42. BobGETs/articles/42. Both see version 7. - Alice fixes a typo and
PUTs her copy. The article is now version 8. - Bob rewrites the intro and
PUTs his copy, which is still based on version 7. - Bob's
PUTsucceeds, and Alice's typo fix is gone. Nobody was told.
Conditional requests fix this with entity tags (ETags), opaque version strings the server sends with each representation:
GET /articles/42 HTTP/1.1
HTTP/1.1 200 OK
ETag: "v7"
Content-Type: application/json
{ "id": 42, "title": "Teh Basics", "body": "..." }When the client saves, it sends that ETag back in If-Match, meaning "only apply this if the article is still "v7"":
PUT /articles/42 HTTP/1.1
If-Match: "v7"
Content-Type: application/json
{ "id": 42, "title": "The Basics", "body": "..." }Alice's PUT matches, succeeds, and the server answers with ETag: "v8". Bob's PUT still says If-Match: "v7", so it fails:
HTTP/1.1 412 Precondition Failed
ETag: "v8"
Content-Type: application/json
{ "error": "precondition_failed", "message": "This article changed since you loaded it." }Bob's client now knows his copy is stale. It can fetch version 8, show him what changed, and let him re-apply his edit on top. That's optimistic concurrency control: no locks are held. You just refuse writes based on a version that's out of date.
Which Headers Produce a 412
RFC 9110, Section 13 defines five conditional headers. The fifth, If-Range, never fails a request: it just falls back to a full 200 instead of a 206 partial response. The other four don't all fail the same way:
If-Match: "etag"— "Only if the current ETag is one of these." False → 412. This is the main source of 412s.If-Unmodified-Since: <date>— "Only if it hasn't changed since this date." False → 412. It's the fallback for resources without ETags, and the server must ignore it whenIf-Matchis also present.If-None-Match— "Only if the current ETag is not one of these." False onGET/HEAD→ 304. False on any other method → 412.If-Modified-Since— a cache check forGET/HEADonly. False → 304, never 412.
A useful special case is If-None-Match: * on a PUT, which means "create this only if nothing exists here yet." If two clients race to create the same resource, the second one gets a 412 instead of overwriting the first. Amazon S3 added exactly this in 2024: conditional writes accept If-None-Match: * and If-Match on uploads, and a losing write gets 412 Precondition Failed.
If-Match also has a strictness rule that catches people out:
An origin server MUST use the strong comparison function when comparing entity tags for If-Match — RFC 9110, Section 13.1.1
Strong comparison means both tags must be identical and neither may be weak (W/"..."). A weak ETag says "semantically equivalent", which is fine for caching but not good enough to guard a write. So a weak ETag can never satisfy If-Match. We'll come back to why that matters in Express.
Order Matters: 412 Isn't Evaluated First
Preconditions aren't the first thing a server checks. The RFC places them after the normal request checks and just before the method runs:
A server MUST ignore all received preconditions if its response to the same request without those conditions, prior to processing the request content, would have been a status code other than a 2xx (Successful) or 412 (Precondition Failed). — RFC 9110, Section 13.2.1
In practice: if the resource doesn't exist, that's a 404, not a 412. If the user isn't logged in, it's a 401. If they lack permission, it's a 403. Auth, routing and existence checks all come before the precondition check.
When several conditional headers arrive together, Section 13.2.2 fixes the order: If-Match, then If-Unmodified-Since (only when If-Match is absent), then If-None-Match, then If-Modified-Since, then If-Range. The write-guarding checks run first because a lost update is worse than a wasted download.
412 vs 304 vs 409 vs 428
| Code | Meaning | Use when |
|---|---|---|
| 412 Precondition Failed | A conditional header evaluated false | The client sent If-Match / If-Unmodified-Since (or If-None-Match on a write) and the resource no longer matches |
| 304 Not Modified | The cached copy is still current | If-None-Match / If-Modified-Since on a GET or HEAD and nothing changed |
| 409 Conflict | The request clashes with current state | An application-level conflict: a duplicate email, a version field in the body that's stale, an invalid state transition |
| 428 Precondition Required | A conditional header was required but missing | The server insists on If-Match for writes and the client sent a bare PUT |
The heuristics to remember:
- 412 = "Your only if was false." The condition was in the headers, and HTTP machinery checked it.
- 304 = "Your only if was false, and that's good news." Same mechanism, but on a read, where it means "you already have it."
- 409 = "Your request conflicts with what's here." No conditional header involved; your own code found the clash.
- 428 = "You need to say only if." It comes before a 412: the client didn't send a precondition at all.
Our 409 Conflict post shows the same optimistic-locking idea built with a version field in the request body. Both approaches are valid. 412 is what you get when the version travels in standard headers instead.
Common Causes
- A stale
If-Match. Someone else updated the resource after the client read it. This is a 412 doing its job. If-Unmodified-Sinceolder than the last modification. The same thing for clients that track dates instead of ETags.If-None-Match: *on a resource that already exists. A create-only write lost a race, or the client wrongly believed nothing was there.- A weak ETag sent in
If-Match. The server compares strongly, soW/"abc"never matches, not evenW/"abc"itself. Every conditional write fails. - The ETag changed for reasons unrelated to the data. Compression, a different serializer, or a load balancer spreading requests across servers that compute ETags differently can all produce a new tag for the same content.
- A malformed date. The RFC says an invalid
If-Unmodified-Sincemust be ignored, but some servers fail it instead (NGINX among them, below).
Returning 412 Correctly
The rule for every platform: make the check and the write a single atomic step. Reading the ETag, comparing it, then writing in separate steps leaves a gap where another request can slip in, and you've rebuilt the lost-update problem with extra steps.
Express / Node.js
const etagFor = (article) => `"v${article.version}"`;
function ifMatchPasses(header, currentEtag) {
if (header.trim() === "*") return true; // any current representation matches
return header
.split(",")
.map((tag) => tag.trim())
.some((tag) => !tag.startsWith("W/") && tag === currentEtag); // strong comparison
}
app.put("/articles/:id", async (req, res) => {
const article = await db.getArticle(req.params.id);
if (!article) {
return res.status(404).json({ error: "not_found" }); // existence beats preconditions
}
const ifMatch = req.get("If-Match");
if (!ifMatch) {
return res.status(428).json({
error: "precondition_required",
message: "Send If-Match with the ETag you last read.",
});
}
if (!ifMatchPasses(ifMatch, etagFor(article))) {
return res
.status(412)
.set("ETag", etagFor(article))
.json({ error: "precondition_failed", message: "This article changed since you loaded it." });
}
// Re-check the version inside the write itself (see the SQL below)
const updated = await db.updateArticleIfVersion(article.id, article.version, req.body);
if (!updated) {
const current = await db.getArticle(article.id);
return res
.status(412)
.set("ETag", etagFor(current))
.json({ error: "precondition_failed", message: "This article changed since you loaded it." });
}
res.set("ETag", etagFor(updated)).json(updated);
});Two Express details matter here. First, Express generates weak ETags by default (app.set("etag", "weak")) for anything sent with res.send or res.json. Those are fine for 304 responses, but they can never pass an If-Match check. Setting ETag yourself, as above, stops Express from generating its own. Second, updateArticleIfVersion is where the atomicity lives:
UPDATE articles
SET title = $3, body = $4, version = version + 1
WHERE id = $1 AND version = $2
RETURNING *;If zero rows come back, someone else won the race between the check and the write, and that's a 412 too.
Next.js App Router
// app/api/articles/[id]/route.ts
const etagFor = (version: number) => `"v${version}"`;
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
const current = await getArticle(id);
if (!current) {
return Response.json({ error: "not_found" }, { status: 404 });
}
const ifMatch = request.headers.get("if-match");
if (!ifMatch) {
return Response.json({ error: "precondition_required" }, { status: 428 });
}
// This API only issues single strong tags shaped like "v7"
const match = /^"v(\d+)"$/.exec(ifMatch.trim());
const updated = match
? await updateArticleIfVersion(id, Number(match[1]), await request.json())
: null;
if (!updated) {
const latest = (await getArticle(id)) ?? current;
return Response.json(
{ error: "precondition_failed", message: "This article changed since you loaded it." },
{ status: 412, headers: { ETag: etagFor(latest.version) } },
);
}
return Response.json(updated, { headers: { ETag: etagFor(updated.version) } });
}Here the comparison is the write: updateArticleIfVersion runs the same WHERE id = $1 AND version = $2 update, so there's no gap between checking and saving. In Next.js 15 and later, route handler params is a Promise, so await it before reading id.
NGINX
For files NGINX serves from disk, it handles conditional headers itself. It generates strong ETags from each file's modification time and size (etag on; is the default) and answers a failed If-Match or If-Unmodified-Since with a 412 instead of sending the file:
curl -I -H 'If-Match: "not-the-current-etag"' https://example.com/files/report.pdf
# HTTP/1.1 412 Precondition FailedWhen NGINX is a plain reverse proxy (no proxy_cache), it passes If-Match and friends through to the upstream untouched, and that's correct: the RFC says only the origin server should evaluate them. Two known quirks are worth knowing:
- Malformed
If-Unmodified-Sincedates fail instead of being ignored. NGINX parses an invalid date as a moment in 1969, so the condition is always false and you get a 412. The ticket was closed as won't-fix. X-Accel-Redirectdouble-checks. If your app validatesIf-Matchand then hands the file to NGINX withX-Accel-Redirect, NGINX evaluates the header again against the file's own ETag and can return 412 even though your app said yes (ticket). The suggested workaround is clearing the header on the internal request.
REST API JSON body
HTTP/1.1 412 Precondition Failed
ETag: "v8"
Content-Type: application/json
{
"error": "precondition_failed",
"message": "The article was modified after you loaded it. Reload, review the changes, and try again.",
"currentEtag": "\"v8\""
}The RFC doesn't require an ETag on a 412, but sending the current one saves the client a round trip and tells it exactly which version it lost to.
Handling 412 on the Client
A 412 is a prompt to reconcile, not a failure to retry:
async function saveArticle(article, etag) {
const res = await fetch(`/api/articles/${article.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json", "If-Match": etag },
body: JSON.stringify(article),
});
if (res.status === 412) {
const latest = await fetch(`/api/articles/${article.id}`);
return {
conflict: true,
theirs: await latest.json(),
theirEtag: latest.headers.get("ETag"),
};
}
return { conflict: false, saved: await res.json(), etag: res.headers.get("ETag") };
}Show the user both versions, merge automatically if the edits don't overlap, then save again with the new ETag. What you must not do is retry immediately with the new ETag and the old body. That overwrites the other person's change, which is exactly what the precondition was there to prevent.
If the API is on another origin, CORS adds two requirements. If-Match isn't a CORS-safelisted request header, so the server must list it in Access-Control-Allow-Headers. ETag isn't a safelisted response header either, so the server must add it to Access-Control-Expose-Headers, or res.headers.get("ETag") returns null in the browser.
412 and SEO
412 should never reach a search crawler. Googlebot makes plain GET requests, sometimes with If-None-Match or If-Modified-Since to check for changes, and those should only ever produce a 200 or a 304. If a public page returns 412 to a crawler, something is misconfigured: a server treating a cache validator as a write guard, a CDN rejecting a malformed date, or an app requiring If-Match on GET.
That matters because Google handles 4xx responses other than 429 as "this content doesn't exist." A page that 412s for Googlebot will drop out of the index the same way a 404 would. Spot-check important URLs with conditional headers (curl -I -H 'If-None-Match: "x"' <url>) and make sure they return 200 or 304.
Common Pitfalls
- Guarding writes with weak ETags.
If-Matchuses strong comparison, soW/"..."tags never match and every save fails. Issue strong ETags for anything clients will write back. In Express, set the header yourself rather than relying on the default weak one. - Checking, then writing. A separate read-compare-write has a race window. Put the version in the
WHEREclause (or use your datastore's compare-and-set) so the check and the write are one step. - Returning 412 when another error applies. A missing resource is a 404, a missing login is a 401, a missing permission is a 403. Preconditions are only evaluated once everything else would have succeeded.
- Returning 412 for a failed
If-None-Matchon aGET. That's a 304. 412 is for writes and other unsafe methods. - Using 412 for business-rule failures. A duplicate email or an order that's already shipped is a 409 or 422. Reserve 412 for failed conditional headers.
- Making preconditions optional on writes that need them. If clients can skip
If-Match, the lost-update problem is still there for anyone who doesn't send it. Require it and answer bare writes with 428. - Auto-retrying a 412 with the new ETag. Retrying the same body against the new version is a blind overwrite with extra steps. Reload, reconcile, then retry.
- ETags that vary across servers. If each instance behind a load balancer computes ETags differently (inode numbers, build timestamps), the same content gets different tags and writes fail at random. Derive ETags from the data, such as a version number or a content hash.
Wrapping Up
412 is a safety feature the client opts into. The rules of thumb:
- 412 means a precondition the client sent evaluated false, so nothing was changed
If-MatchandIf-Unmodified-Sinceproduce 412;If-None-Matchproduces 412 on writes but 304 on readsIf-Matchuses strong comparison: weak ETags can never pass it- Use 412 for failed conditional headers, 409 for application-level conflicts, and 428 when a required precondition is missing
- Preconditions come after routing, auth and existence checks, so a 404 or 403 beats a 412
- Make the check and the write atomic, send the current ETag back, and reconcile on the client instead of blindly retrying
For more, see our pages on 412 Precondition Failed, 409 Conflict, 304 Not Modified and 428 Precondition Required. The read side of the same conditional-request machinery is in our understanding 304 Not Modified post, application-level optimistic locking is in understanding 409 Conflict, and you can compare 409 vs 412 side by side.
Related Status Codes
- 400Bad Request
- 401Unauthorized
- 402Payment Required
- 403Forbidden
- 404Not Found
- 405Method Not Allowed
- 406Not Acceptable
- 407Proxy Authentication Required
- 408Request Timeout
- 409Conflict
- 410Gone
- 411Length Required
- 412Precondition Failed
- 413Payload Too Large
- 414URI Too Long
- 415Unsupported Media Type
- 416Range Not Satisfiable
- 417Expectation Failed
- 418I'm a Teapot
- 421Misdirected Request
- 422Unprocessable Entity
- 423Locked
- 424Failed Dependency
- 425Too Early
- 426Upgrade Required
- 428Precondition Required
- 429Too Many Requests
- 431Request Header Fields Too Large
- 451Unavailable For Legal Reasons