# HTTP Conditional Requests: ETags, Preconditions, and Safe Writes

> Use ETags with If-Match and If-None-Match, date validators, 304 versus 412, optimistic concurrency, If-Range, and retries without lost updates.

**Quick answer:** Conditional requests turn HTTP into a compare-and-swap protocol. A GET with If-None-Match returns 304 when the ETag still matches, while PUT, PATCH, and DELETE with If-Match return 412 when the resource changed. Use strong ETags for writes and ranges, dates only as a fallback, and treat 304 as success rather than an error.

## Key takeaways

- Conditional GET saves bandwidth with 304; conditional writes enforce optimistic concurrency with 412, and the two outcomes must never be conflated.
- If-Match on PUT, PATCH, and DELETE is the lost-update guard; without it, the last writer silently wins.
- Strong ETags compare bytes and are mandatory for If-Match and If-Range; weak validators are acceptable only for cache validation.
- Dates have one-second resolution and depend on clocks, so ETags rather than Last-Modified should carry concurrency decisions.
- The precondition check and the write must happen atomically, and a 412 must trigger a fresh read rather than a blind retry.

---

A conditional request is HTTP's compare-and-swap primitive. The client attaches a validator to a method and asks the origin to proceed only if the current representation still satisfies a stated condition. The same headers support two different jobs: skipping a redundant response body on GET, and refusing a stale write on PUT, PATCH, or DELETE. Teams usually learn the difference after an incident, when a retry overwrites a colleague's edit or a dashboard treats every 304 as a failure.

## What a conditional request actually asks

A conditional request is evaluated before the method runs. RFC 9110 fixes the order: `If-Match`, `If-Unmodified-Since`, `If-None-Match`, `If-Modified-Since`, `If-Range`. `If-Match` suppresses `If-Unmodified-Since`, and `If-None-Match` suppresses `If-Modified-Since`. Each header asks a yes-or-no question about the selected representation, not the URL in the abstract; negotiated variants need their own validators.

There are three outcomes: proceed, 304, or 412. A 304 is reserved for GET and HEAD when a validator proves the representation unchanged. A 412 is the general refusal: an `If-Match` mismatch, an `If-Unmodified-Since` failure, or an `If-None-Match` match on an unsafe method. The intent differs. Conditional GET validates a cache, while conditional PUT, PATCH, or DELETE guards a transaction.

## If-Match and If-None-Match with ETags

An `ETag` identifies one representation as a quoted opaque string, optionally prefixed with `W/` for weak. Clients compare it exactly and never parse meaning from it. `If-Match` accepts one or more tags or `*` and uses strong comparison: the current strong ETag must equal one listed value, or the server returns 412 without applying the method. The `*` form means "only if a representation exists", preventing an accidental upsert.

`If-None-Match` uses weak comparison. On GET or HEAD a match produces 304 without a body; on an unsafe method a match produces 412. That makes `If-None-Match: *` on PUT a create-only guard.

ETags are per representation. A gzip body differs from an identity body, so each variant needs its own tag and the correct `Vary` header. Pairing one variant's ETag with another variant's body breaks validation and preconditions at once. The [HTTP headers analyzer](/tools/http-headers) shows which validator and `Vary` value arrived with each response.

## Date validators: If-Modified-Since and If-Unmodified-Since

Date validators come from `Last-Modified`, an HTTP-date with one-second resolution. `If-Modified-Since` applies only to GET and HEAD and is ignored when `If-None-Match` is present or the method is unsafe. `If-Unmodified-Since` is the write-side mirror: proceed only if the representation has not changed since the date, otherwise 412; it is ignored when `If-Match` is present.

Dates are coarse. Two edits in one second collapse into one timestamp, clock skew shifts comparisons, and a date cannot prove byte identity. Use them as a fallback for simple clients and static files, never as the only concurrency token for records people edit. ETag first, date second.

## Strong and weak validators

A strong ETag promises byte-for-byte identity; any change to representation data, including content encoding, must change it. A weak ETag, written `W/"..."`, promises only semantic equivalence. Weak tags are enough for `If-None-Match` cache revalidation but not for `If-Match` or `If-Range`, which require strong comparison.

Range resumption shows why: a client that has the first megabyte and resumes with a weak validator can splice a suffix from a newer version into the file. Writes show the same problem: a server that accepts a weak tag in `If-Match` claims byte identity it cannot prove. If the framework cannot produce strong tags, fix the validator or disable conditional writes; do not relabel weak as strong.

A good ETag hashes the exact served bytes, after content encoding, per variant. A file mtime, inode number, process-local counter, random per-request value, or user ID makes nodes disagree or invalidates the cache on every read.

## Optimistic concurrency for PUT, PATCH, and DELETE

Read-modify-write is the core pattern. The client GETs the resource, keeps the ETag, edits a copy, and sends the write with `If-Match`. The server compares the precondition with the current representation and applies the method only on a match, returning the new representation or a 204 with the new ETag. On a mismatch it returns 412 and changes nothing; the client re-reads, reconciles, and retries with the fresh validator.

DELETE needs the same guard, or it can remove a record someone just updated. PATCH adds merge or patch syntax, but the precondition still protects the base representation. The comparison and the write must be atomic: a conditional `UPDATE`, a row lock across the check, a DynamoDB condition expression, or a Redis script. Reading the ETag in application code and then writing unconditionally leaves the race intact.

| Method | Header | Condition | Success | Failure |
| --- | --- | --- | --- | --- |
| GET, HEAD | `If-None-Match` | current validator differs from every listed tag | 200 with body | 304 without body |
| GET, HEAD | `If-Modified-Since` | representation changed after the date | 200 with body | 304 without body |
| PUT, PATCH, DELETE | `If-Match` | current strong ETag matches a listed tag, or `*` and a representation exists | 2xx with new validator | 412, method not applied |
| PUT | `If-None-Match: *` | no current representation exists | 2xx, resource created | 412, no overwrite |
| GET with `Range` | `If-Range` | validator matches the current representation | 206 with `Content-Range` | 200 with the full body |
| Any unsafe method | `If-Unmodified-Since` | representation not modified after the date | method proceeds | 412, method not applied |

A complete exchange shows the state transition:

```http
GET /articles/42 HTTP/1.1
Host: api.example.com

HTTP/1.1 200 OK
Content-Type: application/json
ETag: "9f1c2ab7"

PUT /articles/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "9f1c2ab7"

{"title":"Updated title"}

HTTP/1.1 412 Precondition Failed
ETag: "b47d0e19"
Content-Type: application/problem+json

{"type":"about:blank","title":"Precondition Failed","status":412}

GET /articles/42 HTTP/1.1
Host: api.example.com

HTTP/1.1 200 OK
Content-Type: application/json
ETag: "b47d0e19"

PUT /articles/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json
If-Match: "b47d0e19"

{"title":"Updated title"}

HTTP/1.1 204 No Content
ETag: "c81e77a4"
```

The 412 is informative, not destructive. Repeat the current ETag and optionally the current representation so the client can reconcile; keep that body within the caller's authorization. A successful 200 or 204 should carry the new ETag, or the next conditional request will fail on a stale validator.

## Lost updates, retries, and idempotency

A lost update happens when two clients read the same version and both write. Without a precondition the second silently replaces the first. With `If-Match` one succeeds and the other gets 412; the loser fetches current state, merges, and resubmits with the new validator.

Retries need the same discipline. PUT and DELETE are idempotent, but a retry is not automatically safe after a concurrent change. If the first PUT succeeded and the response was lost, a retry with the old ETag returns 412. Only a fresh GET tells the client whether its write landed or someone else won. Treat 412 as a signal to reconcile, never as a transient failure.

Reuse the exact body and validator on transport retries; the server owns the ETag. POST needs an idempotency key because conditional headers do not make a non-idempotent operation idempotent. The [HTTP request workbench](/tools/http-request) can replay the same PUT twice with the same `If-Match` and show the second 412.

## If-Range and range requests

Range requests let a client resume a download in pieces. Without `If-Range`, a client that holds the first megabyte and asks for the rest may receive a suffix from a newer version, producing a file with bytes from two representations. `If-Range` carries a validator: on a match the server returns 206 with the range; otherwise it returns 200 with the full current representation, and the client starts over.

`If-Range` needs a strong validator; weak ETags cannot be used. The date form is allowed only when `Last-Modified` is strong. Servers may ignore `Range` and return 200, which is valid; an unsatisfiable range returns 416. `If-Range` gates partial content, never writes.

Compression complicates ranges because content coding changes bytes and length. Test with the same `Accept-Encoding` values real clients send, and check that `Content-Range`, `Content-Length`, and the byte count agree.

## Cache validation versus write preconditions

The same header names carry different contracts. `If-None-Match` on GET validates a cache: a match produces 304, a successful bodyless response with refreshed metadata, and changes no state. `If-Match` on PUT is a write precondition: a mismatch produces 412 and the method is not applied. A 304 is not an error; a 412 is not a cache miss.

A correct 304 carries `ETag`, `Cache-Control`, `Date`, and `Vary`, plus `Expires` or `Content-Location` when relevant, and no body. A 412 may carry the current validator and representation to help reconciliation, without leaking data. Method rules are strict: `If-Modified-Since` is ignored on unsafe methods, and `If-None-Match` on an unsafe method produces 412, not 304. A proxy must not cache an unsafe request or strip preconditions while forwarding.

## Common mistakes that defeat preconditions

The expensive failures cluster around a few choices:

- Using `Last-Modified` as the concurrency token, then losing two edits made in the same second.
- Omitting `If-Match` on PUT, PATCH, or DELETE, leaving last-write-wins semantics.
- Treating a 304 as a failed request and retrying until rate limits become the real incident.
- Advertising a weak ETag as strong, then accepting it for `If-Match` or `If-Range`.
- Generating ETags from file modification times or process-local counters, so nodes disagree.
- Checking the ETag in application code and then writing unconditionally.
- Expecting 304 from `If-None-Match` on a PUT; unsafe methods return 412 on a match.
- Returning 200 or 204 after a write without the new ETag.
- Retrying a 412 with the same validator instead of re-reading the resource.
- Publishing one ETag across compressed and uncompressed variants, or omitting `Vary`.

The antidote is a short set of rules. Make the validator strong, compute it from served bytes, and scope it to one representation. Require `If-Match` on every state-changing method that updates or deletes an existing resource. Compare and write atomically. Return the new validator on success and the current one on 412. Teach clients that 304 is success and 412 requires reconciliation.

## Verification checklist for conditional requests

Verify against a real deployment, not a mocked ETag. Capture the validator, then exercise both outcomes:

```bash
# 1. Capture the current validator
etag=$(curl -sSI https://api.example.com/articles/42 | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d '\r')

# 2. A conditional GET must be a bodyless 304
curl -sS -o /dev/null -w 'status=%{http_code} bytes=%{size_download}\n' \
  -H "If-None-Match: $etag" https://api.example.com/articles/42

# 3. A stale write must fail without changing state
curl -sS -o /dev/null -w 'status=%{http_code}\n' -X PUT \
  -H 'Content-Type: application/json' -H 'If-Match: "stale-value"' \
  --data '{"title":"should not apply"}' https://api.example.com/articles/42

# 4. The current validator must allow exactly one update
curl -sS -D - -o /dev/null -X PUT \
  -H 'Content-Type: application/json' -H "If-Match: $etag" \
  --data '{"title":"updated"}' https://api.example.com/articles/42
```

Read the status, headers, and stored record after each step, then confirm:

| Check | How to test | Pass criterion |
| --- | --- | --- |
| Conditional GET | Send the stored ETag in `If-None-Match` | 304 with a zero-byte body and the same ETag |
| Stale update | PUT with an old ETag | 412 and the stored document unchanged |
| Current update | PUT with the current ETag | 200 or 204 with a new ETag |
| Create-only | PUT with `If-None-Match: *` to an existing URL | 412 and no overwrite |
| Stale delete | DELETE with an old ETag | 412 and the record still present |
| Range resume | `If-Range` with matching and stale ETags | 206 plus `Content-Range` on match; 200 full otherwise |
| 304 metadata | Inspect the 304 response headers | `ETag`, `Cache-Control`, `Date`, and `Vary` present; no body |
| Concurrent writers | Two clients read one ETag and both write | Exactly one succeeds; the other gets 412 |

For JSON, inspect the exact bytes the client sends and the server hashes. The [JSON formatter](/tools/json-formatter) makes whitespace and key order visible, because an ETag describes the served byte sequence, not an abstract data model. A client that reformats before hashing sees conflicts that do not exist; a server that hashes one form and serves another accepts writes against the wrong bytes.

Finally, test with two concurrent clients. Sequential curl commands prove the happy path, not atomicity. Run two PUTs with the same ETag at once, repeat against every node, and confirm exactly one wins while the other gets 412. That catches per-process validators, missing database predicates, and proxies that strip the precondition.

## Frequently asked questions

### What is the difference between 304 Not Modified and 412 Precondition Failed?

A 304 answers a conditional GET or HEAD: the validator still matches, so the server omits the body but keeps the method successful. A 412 means a precondition such as If-Match was false and the server refused to apply the method, so no write occurred.

### Should an update use If-Match or If-None-Match?

Use If-Match for an update or delete that must apply only to a known version. Use If-None-Match with the asterisk form on PUT when the resource must not already exist, which makes creation conditional and returns 412 instead of overwriting.

### Can Last-Modified replace an ETag for optimistic concurrency?

No. Last-Modified has one-second resolution, depends on clock synchronization, and cannot distinguish two edits within the same second. It is a cache fallback; concurrency decisions need a strong ETag generated from the exact representation.

### Why does If-Match fail when the client sends a weak ETag?

If-Match uses strong comparison, and a weak validator never satisfies it because it promises semantic equivalence rather than byte identity. The origin must issue a strong ETag for any resource that supports conditional writes.

### Does If-Range protect against lost updates?

No. If-Range only decides whether a Range request may return partial content; it prevents mixing bytes from different versions during a resume. Write safety still depends on If-Match on the unsafe method.

## References

- [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110)
- [MDN: If-Match](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/If-Match)
- [MDN: 412 Precondition Failed](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/412)
- [RFC 9111: HTTP Caching](https://www.rfc-editor.org/rfc/rfc9111)

---

- Canonical: https://www.jsonmind.com/guides/http-conditional-requests
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: http-headers, http-request, json-formatter