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

📚 Interview question

What counts as a breaking change in an HTTP API? Go beyond removed fields: discuss new enum values, stricter validation, changed defaults, new required fields and behaviour changes. Explain the tolerant reader pattern, how System.Text.Json settings affect it, and how consumer-driven contract tests protect backward compatibility.

Classifies API changes as breaking or safe (including enums, validation, defaults and semantics), the tolerant reader pattern and System.Text.Json settings that support it, and consumer-driven contract testing with Pact.

Senior Theory Advanced backward-compatibility breaking-changes contract-testing pact system-text-json web-api

🎯 Key points

  • Breaking: remove/rename field, change type or format, new required request field, stricter validation, changed status codes or semantics
  • New enum values are breaking for clients with exhaustive switches; document enums as extensible
  • Changing defaults or sort order silently breaks clients relying on them (Hyrum's law); document what isn't promised
  • Safe (with tolerant readers): new optional request fields, new response fields, new endpoints
  • Tolerant reader: ignore unknown members, don't fail on unknown enum values, read only what you need
  • System.Text.Json ignores unknown members by default; UnmappedMemberHandling.Disallow, strict enum converters and RespectRequiredConstructorParameters make clients throw on additive changes
  • Consumer-driven contract tests (Pact) verify the provider against each consumer's real expectations
  • OpenAPI diff (oasdiff) catches structural breaks; contract tests catch behavioural ones

⏱ 30-second answer

A breaking change is anything that makes a correct existing client fail or behave wrongly. Obvious ones are removing or renaming fields and changing types. Less obvious ones: a new required request field, stricter validation, a changed default or sort order, a different status code, and a new enum value that a client's exhaustive switch doesn't handle.

Adding optional fields and endpoints is safe only if clients are tolerant readers: they ignore unknown members and unknown enum values. System.Text.Json ignores unknown members by default, but opting into strict settings, such as UnmappedMemberHandling.Disallow or a plain JsonStringEnumConverter, makes a client throw JsonException on the next additive server change.

I protect compatibility with OpenAPI diffs for structure and consumer-driven contract tests (Pact) for the behaviour each consumer actually relies on, and I document what isn't promised. The trade-off: every observable behaviour becomes a contract, so you decide deliberately what you promise.

🗣 Full answer (senior)

How I would answer this in an interview

"My working definition is: a change is breaking if a client that was correct yesterday fails or does the wrong thing today without changing its code. Removing a field or changing a number to a string is obvious. The ones that catch teams are subtler. Making a request field required, or tightening validation from 100 characters to 50, breaks clients that were sending valid requests. Changing a default page size, the default sort order or the meaning of a status field breaks clients that relied on it, even if the schema is identical. Returning 422 where you used to return 400 breaks error handling. And adding an enum value, say a new order status OnHold, breaks any client with an exhaustive switch or a strict enum deserialiser.

For example, at [company] we [added a PartiallyRefunded payment status]. The schema diff said it was additive, but [a partner's Java client failed deserialising the unknown value] and [their reconciliation job stopped for a morning]. After that we documented every enum in the API as extensible, told clients to map unknown values to a fallback, and treated new enum values as a change requiring notice. That's the tolerant reader pattern: on both sides, read only what you need, ignore unknown members, and don't fail on values you don't recognise. On .NET, System.Text.Json ignores unknown JSON members by default, which is tolerant; but UnmappedMemberHandling.Disallow, required constructor parameters and integer-only enum converters make your own clients brittle.

Structural tools like oasdiff catch removed fields and type changes in CI. They can't see behaviour, so for important consumers I use consumer-driven contract tests with Pact: each consumer publishes the interactions it relies on, and the provider's pipeline verifies them before deploy. The senior point is Hyrum's law: with enough consumers, every observable behaviour is depended on by somebody, so you decide what you promise and test that."


Change classification

Change Breaking? Why
Add optional response field No (tolerant readers) Unknown members ignored
Add optional request field with a default that preserves behaviour No Old clients get old behaviour
Add endpoint or operation No Nobody calls it yet
Remove or rename a field Yes Clients read or send it
Change type or format (int to string, date format) Yes Deserialisation fails
Make a request field required Yes Old requests now fail validation
Stricter validation (shorter max length, narrower range) Yes Previously valid input rejected
Looser validation Usually no But can break clients that relied on the server rejecting input
New enum value in a response Yes for strict clients Exhaustive switches and strict deserialisers fail
Change default (page size, sort, currency) Yes Behaviour changes silently
Change status code or error code Yes Error handling branches differ
Change auth scopes required Yes Calls start returning 403
Performance change (much slower, lower rate limit) Effectively yes Timeouts, 429s

Tolerant reader rules

Side Rule
Client Ignore unknown members; map unknown enum values to Unknown; don't depend on member order; only read fields you use
Server Accept and ignore unknown request members (unless over-posting matters); keep defaults stable; add, don't change

Production example

After adopting Pact for our [four] internal consumers and oasdiff in CI, the provider pipeline blocked [eleven] breaking changes in a year. Eight were structural (caught by oasdiff), three were behavioural (a changed default sort and two stricter validations) that only the contract tests caught.

🔍 What the interviewer is checking

Checks a senior understanding of compatibility beyond the schema: behavioural changes, enums, tolerant readers and automated contract testing.

Green flags

  • Names subtle breaks: stricter validation, new required fields, defaults, enums, status codes
  • Explains the tolerant reader pattern and relevant System.Text.Json settings
  • Uses both structural diffs and consumer-driven contracts
  • Mentions Hyrum's law or documenting what isn't promised

Red flags

  • "Only removing fields is breaking"
  • Strict deserialisation on clients
  • No automated detection; relies on reviewers noticing

📚 Learn in depth

1. Hyrum's law and the real contract

With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviours of your system will be depended on by somebody.

The documented contract is a subset of the observable behaviour:

┌────────────────────── observable behaviour ─────────────────────────┐
│  sort order, timing, field order, error wording, default page size  │
│   ┌─────────────────── documented contract (OpenAPI) ───────────────┐         │
│   │  paths, schemas, status codes, documented error codes     │         │
│   └───────────────────────────────────────────────────────┘         │
└──────────────────────────────────────────────────────────────────┘

Two defences: make the documented contract explicit about what is not promised ("order of results is unspecified unless sort is given"), and make undocumented behaviour stable anyway where it's cheap (always apply a default sort).

2. Enums: the classic trap

Adding a value is additive for the schema but breaking for clients that:

  • use a strict enum type in a generated client (some generators throw on unknown values),
  • switch exhaustively and throw in default,
  • store the value in a database column with a check constraint.

Mitigations: document enums as extensible (OpenAPI 3.1 has no built-in flag; use a description or an x-extensible-enum extension), send them as strings, and tell clients to map unknown values to a fallback. On the .NET client side, a custom JsonConverter that maps unknown strings to Unknown is a tolerant reader.

3. System.Text.Json and tolerance

Setting Default Effect on tolerance
Unknown JSON members Ignored Tolerant
UnmappedMemberHandling.Disallow Off Throws on any new field: brittle client
JsonStringEnumConverter Not on by default Unknown string values throw JsonException
RespectRequiredConstructorParameters (.NET 9+) Off Missing constructor parameters throw
RespectNullableAnnotations (.NET 9+) Off Nulls in non-nullable members throw
required members Enforced Missing member throws

On the server, strictness on requests (reject unknown members) protects against over-posting and typos, but means a client adding a field for a newer server version fails against an older one. Pick deliberately.

4. Consumer-driven contract testing

consumer test (PactNet) ──► pact file: "GET /orders/42 returns { id, status }"
           │ publish
           ▼
     Pact Broker / PactFlow ──► provider pipeline verifies every consumer's pact
                                     against the real API (with provider states)
           ▲                                      │
   can-i-deploy? ◄───────── results ──────────────┘

The consumer specifies only what it uses, so the provider is free to change everything else. PactNet (v5) runs in xUnit; can-i-deploy gates releases on both sides. It works best for internal consumers you can talk to; for unknown public consumers, rely on oasdiff, conservative change rules and long deprecation windows.

5. Making a breaking change non-breaking

Expand and contract:

  1. Expand: add the new field (totalMoney) alongside the old (total); write both.
  2. Migrate: tell clients, measure who still reads the old one if you can.
  3. Contract: remove the old field in the next major version.

The same pattern applies to validation: log what would fail under the stricter rule for a few weeks before enforcing it.

Try it yourself

  1. Deserialise JSON with an extra member using default JsonSerializerOptions, then with UnmappedMemberHandling.Disallow, and compare.
  2. Add a new enum string to a payload and deserialise with JsonStringEnumConverter; then write a converter that falls back to Unknown.
  3. Write a PactNet consumer test for one endpoint and verify it against a local provider.
  4. Run oasdiff breaking on two versions of a spec where you made a field required.
  5. List every default in one of your APIs (page size, sort, currency, time zone) and check which are documented.

💻 Code

A tolerant .NET client: ignores unknown members and maps unknown enum values instead of throwing.

// Client/TolerantEnumConverter.cs
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Shop.Client;

public enum OrderStatus { Unknown = 0, Open, Paid, Shipped, Cancelled }

// Unknown strings (e.g. a new "OnHold") become Unknown instead of a JsonException.
public sealed class TolerantEnumConverter<TEnum> : JsonConverter<TEnum> where TEnum : struct, Enum
{
    public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
        reader.TokenType == JsonTokenType.String
        && Enum.TryParse<TEnum>(reader.GetString(), ignoreCase: true, out var value)
            ? value
            : default; // Unknown = 0

    public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) =>
        writer.WriteStringValue(value.ToString());
}

public sealed record OrderDto(
    int Id,
    [property: JsonConverter(typeof(TolerantEnumConverter<OrderStatus>))] OrderStatus Status);

public static class Demo
{
    // Defaults are tolerant: unknown members are ignored. Don't add UnmappedMemberHandling.Disallow on a client.
    private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web);

    public static OrderDto Parse() =>
        JsonSerializer.Deserialize<OrderDto>(
            """{ "id": 42, "status": "OnHold", "newFieldAddedLater": true }""", Options)!;
    // => OrderDto { Id = 42, Status = Unknown }
}

A consumer-driven contract test with PactNet: the consumer states only what it relies on.

// Consumer.Tests/OrdersApiPactTests.cs
using PactNet;
using PactNet.Matchers;
using Xunit;

namespace Shop.Client.Tests;

public sealed class OrdersApiPactTests
{
    private readonly IPactBuilderV4 _pact = Pact.V4("mobile-app", "orders-api", new PactConfig())
        .WithHttpInteractions();

    [Fact]
    public async Task Get_order_returns_id_and_status()
    {
        _pact.UponReceiving("a request for order 42")
                .Given("order 42 exists")
                .WithRequest(HttpMethod.Get, "/v1/orders/42")
             .WillRespond()
                .WithStatus(System.Net.HttpStatusCode.OK)
                .WithJsonBody(new { id = 42, status = Match.Type("Open") }); // only fields we use

        await _pact.VerifyAsync(async ctx =>
        {
            using var http = new HttpClient { BaseAddress = ctx.MockServerUri };
            var order = await http.GetFromJsonAsync<OrderDto>("/v1/orders/42");
            Assert.Equal(42, order!.Id);
        });
    }
}

⚠ Common mistakes

  • Mistake: Treating only removed fields as breaking. Why it is wrong: Stricter validation, new required fields, changed defaults and changed status codes break correct clients too. Instead: Use a written classification table in your API guidelines.
  • Mistake: Adding enum values without notice. Why it is wrong: Strict deserialisers and exhaustive switches fail. Instead: Document enums as extensible from day one and announce new values.
  • Mistake: Turning on UnmappedMemberHandling.Disallow in client code. Why it is wrong: Every additive server change breaks the client. Instead: Keep the tolerant default on clients; be strict only where it protects the server.
  • Mistake: Relying on an OpenAPI diff alone. Why it is wrong: It can't see behavioural changes like a new default sort. Instead: Add consumer-driven contract tests for important consumers.
  • Mistake: Writing Pact tests that assert the whole response. Why it is wrong: The provider can't change anything; the tests become a second, brittle schema. Instead: Assert only the fields and behaviour the consumer uses, with type matchers.
  • Mistake: Enforcing a stricter validation rule immediately. Why it is wrong: Clients sending previously valid data start failing. Instead: Log would-be failures first, contact affected clients, then enforce in a new version or after notice.
  • Mistake: Not documenting what isn't promised. Why it is wrong: Clients depend on incidental behaviour (Hyrum's law). Instead: State explicitly that unsorted order and undocumented fields can change.

🏛 Senior insight: trade-offs

Backward compatibility is a cost you pay continuously to avoid paying a much larger one at every release. The cheapest place to buy it is in the initial design: extensible enums, string-encoded money, optional fields with stable defaults, and documentation of what isn't promised. After that, automation (oasdiff, Pact) makes the policy enforceable rather than aspirational.

Option When it fits Cost When not to
oasdiff breaking check in CI Every API with an OpenAPI document Near zero Never skip it
Consumer-driven contracts (Pact) Internal consumers you can coordinate with Broker, provider states, consumer buy-in Unknown public consumers
Expand and contract Renames and type changes Temporary duplication Truly incompatible models (new major version)
Log-then-enforce for validation Tightening rules on live APIs Weeks of delay Security fixes that must ship now

I measure it by breaking changes caught before production versus reported by clients, and by how many releases needed a new major version.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions detecting breaking changes with an OpenAPI diff Why: Checks the CI implementation of structural compatibility checks.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

  2. When: Candidate says a real break needs a new version Why: Checks versioning strategy and when a new major version is justified.
    How to answer

    There are four common schemes: URL segment (/v1/orders), query string (?api-version=1.0), a request header (api-version: 1.0) and a media type parameter (Accept: application/json;v=1.0). In ASP.NET Core the Asp.Versioning library (10.x for .NET 10) implements all four through an ApiVersionReader, and can combine them.

    • URL segment is the most visible, easiest to route, cache and test in a browser, which is why most public APIs use it.
    • Header and media type keep URIs stable but are invisible in logs and links and easy for clients to forget.

    The senior part: version only for breaking changes. Additive changes (new optional fields, new endpoints) should ship without a version bump, because every live version is a support cost you carry for years.

  3. When: Candidate lists stricter validation as a breaking change Why: Checks practical migration technique: measure, communicate, enforce.
    How to answer

    Ship the rule in log-only mode first: evaluate it, record a metric and log the client id when a request would fail, but still accept it. After a few weeks you know exactly which clients send non-conforming data. Contact them, give a date, optionally return a warning header, then enforce in the next major version or after the notice period. Security-driven rules are the exception and ship immediately with direct communication.

🛠 Real-world problems: how you handle them

New enum value stopped a partner's reconciliation
Situation
A payments API on Azure served [N] partners. We added a `PartiallyRefunded` status to `GET /payments/{id}`; oasdiff classified it as non-breaking and it shipped in a routine release.
Signals
The next morning [a partner] reported their reconciliation job had failed overnight. Our Application Insights showed normal 200s; there was no server-side error, only an unusual spike in retries from that partner's client id.
Investigation
The partner shared their stack trace: their generated Java client threw on the unknown enum value. Reviewing our OpenAPI document showed the enum had no extensibility note, and our guidelines didn't classify new enum values at all. A search of API Management analytics showed [two] other partners reading that field.
Resolution
Immediate: mapped `PartiallyRefunded` to the old `Refunded` value for that partner's subscription via a version-specific mapping while they patched their client. Long term: marked every enum as extensible in the spec, published guidance for tolerant enum handling, and made new enum values a notified change with 30 days' notice.
Prevention
API guidelines now classify new enum values as requiring notice; a Spectral rule requires an `x-extensible-enum` note on every enum; Pact contracts with the three largest partners verify status handling; the changelog flags enum additions.

How to tell it (STAR)

**S:** We added a new payment status and a partner's reconciliation job failed overnight because their generated client threw on the unknown value, even though our diff tool said the change was additive. **T:** I owned the API and needed to restore the partner and stop this class of break. **A:** I added a per-subscription mapping to the old value within [two hours], then marked every enum as extensible in the spec, wrote tolerant-reader guidance with a client example, added a Spectral rule, and made enum additions a notified change. **R:** The partner recovered the same day, and in the following [year] we added [five] enum values with no client incidents.

↩ Usually asked after

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me