📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between PUT and PATCH? Explain full replacement vs partial update, JSON Patch (RFC 6902) vs JSON Merge Patch (RFC 7396), how you tell a missing field from an explicit null, and show how you implement PATCH in ASP.NET Core on .NET 10.

PUT as full replacement vs PATCH as partial update, JSON Patch vs JSON Merge Patch, the missing-vs-null problem, and implementing PATCH in ASP.NET Core 10 with System.Text.Json, validation and concurrency.

Mid-Level Coding Intermediate aspnet-core json-merge-patch json-patch patch system-text-json web-api

🎯 Key points

  • PUT replaces the whole representation at the URI; omitted fields are reset; idempotent
  • PATCH sends only the changes; not guaranteed idempotent (merge patch setting values usually is, JSON Patch add to an array is not)
  • JSON Patch (RFC 6902, application/json-patch+json): ordered, atomic ops add/remove/replace/move/copy/test
  • JSON Merge Patch (RFC 7396, application/merge-patch+json): partial document, null means remove, arrays replaced whole
  • Typed DTOs can't tell missing from null; use JsonElement/JsonNode, or an Optional<T> wrapper
  • .NET 10: Microsoft.AspNetCore.JsonPatch.SystemTextJson gives JsonPatchDocument<T> on System.Text.Json
  • Patch a DTO, validate input rules on the DTO and business rules on the resulting entity, then save
  • Use If-Match/ETag from rowversion so concurrent PATCHes don't lose updates (412, 428 when missing)

⏱ 30-second answer

PUT replaces the whole resource with the representation sent, so anything omitted is reset; it is idempotent. PATCH sends only the changes.

Two standard PATCH formats exist:

  • JSON Merge Patch (RFC 7396): send a partial document; null means remove. Simple, but can't express array edits or set a value to null.
  • JSON Patch (RFC 6902): an ordered list of operations (replace, add, remove, test). Precise, but verbose.

The hard part is missing vs null: a normal C# DTO can't tell them apart, so you read JsonElement/JsonNode or use JsonPatchDocument<T> (System.Text.Json-based since .NET 10). The trade-off: merge patch is friendlier for clients; JSON Patch is safer for arrays and conditional (test) updates.

🗣 Full answer (senior)

How I would answer this in an interview

"PUT means 'here is the full new representation, store it at this URI'. If the client leaves out notes, the server should clear notes. That makes PUT idempotent and simple to reason about, but clients must first GET the whole resource and send it all back, and older clients that don't know about a new field will wipe it. PATCH means 'apply these changes'. RFC 5789 doesn't define the format, so you pick a media type. JSON Merge Patch, application/merge-patch+json, is a partial document: fields present are set, null removes. JSON Patch, application/json-patch+json, is an array of operations like replace /status or test /version, applied in order and atomically.

The implementation trap is missing versus null. If I bind merge patch into a C# record, {\"notes\": null} and {} both give Notes == null, so I can't tell 'clear it' from 'leave it'. I either read the body as JsonElement and check TryGetProperty, or use JSON Patch. On .NET 10 there's Microsoft.AspNetCore.JsonPatch.SystemTextJson, so JsonPatchDocument<T> no longer needs Newtonsoft. Either way I patch a DTO, not the EF entity, validate the result, then map it, and I require If-Match with the ETag from a rowversion so two editors don't silently overwrite each other.

For example, at [company] our [customer profile] endpoint used PUT, and an older mobile app version that didn't know about the new marketingConsent field reset it to false on every save, about [3,000] profiles a week. We moved to merge patch for profile edits, added If-Match, and the overwrites stopped. The mistake I see is using PUT for partial updates, or patching entities directly, which is an over-posting hole."


PUT vs PATCH

PUT PATCH
Semantics Replace whole representation Apply a set of changes
Idempotent Yes Not guaranteed
Payload Full resource Changes only
Unknown/new fields Old clients wipe them Untouched
Create if missing Allowed (client-chosen id) Possible but unusual

Merge Patch vs JSON Patch

JSON Merge Patch (RFC 7396) JSON Patch (RFC 6902)
Media type application/merge-patch+json application/json-patch+json
Shape Partial document Array of operations
Remove a field "field": null {"op":"remove","path":"/field"}
Set a value to null Impossible replace with null
Array edits Replace whole array Add/remove by index, - for append
Conditional No test operation
Client friendliness High Lower

Production example

Moving [profile edits] from PUT to merge patch with If-Match cut the average request size from [4 KB to 300 bytes] and eliminated the [~3,000 weekly] accidental resets caused by older app versions; 412 responses (about [0.2%] of edits) showed where real concurrent edits happened and the app now reloads and asks the user.

🔍 What the interviewer is checking

Checks whether the candidate understands PUT vs PATCH semantics, the two PATCH formats, and the practical implementation issues (missing vs null, over-posting, concurrency).

Green flags

  • States that PUT replaces and resets omitted fields
  • Names both RFC 7396 and RFC 6902 and their trade-offs
  • Explains missing vs null and a concrete way to solve it
  • Patches a DTO and validates the result
  • Adds If-Match/rowversion for concurrency

Red flags

  • Uses PUT and PATCH interchangeably
  • Applies JsonPatchDocument directly to EF entities
  • Doesn't consider concurrent edits

📚 Learn in depth

1. Why PUT is dangerous for evolving resources

v1 client knows: { name, email }
v2 server has:   { name, email, marketingConsent }

v1 client: GET -> { name, email, marketingConsent: true }  (ignores unknown field)
           PUT    { name, email }                          (field dropped)
server:    marketingConsent reset to default (false)

This is why many public APIs (e.g. Microsoft Graph) use PATCH for updates and reserve PUT for idempotent create-or-replace with client-chosen ids.

2. JSON Merge Patch semantics (RFC 7396)

target:  {"name":"Ana","phone":"0400 000 000","address":{"city":"Perth","postcode":"6000"}}
patch:   {"phone":null,"address":{"city":"Fremantle"}}
result:  {"name":"Ana","address":{"city":"Fremantle","postcode":"6000"}}

Objects merge recursively; any non-object value (including arrays) replaces; null deletes. Applying the same merge patch twice gives the same result, so merge patch is idempotent in practice, though the method isn't guaranteed to be.

3. JSON Patch semantics (RFC 6902)

[
  { "op": "test",    "path": "/status", "value": "Draft" },
  { "op": "replace", "path": "/status", "value": "Submitted" },
  { "op": "add",     "path": "/tags/-", "value": "urgent" }
]

Paths are JSON Pointers (RFC 6901). Operations apply in order and the whole patch must fail if any operation fails. test gives a lightweight precondition. add to /tags/- appends, so repeating it appends twice: not idempotent.

4. JSON Patch in .NET 10

Until .NET 9, JsonPatchDocument<T> lived in Microsoft.AspNetCore.JsonPatch, required Newtonsoft.Json and AddNewtonsoftJson(). .NET 10 adds Microsoft.AspNetCore.JsonPatch.SystemTextJson, a System.Text.Json-based implementation (namespace Microsoft.AspNetCore.JsonPatch.SystemTextJson) with ApplyTo(target, onError). As of late 2026 it does not support dynamic/ExpandoObject targets, and you should still apply it to a DTO, not an entity. Because the patch can touch any path, restrict which paths are allowed or apply to a DTO that only contains editable fields.

5. The missing-vs-null problem

{}                  -> Notes: null   (meant: leave as is)
{"notes": null}     -> Notes: null   (meant: clear it)

Options:

Technique How Trade-off
JsonElement / JsonNode body TryGetProperty("notes", out var v) Manual mapping, no compile-time safety
Optional<T> wrapper + custom converter Optional<string?> Notes with HasValue Extra type, converter to maintain
JSON Patch Explicit operations Verbose for clients

6. Concurrency

PATCH is read-modify-write on the server. Without a precondition, two edits interleave and one is lost. Expose the SQL Server rowversion as an ETag, require If-Match, set it as the EF Core original value (entry.Property(e => e.RowVersion).OriginalValue = ...), and map DbUpdateConcurrencyException to 412. Return 428 Precondition Required if If-Match is missing on a resource that needs it.

7. Validation

Apply the patch to a DTO, then validate the DTO (DataAnnotations, FluentValidation or .NET 10 Minimal API validation), then map to the entity inside the transaction. Return 400/422 with ValidationProblemDetails if the patched result is invalid, and 400 if the patch document itself is malformed.

Try it yourself

  1. Build a PUT endpoint, then simulate an old client that omits a field and watch it reset.
  2. Implement merge patch with JsonElement and write tests for {}, {"notes":null} and {"notes":"x"}.
  3. Add Microsoft.AspNetCore.JsonPatch.SystemTextJson and apply a patch with a failing test operation; check nothing changes.
  4. Run two concurrent PATCH requests with the same If-Match value in an integration test and assert one gets 412.
  5. Compare payload sizes for PUT vs PATCH on a 50-field resource.

💻 Code

Merge patch with explicit missing-vs-null handling, ETag concurrency and validation of the patched DTO.

// Program.cs (.NET 10)
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<ProfileStore>();
var app = builder.Build();

app.MapMethods("/profiles/{id:int}", ["PATCH"], async (
    int id, HttpRequest request, ProfileStore store, CancellationToken ct) =>
{
    if (request.ContentType?.StartsWith("application/merge-patch+json") != true)
        return Results.StatusCode(StatusCodes.Status415UnsupportedMediaType);

    var current = store.Get(id);
    if (current is null) return Results.NotFound();

    // Optimistic concurrency: the client must send the ETag it last saw.
    var ifMatch = request.Headers.IfMatch.ToString();
    if (string.IsNullOrEmpty(ifMatch)) return Results.StatusCode(StatusCodes.Status428PreconditionRequired);
    if (ifMatch != current.ETag) return Results.StatusCode(StatusCodes.Status412PreconditionFailed);

    using var doc = await JsonDocument.ParseAsync(request.Body, cancellationToken: ct);
    var patch = doc.RootElement;

    // Missing property = leave alone; explicit null = clear (where allowed).
    var updated = current.Data with
    {
        DisplayName = patch.TryGetProperty("displayName", out var dn) ? dn.GetString() ?? current.Data.DisplayName : current.Data.DisplayName,
        Phone       = patch.TryGetProperty("phone", out var ph) ? (ph.ValueKind == JsonValueKind.Null ? null : ph.GetString()) : current.Data.Phone,
        MarketingConsent = patch.TryGetProperty("marketingConsent", out var mc) ? mc.GetBoolean() : current.Data.MarketingConsent
    };

    if (string.IsNullOrWhiteSpace(updated.DisplayName) || updated.DisplayName.Length > 100)
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["displayName"] = ["Display name is required and must be 100 characters or fewer."]
        });

    var saved = store.Save(id, updated);
    request.HttpContext.Response.Headers.ETag = saved.ETag;
    return Results.Ok(saved.Data);
});

app.Run();

public sealed record ProfileDto(string DisplayName, string? Phone, bool MarketingConsent);
public sealed record Versioned(ProfileDto Data, string ETag);

public sealed class ProfileStore
{
    private readonly Dictionary<int, Versioned> _items = new()
    {
        [1] = new(new ProfileDto("Ana", "0400 000 000", true), "\"1\"")
    };
    private int _version = 1;
    public Versioned? Get(int id) => _items.GetValueOrDefault(id);
    public Versioned Save(int id, ProfileDto dto) => _items[id] = new(dto, $"\"{++_version}\"");
}

JSON Patch with the System.Text.Json implementation added in .NET 10 (package Microsoft.AspNetCore.JsonPatch.SystemTextJson), in an MVC controller:

using Microsoft.AspNetCore.JsonPatch.SystemTextJson;
using Microsoft.AspNetCore.Mvc;

[ApiController, Route("orders")]
public sealed class OrdersController(IOrderService orders) : ControllerBase
{
    [HttpPatch("{id:int}")]
    [Consumes("application/json-patch+json")]
    public async Task<IActionResult> Patch(int id, [FromBody] JsonPatchDocument<EditOrderDto> patch, CancellationToken ct)
    {
        var dto = await orders.GetEditableAsync(id, ct);   // a DTO with only editable fields
        if (dto is null) return NotFound();

        patch.ApplyTo(dto, error => ModelState.AddModelError(error.AffectedObject?.ToString() ?? "patch", error.ErrorMessage));
        if (!ModelState.IsValid || !TryValidateModel(dto)) return ValidationProblem(ModelState);

        await orders.UpdateAsync(id, dto, ct);              // maps DTO -> entity, saves with rowversion check
        return NoContent();
    }
}

public sealed class EditOrderDto { public string Status { get; set; } = ""; public List<string> Tags { get; set; } = []; }
public interface IOrderService
{
    Task<EditOrderDto?> GetEditableAsync(int id, CancellationToken ct);
    Task UpdateAsync(int id, EditOrderDto dto, CancellationToken ct);
}

⚠ Common mistakes

  • Mistake: Using PUT for partial updates. Why it is wrong: PUT means replace; clients that omit fields (or old clients unaware of new ones) wipe data. Instead: PATCH for partial changes, PUT only with full representations.
  • Mistake: Binding merge patch to a normal record. Why it is wrong: Missing and null both become null, so you either clear fields by accident or can never clear them. Instead: JsonElement/JsonNode, an Optional<T> wrapper, or JSON Patch.
  • Mistake: Applying JsonPatchDocument<T> to an EF Core entity. Why it is wrong: Clients can patch any path, including IsAdmin, TenantId or navigation properties (over-posting). Instead: Patch an edit DTO, validate it, then map.
  • Mistake: No concurrency check on PATCH. Why it is wrong: Concurrent edits silently overwrite each other. Instead: ETag from rowversion and If-Match; 412 on mismatch, 428 when missing.
  • Mistake: Still pulling in Newtonsoft.Json just for JSON Patch on .NET 10. Why it is wrong: Two serialisers with different settings cause subtle casing and converter bugs. Instead: Use Microsoft.AspNetCore.JsonPatch.SystemTextJson.
  • Mistake: Accepting application/json for PATCH without saying which format. Why it is wrong: Clients guess the semantics. Instead: Require and document application/merge-patch+json or application/json-patch+json.
  • Mistake: Validating only the incoming patch, or only the DTO. Why it is wrong: A well-formed patch can produce an invalid resource, and field-level DTO checks miss cross-field and business rules (e.g. a shipped order can't change its address). Instead: Validate input rules on the patched DTO, then enforce business rules on the resulting entity or domain object before saving.
  • Mistake: Treating JSON Patch array indexes as stable. Why it is wrong: remove /lines/2 removes whatever is at index 2 now, which may differ if another client changed the array. Instead: Combine with test or If-Match, or address array items by id through sub-resources.

🏛 Senior insight: trade-offs

Most teams should default to JSON Merge Patch for simple field edits because clients find it natural, and reach for JSON Patch only when they need array edits, explicit nulls or test preconditions. Whatever format you choose, the safety comes from the same three things: patch a DTO not an entity, validate the result, and require If-Match.

The other senior consideration is evolution. PUT couples clients to the full shape of the resource, so adding a field becomes a breaking change for old clients that round-trip the representation. PATCH lets the resource grow without breaking anyone.

Option When it fits Cost When not to
PUT Small, stable resources; client-chosen ids; idempotent upserts Full payloads, old clients wipe new fields Resources that evolve often
Merge Patch Form-style edits of scalar fields Can't set null, arrays replaced wholesale Array manipulation
JSON Patch Array edits, explicit nulls, conditional ops Verbose, path-level authorisation needed Simple mobile/web forms
Task endpoints (POST /orders/42/submit) State transitions with business rules More endpoints Plain data edits

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency of PUT vs PATCH Why: Checks safe and idempotent method semantics more broadly
    How to answer

    GET reads, POST creates or runs a command, PUT replaces a resource at a known URI, PATCH partially updates it, DELETE removes it, HEAD is GET without the body, and OPTIONS asks what is allowed (used by CORS preflight).

    • Safe (no intended state change): GET, HEAD, OPTIONS.
    • Idempotent (repeating has the same effect as doing it once): the safe methods plus PUT and DELETE.
    • POST and PATCH are neither, unless you make them so.

    These properties are a contract that caches, proxies, browsers and retry policies rely on: a gateway may retry a timed-out PUT but must not blindly retry a POST. Breaking the contract, such as changing state on GET, causes duplicate side effects and crawler disasters.

  2. When: Candidate mentions rowversion or If-Match Why: Checks optimistic vs pessimistic concurrency from .NET against SQL Server
    How to answer

    Optimistic concurrency assumes conflicts are rare: read the row with its rowversion, and when saving run UPDATE ... WHERE Id = @id AND RowVersion = @original. If 0 rows are affected, someone else changed it: return 409/412 and let the user reload or merge. No locks are held between read and write, so it suits web forms with user think time.

    Pessimistic concurrency locks first: inside a short transaction, SELECT ... WITH (UPDLOCK, HOLDLOCK) so no one else can take the row until you commit; for job queues, UPDLOCK, READPAST lets workers skip claimed rows. sp_getapplock locks a logical name (e.g. 'invoice-run-2026-11') when there's no single row to lock.

    The trade-off: optimistic costs retries under contention; pessimistic costs blocking and deadlock risk.

  3. When: Candidate mentions over-posting or binding entities Why: Checks they spot entity binding and error handling problems in a code review
    How to answer

    Ranked by severity: (1) over-posting: binding the EF entity lets a client set fields they shouldn't (IsApproved, Role, Price, Id, navigation properties), a security hole. (2) information disclosure: returning ex.Message can leak SQL, server names or personal data. (3) broken HTTP semantics: 200 with success: false makes failures look like successes to monitoring, retries, caches and clients. (4) swallowed exceptions: the catch-all hides bugs and usually doesn't log. (5) hand-rolled validation: inconsistent and duplicated. The rewrite: a request DTO with only the allowed fields, DataAnnotations with [ApiController] (or FluentValidation), explicit mapping to the entity, proper status codes (201, 400, 404, 409) via ProblemDetails, and global exception handling with UseExceptionHandler instead of try/catch in every action.

🛠 Real-world problems: how you handle them

Old mobile app versions reset a new consent field through PUT
Situation
A [customer profile] API used PUT for edits. A new `marketingConsent` field shipped in [v5] of the app, but [30%] of users were still on [v4], which round-tripped only the fields it knew about.
Signals
Support tickets from customers who had opted in but stopped receiving offers; a daily report showed [~3,000] consent flips from true to false per week; no errors in Application Insights because every request returned 200.
Investigation
Queried the audit table for consent changes and joined to request telemetry by operation id; the changes all came from requests with the [v4] `User-Agent`. Reproduced with an HTTP file sending the v4 payload: the server mapped the missing property to `false`.
Resolution
Immediately: the PUT handler kept the existing `marketingConsent` when the property was absent (a temporary compatibility shim) and the affected profiles were restored from the audit table. Then: added `PATCH /profiles/{id}` with `application/merge-patch+json`, `If-Match` with a rowversion ETag, and moved the apps to it; PUT was deprecated with a Sunset header.
Prevention
API guideline: partial updates use PATCH; contract tests that replay old client payloads against new server versions; an alert on unusual rates of consent changes; the Privacy Act consent audit kept as the source of truth.

How to tell it (STAR)

**S:** Our [profile API] used PUT, and when we added a marketing consent field, older app versions started resetting it to false, about [3,000] customers a week. **T:** I needed to stop the data loss, repair affected records and fix the contract so it couldn't recur. **A:** I traced the changes through the audit table and request telemetry to the [v4] user agent, shipped a shim that ignored missing fields on PUT, restored the records from the audit log, then designed a merge-patch endpoint with If-Match concurrency and contract tests that replay old payloads. **R:** Accidental resets dropped to zero within [a day], payloads shrank by [~90%], and the replay tests have since caught [two] other breaking changes before release.

↩ Usually asked after

More in HTTP Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me