Is HTTP PATCH idempotent?
RFC 5789, which defines the PATCH method, states that PATCH is neither safe nor idempotent. That does not mean every PATCH request is unsafe to repeat. It means the method makes no promise. Whether sending the same request twice leaves the resource in the same state as sending it once depends on two things: what the patch document says and how the server applies it.
PUT works differently. A PUT carries a complete representation of the resource, and the server replaces whatever it holds with that representation. If you send the same body twice, the second request writes the same state again. The idempotency comes from full replacement, not from anything the server has to do carefully. "Set the user to exactly this" is idempotent. "Add this item to the user's list" is not, and PATCH can express both.
Partial updates exist because full replacement is often impractical. Sending an entire large document to change one field wastes bandwidth. More importantly, PUT requires the client to know the full current resource, including fields it doesn't own or understand. If the client gets that wrong, it can silently overwrite another client's changes or drop fields added by a newer API version. A partial update lets the client send only its intent.
That intent is where retries become a risk. A network timeout leaves the client unsure whether its PATCH was applied, so it sends the request again. The rest of this article examines which patch formats make that retry safe, and under what conditions.
How does a PATCH request work end to end?
A PATCH request carries a patch document, not a resource representation. The Content-Type header names the patch format, and that media type defines how the server interprets the body. The same JSON body means different things under application/merge-patch+json and application/json-patch+json.
On the server, a well-behaved PATCH handler goes through the same steps regardless of format:
- Check the media type. If the server does not support the format in
Content-Type, it rejects the request with 415 and lists the formats it does support inAccept-Patch. - Check preconditions. If the request carries
If-Match, the server compares it with the resource's currentETagand returns 412 on a mismatch, before touching anything. - Load the current state of the resource.
- Apply the patch to a copy, following the rules of the patch format. Merge Patch merges a sparse document into the target. JSON Patch runs an ordered list of operations.
- Validate the result against the resource schema and authorization rules.
- Commit atomically. RFC 5789 requires the server to apply the whole set of changes or none of them. A partially applied patch must never become visible.
- Respond, typically with 200 and the updated representation, or 204 with no body.
Retry safety is decided mostly in step 4. If applying the patch to its own result produces the same document, a retry is harmless. If it does not, steps 2 and 5, plus the techniques described later, have to catch the replay. The next two sections explain how each format behaves at step 4.
How does JSON Merge Patch (RFC 7396) work?
JSON Merge Patch, sent with the media type application/merge-patch+json, describes a change by showing what the resource should look like in the parts you care about. The server walks the patch and the target together, applying three rules:
- Objects merge recursively. Each member in the patch is matched by name against the target. Members the patch does not mention are left untouched.
nullremoves a member. A patch member whose value isnulldeletes that member from the target instead of storing a null.- Everything else replaces wholesale. Strings, numbers, booleans and arrays overwrite the target value completely. Arrays are not merged element by element. The patch's array becomes the new value.
Take a target of {"name": "api-gw", "tags": ["prod", "eu"], "owner": "team-a"} and a patch of {"tags": ["prod"], "owner": null}. The result is {"name": "api-gw", "tags": ["prod"]}. Apply the same patch to that result and nothing changes. tags is set to ["prod"] again, and owner is already absent, so removing it again does nothing.
This is why a retried merge patch is safe. Every rule sets the final state of a location rather than describing a step relative to the current state. The outcome depends only on the patch, so a second application produces the same document as the first.
The format is also easy for clients to produce. A merge patch looks like a sparse copy of the resource, so a client can build one by serializing an object that contains only the changed fields. It needs no path syntax and no operation vocabulary. The cost of that simplicity appears in what the format cannot say.
import copy
import json
def merge_patch(target, patch):
# Mirrors the algorithm in RFC 7396, section 2.
if not isinstance(patch, dict):
# Non-object values (strings, numbers, booleans, arrays) replace wholesale.
return copy.deepcopy(patch)
# A patch object applied to a non-object target starts from an empty object.
result = copy.deepcopy(target) if isinstance(target, dict) else {}
for name, value in patch.items():
if value is None:
# null means "remove this member". Removing an absent member is a no-op.
result.pop(name, None)
else:
# Objects merge recursively. Members not named in the patch are untouched.
result[name] = merge_patch(result.get(name), value)
return result
before = {"name": "api-gw", "tags": ["prod", "eu"], "owner": "team-a"}
patch = {"tags": ["prod"], "owner": None}
once = merge_patch(before, patch)
twice = merge_patch(once, patch) # simulate a client retry
print(json.dumps(once)) # {"name": "api-gw", "tags": ["prod"]}
print(json.dumps(twice)) # {"name": "api-gw", "tags": ["prod"]}
assert once == twice # a second application changes nothing
A minimal Python implementation of the RFC 7396 merge algorithm applies the section's patch twice and shows both results are the same: the array is replaced, owner is removed, and the retry is a no-op.
What can't JSON Merge Patch express?
Merge Patch's simplicity limits what it can say. There are three gaps, and each follows directly from reusing the resource's own shape as the patch format.
You cannot set a field to null
In a merge patch, null means "remove this member." Suppose a client sends {"middleName": null} because the API documents middleName as nullable. The server deletes the key instead of storing a null. If your schema treats "absent" and "null" differently, for example absent meaning "inherit the default," the client has changed behavior without any error. The only fixes are to avoid nullable fields that differ from absence, or to use a sentinel value that clients must learn.
You cannot edit one array element
Arrays are replaced wholesale. To change the third item in a 500-element lineItems array, the client resends all 500 items. That costs bandwidth, but the bigger problem is concurrency. Client A edits item 3 and client B edits item 400. Both send the full array, and whichever arrives second erases the other's change. The server cannot merge them, because the format has no way to say "only item 3."
A non-object patch replaces everything
If the patch body is a string, number, array, or null, the result is the patch itself. A buggy client that sends [] wipes the resource.
Merge patches are idempotent: applying the same patch twice gives the same document. That property says nothing about two different patches. Without a precondition check on the server, the last write wins and the earlier update is silently lost.
import copy
def merge_patch(target, patch):
# RFC 7396: a non-object patch replaces the target outright
if not isinstance(patch, dict):
return copy.deepcopy(patch)
result = copy.deepcopy(target) if isinstance(target, dict) else {}
for key, value in patch.items():
if value is None:
result.pop(key, None) # null means "remove", never "store null"
else:
result[key] = merge_patch(result.get(key), value)
return result
user = {"name": "Ada", "middleName": "K", "tags": ["a", "b", "c"]}
print(merge_patch(user, {"middleName": None}))
patch_a = {"tags": ["A", "b", "c"]} # client A changes tags[0]
patch_b = {"tags": ["a", "b", "C"]} # client B changes tags[2]
stored = merge_patch(merge_patch(user, patch_a), patch_b)
print(stored["tags"]) # ['a', 'b', 'C']: A's edit is silently lost
print(merge_patch(user, [])) # []
once = merge_patch(user, patch_a)
assert merge_patch(once, patch_a) == once
A minimal RFC 7396 merge-patch function in Python showing three outcomes: a null value deletes the field, two clients editing different array elements lose one update, and a top-level array patch replaces the whole resource, even though applying the same patch twice is idempotent.
How does JSON Patch (RFC 6902) work, and which operations break on retry?
A JSON Patch document (application/json-patch+json) is an ordered array of operations: add, remove, replace, move, copy and test. Each operation names its target with a JSON Pointer (RFC 6901), such as /items/2/qty, and move and copy also take a from pointer. The server applies the operations in sequence. If any one fails, the whole patch is rejected and the document stays unchanged. Because a patch describes a sequence of edits instead of a final state, its result depends on the state of the document it is applied to. That dependency is why several operations break on retry.
addto an array index or to-. Arrayaddinserts an element and never overwrites one. Each replay inserts another copy, so a retried append duplicates data.removeon a path that is already gone. RFC 6902 treats a missing target as an error. The document ends up correct, but the client receives a failure for a request that actually succeeded on the first attempt.replaceon an array index./items/0refers to whatever element currently sits at position 0. If a concurrent insert or delete shifts the array between the original request and the retry, the replay overwrites a different element.
Client Server
|-- PATCH add /tags/- "x" -->| tags: [a] -> [a, x]
| (response lost) X-|
| timeout, retry |
|-- PATCH add /tags/- "x" -->| tags: [a, x] -> [a, x, x]
|<----------- 200 OK --------|
import copy
def apply_patch(doc, ops):
# Minimal RFC 6902 sketch (add/remove/replace only, no ~0/~1 unescaping).
# Atomic: edits a deep copy, so the caller's doc is untouched if any op raises.
out = copy.deepcopy(doc)
for op in ops:
*parents, last = op["path"].split("/")[1:]
node = out
for key in parents:
node = node[int(key)] if isinstance(node, list) else node[key]
if isinstance(node, list):
if op["op"] == "add": # array add inserts, never overwrites; "-" appends
node.insert(len(node) if last == "-" else int(last), op["value"])
continue
last = int(last)
if op["op"] == "add":
node[last] = op["value"]
elif op["op"] == "remove":
del node[last] # missing target raises: RFC 6902 treats it as an error
elif op["op"] == "replace":
node[last] # target must already exist
node[last] = op["value"]
return out
doc = {"note": "gift", "tags": ["a"], "items": [{"sku": "A1"}, {"sku": "B2"}]}
append = [{"op": "add", "path": "/tags/-", "value": "x"}]
doc = apply_patch(doc, append) # applied, but the response is lost
doc = apply_patch(doc, append) # client retries
print(doc["tags"]) # ['a', 'x', 'x']: duplicated append
drop = [{"op": "remove", "path": "/note"}]
doc = apply_patch(doc, drop)
try:
apply_patch(doc, drop) # retry of a request that already succeeded
except KeyError:
print("retry reported failure; /note is already gone")
fix = [{"op": "replace", "path": "/items/0", "value": {"sku": "A1", "qty": 3}}]
doc["items"].insert(0, {"sku": "Z9"}) # concurrent insert shifts the array before the retry
doc = apply_patch(doc, fix)
print(doc["items"][:2]) # Z9 was overwritten; A1 is now at index 1, unchanged
A minimal Python applier for add, remove and replace that reproduces the three retry failures: a duplicated '-' append, a remove that errors on replay, and an index replace that overwrites the wrong element after the array shifts.
How do you make PATCH safe to retry?
Guard the patch with test operations
RFC 6902 applies a patch atomically: if any operation fails, none of them take effect. A leading test against a /version field turns a blind append into a conditional one. In the retry above, the first request bumped the version, so the replay's test fails and the second "x" is never added. Testing an array element's identity (for example /items/2/id) before removing or replacing /items/2 does the same for index-based paths, because a shifted array fails the test instead of hitting the wrong element. The cost is that a replayed patch now returns an error even though its first attempt succeeded. The client has to re-read the resource to tell "already applied" from "conflict."
Use ETag with If-Match
The server returns an ETag. The client sends it back in If-Match, and the server responds 412 Precondition Failed if the resource has changed. This works for both formats, including Merge Patch, which has no test equivalent. Under high contention, writers keep receiving 412 responses, and the retry and merge logic moves onto every client.
Add idempotency keys for non-idempotent operations
The client sends a unique key. The server stores the key together with the response and replays that response on retry. The Idempotency-Key header is still an IETF draft, so treat its semantics as your own contract. You also need to decide on storage, an expiry window, and a rule for a reused key that arrives with a different body (usually reject it). Keys stop duplicate requests, but they do not stop two different clients from overwriting each other. Keep conditional requests in place as well.
GET /orders/42 HTTP/1.1
Host: api.example.com
HTTP/1.1 200 OK
ETag: "v7"
Content-Type: application/json
{"id": 42, "version": 7, "tags": ["a"], "items": [{"id": "i-1"}, {"id": "i-2"}, {"id": "i-9"}]}
PATCH /orders/42 HTTP/1.1
Host: api.example.com
Content-Type: application/json-patch+json
If-Match: "v7"
Idempotency-Key: 3f6c2a9e-8b1d-4c7e-a0f2-5d9e1b7c4a10
[
{ "op": "test", "path": "/version", "value": 7 },
{ "op": "test", "path": "/items/2/id", "value": "i-9" },
{ "op": "remove", "path": "/items/2" },
{ "op": "add", "path": "/tags/-", "value": "x" },
{ "op": "replace", "path": "/version", "value": 8 }
]
HTTP/1.1 412 Precondition Failed
Content-Type: application/problem+json
{"title": "Resource has changed", "status": 412}
A JSON Patch request that uses three layers of protection together: leading test operations on the version and on an array element's id, an If-Match precondition that returns 412 when the resource has changed, and an idempotency key so the server can replay the stored response when a client retries.
What should the server-side PATCH contract look like?
Advertise what you accept with Accept-Patch, for example application/merge-patch+json, application/json-patch+json, in responses to OPTIONS and to GET on the resource. Clients can then discover the supported formats without trial and error. RFC 5789 maps failures to specific status codes:
| Condition | Status | Why this code |
|---|---|---|
| Patch format not supported | 415 | Media type rejected; include Accept-Patch |
Patch is well-formed but cannot be applied (failed test, missing path) |
422 | Syntax is fine, semantics fail |
| Patch conflicts with current state | 409 | Retrying the same patch will not help |
If-Match ETag is stale |
412 | Precondition failed; re-read and rebase |
Apply every operation to a copy, or inside a transaction, and commit only if all of them succeed. RFC 6902 requires the patch to be atomic, and a half-applied patch leaves no safe state to retry from. On a single row this costs little. When the resource spans several tables, you need one transaction that holds locks across all of them. When it spans services, you need a saga or an outbox, which makes the operation more complex and slower.
Validate the resulting document against the schema, not just the patch. A patch that is valid on its own can still remove a required field or produce combinations of values that the schema forbids.
You have two options when a retried remove targets a path that no longer exists. Returning an error is correct under RFC 6902. Treating it as a no-op makes retries easier, but it deviates from the RFC, so document it if you choose it.
Field-level authorization is harder with move and copy, because each one reads from one path and writes to another. You must check permissions on both paths. Supporting both formats doubles the surface you have to validate, authorize and test, and that increases development cost.
When should you use JSON Merge Patch vs JSON Patch, and what are the alternatives?
That doubled validation, authorization and testing surface is the main reason to choose one format per resource rather than accepting both.
| Concern | JSON Merge Patch (RFC 7396) | JSON Patch (RFC 6902) |
|---|---|---|
| Expressiveness | Set or remove object members | Add, remove, replace, move, copy, test |
| Idempotency | Idempotent by construction | Depends on operations (array appends and index removals are not) |
| Array handling | Whole array replaced | Element-level edits by index |
| Null handling | null means delete |
Explicit null values allowed |
| Client ergonomics | Send the changed fields | Build an operation list |
| Authorization complexity | Paths map to fields sent | move/copy touch two paths |
| Concurrency needs | If-Match for lost-update protection |
test plus If-Match |
Use Merge Patch for flat or shallow resources where null carries no meaning and arrays are small enough to replace as a whole. Avoid it when clients must store explicit nulls or edit large arrays, because every array change means resending the full array.
Use JSON Patch when you need element-level array edits, moves, explicit nulls or a test precondition. Avoid it for simple forms and public APIs where most clients only change a few scalar fields. In those cases the operation model adds client work without adding anything they need.
There are two alternatives. PUT with full replacement suits small resources that clients already read in full. It is idempotent and needs no patch semantics. For large collections, model them as subresources with their own endpoints, such as POST /orders/{id}/items and DELETE /orders/{id}/items/{itemId}. Each endpoint then has one meaning, its own authorization rule and its own retry behavior. Combined with one patch format for the parent resource, you get fewer code paths to validate and test, and clients can predict what a retry will do.
Who should use these patch formats?
API designers and backend engineers who expose resources that clients update partially. They choose the format, define the status codes, and decide how retries and concurrent writes are handled. Most of the decisions in this article are theirs.
Client and SDK developers whose code retries requests after timeouts or connection resets. They need to know whether a given PATCH is safe to resend blindly, needs an idempotency key, or must be preceded by a fresh read and an If-Match.
Platform and API governance teams who write organization-wide API guidelines. A single documented rule, such as "Merge Patch for configuration-style resources, subresources for large collections, If-Match on every PATCH," removes the same debate from every team that builds an API.
Teams whose resources are small and always read in full have less need for either format. PUT with If-Match gives them idempotent updates and lost-update protection with no patch semantics to implement. Likewise, internal endpoints with a single writer and no automatic retries face few of the failure modes described here, although adding those retries later brings the problems back.
How can choosing the right patch format save engineering time?
Most of the time cost of PATCH comes from bugs that surface late: duplicated array entries after a retry, fields silently deleted by a null, or one client's edit overwritten by another. These are hard to reproduce because they depend on network timing and concurrent writers. Making the right choices up front moves that work from incident investigation to design.
- Idempotent-by-construction formats remove retry code. If a resource uses Merge Patch with
If-Match, clients can resend the same request after a timeout without first checking whether it was applied. There is no deduplication logic to write per endpoint and no "already applied versus conflict" disambiguation for that path. - One format per resource shrinks the test matrix. Each supported format needs its own parser, validation, authorization checks and test cases. Supporting only one halves that work for the resource and halves what reviewers have to reason about.
- Standard formats avoid custom ones. Both RFC 7396 and RFC 6902 are widely implemented, so teams can use an existing, tested library for applying patches instead of designing and documenting a bespoke update format, and client developers already recognize the semantics.
- Subresources for large collections avoid lost-update debugging. When item edits go through their own endpoints, two clients editing different items no longer overwrite each other, so a class of intermittent bug never appears.
- Explicit server contracts reduce support load.
Accept-Patch, consistent 412/409/422 responses and a documented rule for retriedremovelet client developers handle failures from the documentation rather than through trial and error or support requests.
As an illustrative estimate with assumed inputs only: assume an API has 20 PATCH endpoints, and that supporting a second patch format costs about one assumed engineer-day per endpoint for parsing, authorization and tests. Picking a single format per resource would avoid roughly 20 engineer-days of initial work, before counting ongoing maintenance. These inputs are assumptions, not measurements. Substitute your own endpoint count and per-endpoint cost to get a figure for your API.
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 json merge patch vs json patch, 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.