API Versioning, Deprecation and Backward Compatibility Questions
Evolving an API without breaking existing consumers: versioning schemes (URI, header, media type, semantic versioning), classifying breaking versus non-breaking changes including behavioural ones such as defaults and error text, deprecation and sunset policy and timelines (including accelerated retirement), running multiple versions concurrently, and planning consumer migrations at scale including SDK, partner, mobile and long-tail client impact. Also covers finding who still calls an old version, catching accidental breaks with contract checks in CI, expand-then-contract evolution of fields and stored data, gradual rollout with per-version monitoring, and compatibility between independently deployed services, streams and libraries. Covers compatibility guarantees across REST, GraphQL and gRPC consumers. Excludes general API surface design, payload and OpenAPI schema design, protobuf field-level mechanics, writing the notices themselves, rate limiting, gateways and database schema migration.
Your widely used API needs new fields now and you plan to drop a rarely used field later. How do you evolve the contract without breaking anyone, and how do you decide when the old field can finally go?
Sample Answer
The idea in plain words
Evolve in two separate moves. First expand: add the new fields in a way that cannot change anything an existing client sees. Later contract: remove the old field, but only after a published notice period has passed and evidence shows nobody still depends on it. Adding is a code change you can ship today. Removing is a decision that needs a date and a measurement, and the measurement is harder than it first looks.
Scenario (assumed for the worked numbers): an Orders API with 3,200 active API keys. Product wants a new delivery_window object on the order response and an optional gift_message on order creation. Engineering wants to retire a rarely used legacy_ref field.
Step 1: add the new fields without breaking anyone
- Make every addition optional and additive.
delivery_windowis a new response property; old clients that ignore unknown properties are unaffected.gift_messageis an optional request property. - Choose defaults that reproduce old behaviour. If
gift_messageis omitted the server behaves exactly as before (no gift card). Changing the default of an existing parameter is a breaking change; a default for a brand-new parameter is not, as long as "absent" means "do what we always did". - Never add a new required request field to the existing endpoint. Requiring it breaks every client that does not send it. If the new capability truly needs new input, make it optional now and enforce later through a new version.
- Gate the rollout with a feature flag, but do not use flags to change the contract per client. A flag (a server-side on/off switch) lets you ship the code dark (deployed but switched off), turn on 1 percent of traffic, watch error rates by client, and switch off instantly. It controls the rollout of an implementation. Long-lived per-client flags that make responses differ are a hidden version system with no documentation.
- Document it: mark both fields optional in the OpenAPI description, say when
delivery_windowcan be absent, and add a changelog line. - Check strict readers before shipping: run the official SDKs against a fixture response that contains the new property, because a strict deserializer (code that turns JSON into typed objects and refuses properties it has no field for) is the usual failure.
Step 2: signal the removal
Publish the plan with dates, and put machine-readable signals on every response that carries the old field's endpoint (RFC 9745 defines the Deprecation response header; RFC 8594 defines Sunset). Mark the field deprecated in the OpenAPI description and in SDK docs.
Illustrative response headers (the dates are assumptions):
HTTP/1.1 200 OK
Content-Type: application/json
Deprecation: @1806883200
Sunset: Mon, 03 Apr 2028 00:00:00 GMT
Link: <https://developers.example.com/changes/legacy-ref>; rel="deprecation"; type="text/html"
Deprecation carries the date the field was deprecated as a Unix timestamp prefixed with @ (here 2027-04-05 00:00:00 UTC). To get the number, take the date 2027-04-05 00:00:00 UTC and count the seconds since 1970-01-01 00:00:00 UTC (the Unix epoch): that is 1806883200. Sunset is an HTTP-date (the fixed text date format HTTP uses) after which the feature is expected to stop. The Link header with rel="deprecation" points at human-readable documentation. Headers are per response, not per field, so they say "something on this endpoint is deprecated" and the linked page says which field.
Step 3: decide when the old field can go
Rule: remove on the later of two dates: the end of the notice period, and the first day after 30 consecutive days with no evidence of use. State both so neither is skipped.
The measurement depends on which side carries the field.
- A request field (clients send
legacy_ref): the server sees every use. Log the API key and the presence of the field. This is cheap and exact. - A response field (clients read
legacy_ref): the server cannot see whether a client reads it. Use indirect evidence. Start with what you already own: telemetry from your official SDKs (usage data the client libraries report, such as which accessors, the getter methods for each field, the application calls). Then add the one test that also covers clients you cannot see, a removal canary. A canary is a small group tried first so that a problem harms few: switch the field off for a handful of keys that opted in through a setting on the key in the developer dashboard, then watch for effects. A client that was reading the field shows up as a rise in that key's failed follow-up calls, a support ticket or a partner's error report, because your server cannot see the break directly. Further evidence: contract tests from consumers, partner confirmation for the largest integrations, and a code search of public repositories where feasible. For a GraphQL API, field-level usage is visible directly.
Worked timeline (every figure is an assumption)
Notice period: 52 weeks (364 days) for external consumers. Announce Monday 2027-04-05, so the earliest removal is 2027-04-05 plus 364 days = Monday 2028-04-03. Request-field usage measured by distinct API keys sending legacy_ref in the trailing 30 days (the 30 days ending on the measurement date), out of 3,200 active keys:
| Week | Date | Keys still sending | Share of 3,200 keys |
|---|---|---|---|
| 0 | 2027-04-05 | 14 | 14 / 3,200 = 0.4375% |
| 12 | 2027-06-28 | 6 | 6 / 3,200 = 0.1875% |
| 26 | 2027-10-04 | 2 | 2 / 3,200 = 0.0625% |
| 39 | 2028-01-03 | 0 | 0% |
The week-39 count is a trailing 30-day measure, so the usage condition is met from 2028-01-03. That is before the notice period ends, so the later date wins: removal on 2028-04-03, not earlier. If one key were still sending at week 51, the field would not go on that date; the owner contacts that key, and either it migrates or a tracked exception (a recorded, dated permission with an owner) keeps the field on for that key only.
The percentages above are small because the field is rarely used, but 14 of 3,200 keys is still 14 integrations that will break. A low share is a reason to contact those 14 directly, not a reason to skip the notice period.
Monitoring and rollback
Run the removal as a staged change: first stop returning the field to a 1 percent canary of opted-in keys, then 10 percent, then everyone, watching error rate by key and by SDK version at each step. Keep a switch that restores the field instantly. After removal, a request that still sends legacy_ref should be ignored for a grace period (a stated stretch of time during which old input is still tolerated) or rejected with a clear 400 problem response naming the field; pick one and publish it.
Common mistakes
- Using only server logs to prove a response field unused.
- Reading a low usage percentage as permission to skip the notice period.
- Flipping the default of an existing parameter and calling it additive.
- Treating a feature flag as a substitute for a version.
You want to add an optional field to a JSON response that thousands of clients consume. Is that safe without a version bump? What could still break, and what do you check on the server, in SDKs and in documentation before shipping?
Sample Answer
The idea in plain words
Yes, adding an optional field to a JSON response is normally safe without a version bump, because well-behaved clients follow the tolerant reader pattern: read the fields you need and ignore the rest. It is not safe unconditionally. With thousands of clients, some will be strict, some will pass the whole object somewhere that does care, and some will depend on behaviour you never documented (Hyrum's law: with enough users, every observable behaviour gets depended on by someone). So the answer is "safe by default, verify the exceptions before shipping".
What could still break
- Strict deserializers (code that turns JSON into typed objects and refuses properties it has no field for). Whether unknown properties are rejected depends on the library and its settings. As two examples: Jackson, a Java JSON library, documents its
FAIL_ON_UNKNOWN_PROPERTIESfeature as enabled by default (checked against the 2.17 source), so an unknown property throws unless the application turns the feature off; Go's standardencoding/jsondocuments that unknown keys are ignored by default and rejects them only when the caller usesDecoder.DisallowUnknownFields. The point is only that some parsers reject unknown fields unless configured otherwise. Generated clients built with strict settings, and clients that validate the response against a JSON Schema (a machine-readable description of allowed JSON shapes) withadditionalProperties: false(a setting meaning no properties beyond the listed ones are allowed), fail on the new field. - Whole-object pass-through. A client that spreads the response (copies every property of it, as in
{...response}in JavaScript) into a database insert or a downstream API call now sends a column or property the destination does not know. - Name collisions. The new name equals a property the client adds to the same object, or a reserved word in a generated client. Example: a client that decorates each order with its own
delivery_windowvalue before saving it now has the server's value overwrite, or be overwritten by, its own. - Integrity over the whole body. Anything that hashes or signs the raw response, or snapshot tests that compare the full body, changes when a field appears.
- Size and limits. More bytes per response raises bandwidth and can hit client or proxy size limits.
- Semantic surprises. A field that is sometimes absent and sometimes
nullis a trap:{"id":"ord_1"}and{"id":"ord_1","delivery_window":null}mean different things to code that checks whether the key exists. A number larger than JavaScript can hold exactly is another: JavaScript stores numbers as 64-bit floating point, which represents whole numbers exactly only up to 9,007,199,254,740,992 (2 to the power 53), so a larger identifier in a new field is silently rounded in a JavaScript client even though the field is "just new".
Worked size check (assumptions: the new property is "delivery_window":{"start":"2027-05-01T09:00:00Z","end":"2027-05-01T12:00:00Z"}, 50,000,000 responses per day, no compression):
- Property text is 79 characters, plus 1 comma separator = 80 bytes per response (ASCII, one byte per character).
- Extra volume per day = 80 bytes x 50,000,000 = 4,000,000,000 bytes = 4.0 GB (decimal gigabytes).
That is modest for most services and worth knowing if the fleet is mobile or metered.
What to check before shipping
On the server
- Make the field optional in the contract and keep one stable type. Decide and document whether absence,
nulland empty mean different things. - Run the contract tests (automated checks that responses match the documented shapes) and any recorded-response comparison; update the golden files (saved expected response bodies that tests compare against) deliberately.
- Roll out to a small share first (a staged rollout, for example enabling the field for a few API keys and then more) and watch error rates by API key and by SDK version (the
User-Agentheader usually carries the SDK name and version), not just overall.
In SDKs
- Parse a fixture response (a saved sample response) that already contains the new property with the official SDKs. Fix any strict mode, release the SDK that models the field, and publish it before or with the API change.
- Check generated model classes for the collision cases above.
In documentation
- Add the field to the reference as optional, say when it appears, give an example, and add a changelog entry.
- State the compatibility rule near the top of the docs: "responses may gain new properties at any time; ignore properties you do not recognise". Publishing that rule on day one is what makes later additions safe, because it turns a surprise into a documented behaviour.
Illustrative response after the change
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 45
{"id":"ord_123","status":"paid","total":2500}
becomes
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 125
{"id":"ord_123","status":"paid","total":2500,"delivery_window":{"start":"2027-05-01T09:00:00Z","end":"2027-05-01T12:00:00Z"}}
The first body is 45 bytes and the second is 45 + 80 = 125 bytes, matching each Content-Length header, because the new property adds the 80 bytes counted above.
Recommendation
Ship it without a version bump after the SDK fixture test and a staged rollout. Bump a version only if the field changes the meaning of existing fields or if monitoring shows strict clients you cannot move. If a particular partner is strict, give that partner the field only on request, for example through a documented request parameter, rather than versioning everyone.
Common mistakes
- Assuming "optional" means no client can break.
- Testing only with your own SDK and not a strict third-party parser.
- Forgetting that cached copies keep the old shape until they expire, so clients can see both shapes during rollout.
- Shipping the field with no documented statement that new properties may appear.
For each of these changes to a live API, decide whether it breaks existing clients and what you would do instead if it does: removing a field, renaming a field, adding a field, and adding or changing an enum value.
Sample Answer
The idea in plain words
A change breaks a client if a client that was correct yesterday is wrong today without touching its own code. The server sends responses and clients send requests, so the same edit can be safe in one direction and breaking in the other. Of the four changes asked about, only adding an optional field is clearly safe, and it has a condition: clients must behave as tolerant readers, meaning they read the fields they need and ignore any property they do not recognise. Removing, renaming and changing an enum all need a different route: add the new thing alongside the old one, move clients across, then remove the old one later (often called expand then contract, or a parallel change).
Assumed example throughout: an Order response with fields id, status (values pending, paid, shipped) and total.
The four changes
| Change | Breaks existing clients? | Why | Do this instead |
|---|---|---|---|
| Remove a response field | Yes | Clients that read it get undefined, null or an exception | Deprecate, measure who still uses it, give the notice period, then remove |
| Rename a response field | Yes | A rename is a removal plus an addition, so readers of the old name break | Add the new name next to the old one, return both, deprecate the old, remove after the notice period |
| Add a field | Response field: usually no. Request field: no if optional, yes if required | Tolerant readers ignore unknown properties; a required new request field makes every existing request invalid | Keep new request fields optional with a default that reproduces old behaviour |
| Add an enum value | Response (server sends): can break. Request (client sends): no | A client that handles only the values it knew may crash, mislabel or loop on the new one | Do not emit the new value to old clients; describe it in a sibling field (a new field beside the old one) or gate it on a capability the client declares (for example a request parameter saying it understands the new value) |
| Change an enum value (rename, merge, split) | Yes in both directions | Clients compare against the old string or number | Add the new value, accept both on input, keep emitting the old one until clients migrate |
Nuance on inputs: removing an enum value a client may still send breaks that client, while adding a value to an enum the server accepts is safe. The asymmetry is the reason to classify each change by where it appears.
Plan for each, step by step
Remove a field
- Mark it deprecated in the contract and send
DeprecationandSunsetheaders (RFC 9745 and RFC 8594). - Measure usage. A request field is visible in server logs; a response field needs SDK telemetry (usage data your official client libraries report back, such as which fields the application reads) or partner confirmation.
- Remove after the announced date and when usage is zero or accepted exceptions are handled.
Assume the response also carried a rarely used legacy_ref. Illustrative before and after:
{"id":"ord_1","status":"paid","total":2500,"legacy_ref":"A-77"}
{"id":"ord_1","status":"paid","total":2500}
Illustrative headers on the deprecated endpoint while the notice period runs:
Deprecation: @1803859200
Sunset: Wed, 01 Mar 2028 00:00:00 GMT
Link: <https://developers.example.com/changes/legacy-ref>; rel="deprecation"; type="text/html"
Deprecation is the date deprecation started (here 2027-03-01 00:00:00 UTC, written as @ and a Unix timestamp), Sunset is the date after which the endpoint is expected to stop working, and the Link with rel="deprecation" points a human at the explanation. They apply to the whole response, so the linked page says which field is going.
Rename a field (total to amount)
- Release: return both
totalandamountwith the same value; accept both on input if clients send it. - Move: update the SDKs and docs to use
amount; deprecatetotal. - Contract: remove
totalafter the notice period.
A rename done in one step is the classic accidental break. Illustrative bodies for the three phases:
{"id":"ord_1","status":"paid","total":2500}
{"id":"ord_1","status":"paid","total":2500,"amount":2500}
{"id":"ord_1","status":"paid","amount":2500}
The first is before the change, the second is the release and move phase (both names, same value), and the third is after the contract phase. A client reading total works in the first two and breaks in the third, which is why the third waits for the notice period.
Add a field
- Add as optional in the contract with a default for missing input.
- Tell consumers in the docs that responses may gain properties.
- Test the official SDKs against a response with the extra property.
Add or change an enum value
Suppose a refund state is needed and the existing status enum is pending, paid, shipped. A client with switch(status) and a default: throw branch would crash if the server begins sending refunded.
- Option 1: publish from the first release that the enum is open ("clients must treat unknown values as unknown") and send the new value only after clients have had time to comply.
- Option 2: keep
statusunchanged and add a sibling field (a new field beside the old one) such asrefund_state, so old clients never see a newstatusvalue. - Option 3: return the new value only to clients that declared support, for example through a newer API version or a documented request parameter.
I would pick option 2 for a widely used API, because it needs no client cooperation, and option 1 as the contract rule for every enum created from now on.
Worked check on the example
Assumptions: 10,000 orders reach the API per day and 2 percent of orders ever reach the refund state. Orders exposed to the new status value = 10,000 x 0.02 = 200 per day. A client with a strict switch fails on those 200 orders per day and works for the other 9,800. That is why the failure shows up late and unevenly: nothing looks wrong until the first refund is read, so the rollout should be watched by error rate per client after the first refunds appear, not only in the first minutes.
Common mistakes
- Treating a rename as a small tidy-up.
- Thinking "adding" is always safe and forgetting that a new required request field is a breaking addition.
- Adding enum values to an output without ever having told clients to expect unknown values.
- Deleting the old field on the date promised without checking usage.
A property that is returned on most responses must change from a scalar to a different type, and you also want to add nested fields. Propose a plan that keeps old clients working and tells you which clients are affected during rollout.
Sample Answer
The idea in plain words
Changing a field from a scalar (a single number or string) to an object is a breaking change: a client that does price + tax or stores price in an integer column fails the moment it receives {...} instead of 1999. So the plan is never to retype the field in place for everyone. Instead, give old and new shapes different "addresses" for a while (a new field name, or a shape the client has to ask for), keep the old shape as the default, measure who has moved, and only change the default under a published notice. The second ask, knowing which clients are affected, is solved by making each client's shape choice visible to the server.
Plan, in the order I would do it
Running example (an assumption): GET /products/9 returns "price": 1999, meaning 1999 minor currency units (cents). The new shape is an object with amount, currency and a display string, and more nested fields will follow.
Step 1. Add, do not replace
Add a new field, pricing, holding the object. Keep price as the scalar. Both are returned. Old clients read price and ignore pricing, which is safe for any client that ignores unknown fields. All future nested fields go inside pricing, so you can grow it without touching price again. The pair price and pricing is only a stepping stone: carrying a deprecated scalar next to a differently named object forever is confusing, which is why product eventually wants one clean name, price, holding the object (step 2). In GraphQL (a typed query language where clients name the fields they want) this is the same move: add pricing: Money, mark price with @deprecated(reason: "Use pricing"). A GraphQL client can rename a result for its own code with an alias, as in query { product(id: "p_9") { id cost: pricing { amount } } }, which returns the object under the key cost. The alias changes only the name in that one client's response; the server schema still needs the pricing field to exist, so aliases are not a way for the server to evolve and the field must still be added. In REST, mark price deprecated in the OpenAPI description and send the Deprecation header (RFC 9745).
Step 2. If the final name must be price, make the new shape opt-in
When product wants the object under the name price, do it through client capability negotiation: the client declares what it understands, and the server answers accordingly. Two standard mechanisms are content negotiation (client and server agree on a representation using request headers; defined in RFC 9110, the HTTP semantics standard) with a vendor media type (a format name in the vnd. namespace, made up by the API owner) in Accept, or a version header or parameter the client sends.
Illustrative exchange, same URL, two clients:
GET /products/9 HTTP/1.1
Host: api.example.com
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept
{"id":"p_9","name":"Desk lamp","price":1999,"pricing":{"amount":1999,"currency":"USD","display":"19.99"}}
GET /products/9 HTTP/1.1
Host: api.example.com
Accept: application/vnd.example.v2+json
HTTP/1.1 200 OK
Content-Type: application/vnd.example.v2+json
Vary: Accept
{"id":"p_9","name":"Desk lamp","price":{"amount":1999,"currency":"USD","display":"19.99"}}
In server code, a serializer is the piece that turns an internal object into the JSON the client receives; the plan needs two of them, one per shape. Fields explained: Accept is the client's statement of formats it can handle. Content-Type is what the server actually sent. Vary: Accept tells caches (CDNs, content delivery networks that keep copies of responses near users, and browsers) that the response differs by Accept. Without it, a cache can store the first answer it sees under the URL: if an opted-in client fetches /products/9 first, the cache keeps "price":{...}, and the next client that sent plain application/json is handed that object, so its price + tax fails even though the server is correct. application/vnd.example.v2+json is a made-up vendor media type for this illustration. The amount 1999 shows as 19.99 because 1999 / 100 = 19.99; 1999 is in minor currency units, the smallest unit of the currency (cents for USD). A client that sends Accept: */* (accept anything) gets the default shape, the old one, because it has not asked for the new one.
Step 3. Gate the rollout with a flag per client
Put the new default behind a feature flag (a runtime switch, here keyed by API key) so that moving a client is a data change, not a deploy, and moving it back is instant.
Step 4. Detect who is affected
The server can see what it sends, but not whether a client reads or parses price. Use several signals together. The first is the primary one, because it is an explicit statement by the client; the others cover keys that never opted in:
- Who has opted in: every request carrying the v2
Acceptis a known-ready client. Everyone else, until proven otherwise, is an unknown reader. Log the shape served per API key. - SDK version: the
User-Agentheader carries the SDK name and version. Maintain a table of SDK versions that parse the new shape. - Key-by-key canary: serve the new shape to a small set of volunteer keys first and watch their error rate and their retry or support traffic. A strict parser shows up as an error spike for that key.
- Consumer contract tests: partners publish what they parse, so a failing contract names the partner before production.
- Direct outreach: for the largest keys, ask.
Worked rollout (all figures are assumptions)
3,000 active API keys. The canary (a small group moved first, here chosen from volunteers) is 1 percent of keys: 3000 x 0.01 = 30 keys. If error rates by key stay at baseline for a week, widen to 10 percent: 3000 x 0.10 = 300 keys. A cohort is simply the group of keys moved together at one step, so a failure can be traced to the step that caused it. At each step the log shows how many keys are on v2 and which keys still send the plain application/json Accept. The default only changes in a new major version under the published notice period, and keys that never opted in are contacted before that date. Any key whose error rate rises goes back to the old shape through the flag.
The judgment
I would add pricing now (step 1) and deliver the nested fields through it, because it is additive, costs one release and needs no negotiation. I would add the opt-in price object only if the product requirement really is the name price. The risk of negotiation is operational: caches must Vary correctly, docs must show both shapes, and you carry two serializers until the old one is retired.
This plan is a small illustration. A real rollout must also handle clients that send Accept: */*, SDKs generated from the old description, webhooks and exports that embed the same field, and stored data that downstream systems copied.
Common mistakes
- Changing the type in place and calling it a minor release.
- Forgetting
Vary: Accept, so a cache mixes shapes. - Treating "no errors in server logs" as proof that no client reads the field.
- Opting everyone in at once, so a failure cannot be attributed to a cohort.
A developer platform serves both REST and GraphQL APIs to many SDK consumers. How does versioning and deprecation differ between the two, how do you keep SDKs from breaking, and what would your rollback plan be for a change that slips through?
Sample Answer
The idea in plain words
REST and GraphQL put the contract in different places, so "breaking" and "deprecated" work differently. In REST (resources at URLs, usually returning JSON) the server decides the shape of each response, so a change to that shape reaches every client, and you version the shape (a URL like /v2/, or a media type). In GraphQL (clients send a query naming exactly the fields they want, against a typed schema) each client only depends on the fields it names, so you can usually evolve one schema continuously: add fields freely, mark old ones deprecated, watch which fields are still requested, and remove a field only when nobody asks for it. SDKs (software development kits, the client libraries you publish) sit on top of either and add their own breakage risks, mainly strict parsing of responses.
GraphQL notation used below: a schema is the typed list of everything a client may ask for. In schema text, Int is a nullable integer (the value may be missing) and Int! is a non-null integer, because the ! (the bang) means the server promises a value. Money is an example custom object type, for instance {amount, currency}. @deprecated(reason: "...") is a directive, an annotation on a field that marks it as scheduled for removal. Introspection is the built-in way to ask a GraphQL server what its schema contains, which tools use to show deprecation warnings. An operation name is the label on a query, as in query ProductPage { ... }, which lets the server log which screen or feature sent it. The nearest nullable parent is the closest enclosing object whose type allows null. A persisted query is a query stored on the server and requested by its ID.
How versioning and deprecation differ
| Question | REST | GraphQL |
|---|---|---|
| What is the contract? | The OpenAPI description plus observed behaviour | The schema plus the queries real clients send |
| Who decides what a client receives? | The server (fixed response shape) | The client (it names the fields) |
| Is adding a field safe? | Usually, if clients ignore unknown fields | Yes for queries (a client never receives a field it did not ask for) |
| How do you signal deprecation? | Deprecation and Sunset response headers (RFC 9745, RFC 8594), docs, Link header | The @deprecated(reason: "...") directive in the schema; it applies to fields, arguments, input fields and enum values and shows in introspection and tooling |
| How do you know who still uses the old thing? | Request logs for inputs; response fields are invisible to the server | Per-field usage is visible: the server sees every field in every query |
| When do you cut a new version? | When a shape change cannot be made additively | Rarely; evolve in place and remove after usage is zero |
| Error signalling | HTTP status codes | Usually HTTP 200 with an errors array in the body, so monitoring status codes alone misses failures |
A REST call returns the fixed shape the server chose. A GraphQL call names the fields it wants, so the server can count them:
query ProductPage {
product(id: "p_9") { id name oldPrice }
}
Every use of oldPrice is attributable to the operation named ProductPage.
GraphQL errors arrive inside a 200 response. Illustrative: a field fails, and the HTTP status is still 200 OK, so a dashboard that counts only status codes sees nothing:
HTTP/1.1 200 OK
Content-Type: application/json
{"data": {"product": {"id": "p_9", "price": null}},
"errors": [{"message": "price could not be resolved", "path": ["product", "price"]}]}
Nullability is a GraphQL-specific trap. Marking an output field non-null (Int to Int!) looks like a harmless tightening, but if the server ever fails to produce a value, GraphQL sets the nearest nullable parent to null, so one missing value can erase a whole object in the response. Going the other way (Int! to Int) breaks typed SDKs that generated a non-optional property. For arguments the direction reverses: making an argument required (Int to Int!) breaks callers, while relaxing it is safe. Treat both directions as reviewed changes, and prefer adding a new field to changing the nullability of an existing one.
To see the null spreading, take the same failure as above but with price: Money! (non-null). The field cannot be null, so the null moves up to the nearest nullable parent, here product, and the whole object is lost:
{"data": {"product": null},
"errors": [{"message": "price could not be resolved", "path": ["product", "price"]}]}
With a nullable price only the one value was missing (the previous response). That is the sense in which one missing value can erase a whole object.
Keeping SDKs from breaking
- Write the tolerance rules into every SDK: ignore unknown fields, map unknown enum values to an
UNKNOWNmember rather than throwing, and treat optional fields as optional. Most SDK breakage is a strict parser meeting a harmless addition. - Pin and test a matrix: in CI (the automated build pipeline) run the last several released versions of each SDK against the candidate server build. A failure names the SDK version.
- Consumer-driven contracts: the SDK and key partners publish the exact requests and responses they rely on, and the provider's pipeline replays them on every build. This catches payload changes (a type, a format, an error shape) that a schema diff does not describe, and names which consumer would break.
- Identify clients: the SDK sets a
User-Agentheader with its name and version (and GraphQL clients send a named operation), so the server can break down errors and deprecated-field usage by SDK version. - For GraphQL, register operations: typed SDKs usually generate fixed queries, which you can store as persisted queries. The registry then lets CI validate a candidate schema against every stored operation; the program in the worked example shows that check.
- Ship the SDK update before the server removal: an SDK release that stops using the deprecated field must exist and have time to spread before the field is removed.
Worked example: removing Product.oldPrice (all figures are assumptions)
Schema after the first step: oldPrice: Int @deprecated(reason: "Use price.amount"), with a new price: Money. Over a trailing 30 days, the server logs show 2,500 distinct operations. Of these, 37 select oldPrice: 37 / 2,500 = 1.48%, coming from 3 client names. The field cannot go yet, but the list of 3 clients is exact.
The CI check works on the stored operations. The program below holds three of them and a candidate schema that has dropped oldPrice; it reports every operation that selects a field the candidate no longer has, and repeats the 37 / 2,500 arithmetic.
# Stored operations (persisted queries): name -> fields each one selects.
stored_operations = {
"ProductPage": ["Product.id", "Product.name", "Product.oldPrice"],
"ProductList": ["Product.id", "Product.name", "Product.price"],
"CartSummary": ["Cart.id", "Cart.total"],
}
candidate_schema = {"Product.id", "Product.name", "Product.price", "Cart.id", "Cart.total"} # oldPrice removed
broken = {name: [f for f in fields if f not in candidate_schema]
for name, fields in stored_operations.items()}
for name, missing in broken.items():
print(f"{name}: {'ok' if not missing else 'BREAKS, missing ' + ', '.join(missing)}")
print("CI result:", "fail" if any(broken.values()) else "pass")
print(f"{37 / 2500:.2%} of 2500 operations select oldPrice")
Output:
ProductPage: BREAKS, missing Product.oldPrice
ProductList: ok
CartSummary: ok
CI result: fail
1.48% of 2500 operations select oldPrice
Read-out: ProductPage selects Product.oldPrice, which the candidate schema lacks, so the check names that operation and fails the pipeline before the field is removed; the other two stored operations are unaffected. The final line is the 1.48 percent from the paragraph above. After those 3 move, the count reads 0 for the 30-day window and the field can be removed after the stated notice period.
The REST equivalent is GET /v1/products/9 returning old_price. The server cannot see who reads old_price, so it adds price and the Deprecation header now, uses SDK telemetry and consumer contracts to estimate use, and removes the field in a new version or after a small test group: first hide the field for a handful of keys that agreed to try it, watch their error rate, and only then remove it for everyone.
Rollback plan for a change that slips through
- Detect: alert on error rate per SDK version and, for GraphQL, per operation name and per field path from the
errorsarray, since status codes will still read 200. Example rule, illustrative: page when any SDK version's error rate is more than 2 times its 7-day baseline for 5 minutes in a row. With a baseline of 0.4%, that threshold is 2 x 0.4% = 0.8%. - Contain first: ship risky changes behind a feature flag (a runtime switch) and release by canary (a small share of traffic first). Rollback is then flipping the flag or shifting traffic back, which takes minutes and needs no deploy.
- Restore the old shape: if a field was removed or retyped, bring it back through the flag, because adding a field back is itself additive.
- Handle data written during the bad window: if the new version accepted writes in a new format, the old version must be able to read them, so the data change is made backward compatible before the API change ships. Where that was not done, roll forward with a fix instead of back.
- Communicate and learn: tell the affected consumers, find why the contract check missed it, and add a contract test for the case.
This detection rule is a simple illustration based on one ratio. A real alert also needs a minimum traffic floor, handling for consumers with tiny volumes, and separate treatment of client errors caused by consumer bugs.
Common mistakes
- Believing GraphQL needs no versioning policy: it needs deprecation periods, usage tracking and nullability discipline.
- Watching HTTP status only on a GraphQL API.
- Removing a deprecated field because server logs show no use, when the field is a REST response field that logs cannot show.
- Releasing an SDK that throws on unknown enum values.
Running the code
Paste the program into a file and run it with Python 3.12; it needs no extra packages and prints exactly the output shown.
That is every published API Versioning, Deprecation and Backward Compatibility question for Full-Stack Developer so far. Browse the other topics in this category, or practice this one interactively.