What counts as a breaking change in an internal API?

Microservice API versioning protects one thing: callers that were built against yesterday's contract and will not be redeployed on your schedule. A change is breaking if any existing consumer can fail, or quietly produce wrong results, after the provider ships it. Internal callers count. Sharing a monorepo does not mean every service deploys at the same time.

Change Breaking? Why
Remove or rename a response field Yes Consumers reading it get nulls or crash
Change a field's type or meaning (e.g. cents → dollars) Yes Parses fine and computes wrong; the hardest kind to detect
Tighten validation on requests Yes Payloads that used to be accepted now get rejected
Change error body format or status codes Yes Retry and fallback logic branches on these
Add an optional request field No Old callers omit it and get the old behaviour
Add a response field No, if readers are tolerant Strict deserializers reject unknown fields

Most version bumps are avoidable. Providers can change additively: add fields, endpoints and enum handling, and never repurpose an existing field. Consumers can act as tolerant readers: ignore unknown fields, rely only on what they use, and treat unrecognised enum values as a known fallback. When both sides follow these rules, the contract can grow for a long time without a new version.

Where the version identifier lives, in a header or in the path, matters less than having a written compatibility policy. A new version number does not permit breaking consumers. Callers still on the old version need a supported migration path and a deprecation window.

from dataclasses import dataclass
from enum import Enum


class OrderStatus(Enum):
    PENDING = "pending"
    SHIPPED = "shipped"
    UNKNOWN = "unknown"  # explicit fallback for values the provider adds later

    @classmethod
    def parse(cls, raw: str) -> "OrderStatus":
        try:
            return cls(raw)
        except ValueError:
            # Unrecognised enum value: degrade to a known state instead of crashing
            return cls.UNKNOWN


@dataclass
class Order:
    id: str
    amount_cents: int
    status: OrderStatus


def read_order(payload: dict) -> Order:
    # Tolerant reader: pick out only the fields this consumer uses.
    # Unknown keys are ignored rather than rejected.
    return Order(
        id=payload["id"],
        amount_cents=int(payload["amount_cents"]),
        status=OrderStatus.parse(payload.get("status", "unknown")),
    )


payload = {
    "id": "ord_123",
    "amount_cents": 4999,
    "status": "on_hold",
    "tracking_url": "",
}

print(read_order(payload))

A tolerant-reader consumer in Python that ignores unknown response fields and maps unrecognised enum values to a fallback, so additive provider changes do not require a new API version.

When should you introduce a new API version?

Use a new version only when you need a breaking change and cannot express it additively. In practice, that means one of the following:

  • The meaning of existing data changes. For example, a total field moves from integer cents to a structured money object. You could add a new field next to the old one, but if both must stay consistent forever, a clean new version is often easier to reason about.
  • A field or endpoint must be removed for a reason that cannot wait for a long deprecation, such as a security or data-protection problem with what it exposes. Even then, removal under a new version gives callers an explicit migration step instead of a sudden failure.
  • Request validation must get stricter, and some existing callers send payloads the new rules would reject.
  • The error contract changes, such as new status codes for conditions that callers already handle.

Do not use a new version in these cases:

  • The change is additive. New optional request fields, new response fields, and new endpoints belong in the current version if consumers are tolerant readers.
  • Only one consumer needs the change and it can be coordinated. If a single team owns the only caller, a coordinated two-step change (add the new field, migrate the caller, remove the old field) is usually cheaper than running two versions.
  • You want to signal a release. Version numbers in an API describe contract compatibility, not release cadence. Bumping them for marketing or milestone reasons forces every caller to evaluate a migration that does nothing for them.

If you are unsure, run the schema diff and contract tests described later in this article. If nothing breaks for any deployed consumer, you do not need a new version.

How does API versioning work end to end?

Whichever strategy you choose, versioning has the same moving parts. Knowing them makes the header-versus-URL trade-offs in the next sections easier to follow.

  1. The provider publishes contracts per version. Each supported version has its own schema, such as an OpenAPI document, describing requests, responses, and errors. Usually only the newest version receives new features. Older versions receive fixes only.
  2. The caller declares which version it was built against. It does this through the URL path (/v2/orders/42) or through a request header (Api-Version: 2 or a versioned media type in Accept).
  3. Something resolves the version. Either the gateway, ingress, or mesh routes the request to a version-specific backend, or a single service reads the version and dispatches to a version-specific handler.
  4. The handler serves the matching representation. Often several versions share one internal data model, and thin adapters translate between that model and each version's request and response shape. This keeps business logic in one place and limits per-version code to the translation layer.
  5. The response confirms what was served. With media-type versioning, the server echoes the version in Content-Type. Responses from deprecated versions also carry deprecation signals so callers learn about the migration through their own tooling.
  6. Telemetry records version and caller. Logs, metrics, and traces tag each request with the version and the calling service, so the provider knows who depends on each version.
  7. Old versions are retired. Once telemetry shows no remaining callers, the route, handler, adapters, and tests for that version are deleted.

Steps 2, 3, and 6 are where URL and header versioning differ. The rest is the same for both.

How do URL path versioning and header versioning work?

With URL path versioning, the version is part of the resource address: GET /v1/orders/42 and GET /v2/orders/42 are different URLs. The gateway or ingress matches on the path prefix and forwards each prefix to its own upstream. That upstream can be a separate deployment or a separate route table inside one service. Because routing happens before any application code runs, v1 and v2 can run side by side, scale independently, and be rolled back separately. The version also appears in access logs, traces, and copied curl commands without extra configuration.

Header versioning keeps one URL, /orders/42, and moves the version into request metadata. There are two common forms:

  • Custom header: for example, Api-Version: 2.
  • Media-type versioning: the version goes in Accept, as in Accept: application/vnd.example.orders.v2+json. The server echoes the chosen media type in Content-Type.

Either the gateway routes on the header value, or a single service reads it and dispatches to a version-specific handler, usually through a lookup from version to handler. This keeps resource identity stable across versions. The cost is that the version is less visible: it doesn't appear in the URL, so it only shows up where headers are logged.

If any shared cache sits in the path, such as a CDN, a caching proxy, or a gateway cache, responses must include Vary: Api-Version or Vary: Accept. Without it, the cache keys only on the URL and can serve a cached v1 body to a v2 caller. That failure is silent and hard to reproduce. Path versioning avoids this problem because each version already has its own URL and therefore its own cache key.

import { createServer, IncomingMessage, ServerResponse } from "node:http";

// One handler per supported version; both strategies dispatch through this table.
type Handler = (id: string) => object;
const handlers: Record<string, Handler> = {
  "1": (id) => ({ id, total: 1999 }),                                // v1: integer cents
  "2": (id) => ({ id, total: { amount: 1999, currency: "EUR" } }), // v2: structured money
};

// Header versioning: custom header first, then media type in Accept, else default to v1.
function versionFromHeaders(req: IncomingMessage): string {
  const custom = req.headers["api-version"];
  if (typeof custom === "string") return custom.trim();
  const m = /application\/vnd\.example\.orders\.v(\d+)\+json/.exec(req.headers.accept ?? "");
  return m ? m[1] : "1";
}

createServer((req: IncomingMessage, res: ServerResponse) => {
  const path = (req.url ?? "/").split("?")[0];               // strip the query string
  const byPath = /^\/v(\d+)\/orders\/([^/]+)$/.exec(path);  // curl /v2/orders/42
  const byHeader = /^\/orders\/([^/]+)$/.exec(path);         // curl -H 'Api-Version: 2' /orders/42
  if (!byPath && !byHeader) { res.statusCode = 404; return res.end(); }

  const version = byPath ? byPath[1] : versionFromHeaders(req);
  const id = byPath ? byPath[2] : byHeader![1];
  const handler = handlers[version];
  if (!handler) { res.statusCode = 400; return res.end(`unsupported version: ${version}`); }

  // Same URL can return different bodies, so shared caches must key on these headers too.
  // Path-versioned URLs are already distinct cache keys and don't need Vary.
  if (!byPath) res.setHeader("Vary", "Accept, Api-Version");
  // Echo the media type actually served so clients can confirm which version they got.
  res.setHeader("Content-Type", `application/vnd.example.orders.v${version}+json`);
  res.end(JSON.stringify(handler(id)));
}).listen(8080);

A minimal Node.js HTTP service that resolves the API version from either the URL path prefix or the Api-Version/Accept headers, dispatches through a version-to-handler table, and sets Vary only on header-versioned responses.

Which strategy makes it easier to see who is still calling v1?

With URL versioning, the version appears in every place a request leaves a record. Default access log formats include the request path, so a count of /v1/ lines grouped by client address answers "who still calls v1?" without any setup. Gateway metrics that are labeled by route or path template split by version automatically. Trace spans usually record the HTTP route as well, so you can filter traces by version in your tracing backend.

Header versioning hides that signal. Most default log formats, metric labels, and span attributes leave out arbitrary request headers. A v1 call and a v2 call look the same until you configure each layer to record the header. That means three separate changes: add the header to the access log format, add it as a label on request metrics, and set it as a span attribute in your tracing instrumentation. If you skip one of them, that layer cannot tell versions apart. The version alone is also not enough. You need the caller's identity, such as a workload identity from mTLS or a service-name header that your platform sets, so that a v1 count turns into a list of teams to contact. The example below records both fields.

Header versioning also costs more during debugging. You cannot paste a URL into a browser to reproduce a v2 response. A link copied from a chat thread loses the header. An engineer reading basic logs during an incident cannot see which contract the failing request expected. Requests without the header add one more case, which the next section covers. Every one of these problems can be solved, but each one requires deliberate setup, while URL versioning provides the same visibility without any.

map $http_api_version $api_version {
    ""      "unset";
    default $http_api_version;
}

map $ssl_client_s_dn $caller_identity {
    ""      $http_x_caller_service;
    default $ssl_client_s_dn;
}

log_format api_versioned escape=json
  '{"time":"$time_iso8601","method":"$request_method","uri":"$uri",'
  '"status":$status,"api_version":"$api_version",'
  '"caller":"$caller_identity","request_time":$request_time}';

upstream orders_backend {
    server 10.0.12.5:8080;
}

server {
    listen 443 ssl;
    server_name orders.internal.example;
    ssl_certificate        /etc/nginx/tls/server.crt;
    ssl_certificate_key    /etc/nginx/tls/server.key;
    ssl_client_certificate /etc/nginx/tls/internal-ca.crt;
    ssl_verify_client      optional;

    access_log /var/log/nginx/orders_access.json api_versioned;

    location / {
        proxy_pass
    }
}

An nginx access log format that writes the API-Version header and the caller's identity (taken from the mTLS certificate subject, or a platform-set header as a fallback) as JSON fields, so you can group v1 traffic by calling service.

How do gateways, ingress controllers, and service meshes handle each approach?

Path-prefix rules are the common denominator. Every gateway, ingress controller, and mesh can match /v1/ and /v2/ and send them to different backends, and the rule sits in plain sight in the route config. Header-match routing is also widely supported, but it only works if every hop between caller and service forwards the header unchanged.

Concern URL path versioning Header versioning
Routing rule Path prefix match Header match, usually with a fallback route
Header stripped by an intermediary Not applicable Request falls through to the default version
HTTP caching Version is part of the cache key Needs Vary on the version header
Resource identity One resource, multiple URLs One URL per resource

The stripped-header case causes the most trouble. A proxy with a header allowlist, or a client library that rebuilds requests, can drop X-API-Version without any error. The request reaches the default version and returns a 200 with a different shape or different semantics. Nothing returns an error and no alert fires, so the client simply processes the wrong data. This is a correctness bug, and it can go unnoticed for weeks.

Caches cause a related failure. If a response depends on a header and the service does not send Vary for it, a shared cache can serve a v2 body to a v1 caller. Adding Vary fixes the mismatch but splits the cache into one entry per version.

URL versioning has its own cost: resource identity. /v1/orders/123 and /v2/orders/123 refer to the same order through two different URLs. Hypermedia links, URLs stored in databases, and event payloads all carry the version with them. That keeps v1 alive long after its callers have migrated, unless someone rewrites the stored references.

Mixing strategies across teams costs more than either approach on its own. The platform team must maintain both kinds of routing rules, and any call chain that crosses teams has to translate between the two conventions.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: orders
spec:
  parentRefs:
    - name: internal-gateway
  hostnames:
    - orders.internal.example.com
  rules:
    # URL versioning: the version is visible in the path and in the route config.
    - matches:
        - path: { type: PathPrefix, value: /v2/ }
      backendRefs:
        - { name: orders-v2, port: 8080 }
    - matches:
        - path: { type: PathPrefix, value: /v1/ }
      backendRefs:
        - { name: orders-v1, port: 8080 }
    # Header versioning: this only works if every hop forwards X-API-Version unchanged.
    - matches:
        - headers:
            - { type: Exact, name: X-API-Version, value: "2" }
      backendRefs:
        - { name: orders-v2, port: 8080 }
    # Fallback: a request whose header was stripped lands here and gets a 200 from v1.
    # That is the silent correctness bug. A safer option is to point this rule at a
    # small backend that returns 400 "version required" and to count those responses.
    - matches:
        - path: { type: PathPrefix, value: / }
      backendRefs:
        - { name: orders-v1, port: 8080 }

A Gateway API HTTPRoute that routes by path prefix and by header match, where the catch-all rule silently sends any request missing its version header to v1.

What should happen when a request has no version?

Routing unversioned requests to the newest version looks convenient, but it turns every release into a change the caller never agreed to. A service that has called /orders without a version for a year was implicitly tested against v2. When v3 ships and becomes the default, that caller starts receiving the new response shape on the next deploy, with no code change on its side and no warning in its own CI. Internal consumers are especially exposed because they tend to call each other directly and are rarely re-tested when a dependency deploys.

There are two safer defaults.

Require an explicit version. A request with no Api-Version header gets a 400 whose body names the missing header and lists the supported values, for example "Api-Version header required; supported: 2, 3". Callers find out the first time they run the code, which is cheap.

Pin to the oldest supported version. An unversioned request is served by v2 until v2 is removed. Behavior stays stable, but the problem is postponed. Removing v2 later breaks exactly the callers who never declared a version, so you need to count them in metrics and contact them first.

Dropped headers make this choice matter more with header versioning. Proxies, retry wrappers, and HTTP clients that rebuild requests can strip custom headers. If you reject unversioned requests, a dropped header fails loudly and immediately. If you pin them to the oldest version, a dropped header is silently downgraded. The caller then gets old behavior with no error, and the bug only appears when that version is retired. URL versioning avoids this failure mode because the version is part of the path and survives intermediaries.

How do you deprecate and remove an old API version safely?

Deprecation works the same way under either strategy. The steps that matter happen outside the routing layer.

  1. Announce the deprecation in the channel your consuming teams actually read. Give the reason and the replacement.
  2. Emit signals in every response from the old version, such as a Deprecation or Sunset header. Generated clients and log pipelines can surface these to callers who missed the announcement.
  3. Track remaining callers by service identity. Use mTLS identities or authenticated service accounts, not IP addresses or user agents. This gives you a named list of owners to contact.
  4. Set a removal date only after you know who is left.
  5. Remove the version when traffic reaches zero and has stayed there across a full business cycle, so that monthly batch jobs have had a chance to show up.

Teams usually underestimate how long old versions stay in use. The last callers tend to be low-traffic jobs whose owners have moved on. During that time, every parallel version costs you duplicated handlers, request and response transformations between old and new data models, and a test matrix that grows with each live version.

URL versioning makes this worse because it pushes teams toward whole-API bumps. Changing one endpoint means publishing /v2 for all of them.

Illustrative estimate (assumed inputs): a service has 40 endpoints, and a breaking change touches 3 of them. Assume 0.5 engineer-hours per duplicated endpoint per month for fixes, transformations, and test upkeep, and assume old callers persist for 12 months.

  • A whole-API bump costs 40 × 0.5 × 12 = 240 hours.
  • Versioning only the 3 changed endpoints costs 3 × 0.5 × 12 = 18 hours.

How can contract tests and schema diffs catch breaking changes in CI?

The cheapest version bump is the one you never need. Two automated checks catch most accidental breaks before they reach a caller, and they work the same whether the version lives in the path or a header.

Schema diffing compares the provider's OpenAPI document in the pull request against the document for what is currently deployed, not against the main branch. Production is what callers depend on. The diff classifies each change: removing a field, narrowing a type, adding a required request parameter, or removing an enum value the provider returns is breaking. Adding an optional field or a new endpoint is not. A breaking result should block the merge unless the same change introduces a new version or carries an explicit, reviewed override.

Consumer-driven contract tests cover what a spec cannot express: which fields each consumer actually reads and which values it expects. Each consumer publishes its expectations, and the provider's pipeline verifies them against every consumer version running in production. A failure should block the provider's deploy, not only its merge, because the set of deployed consumers can change after the merge. Consumers need the mirror check: do not deploy if the provider version in production cannot satisfy their contract.

These checks are what make the alternatives to explicit versioning safe. Additive-only evolution, tolerant readers, and field-level deprecation all assume nobody removes something still in use. Without the checks, that assumption is a guess. With them, a CI failure catches the break before deploy, and you avoid an incident and an emergency v2.

How can a deliberate versioning strategy save engineering time?

Most of the engineering time spent on API versions goes into three activities: running parallel versions, finding remaining callers, and debugging version mismatches. A deliberate strategy reduces each of them.

Fewer versions to run. Every version you avoid removes a set of handlers, adapters, and tests, plus a deprecation project later. Additive changes, tolerant readers, and the CI checks above turn many would-be version bumps into ordinary releases. When a bump is unavoidable, versioning only the endpoints that changed keeps the parallel surface small, as the illustrative estimate in the deprecation section shows.

Shorter deprecations. Most of the time in a deprecation goes into finding out who still calls the old version and chasing owners. If version and caller identity are already in logs and metrics, that question is a query instead of an investigation. URL versioning gives you the version for free. Header versioning gives you the same answer once the logging, metric, and tracing changes are in place.

Faster incident debugging. When the version is visible in the URL or in every log line, an on-call engineer can see which contract a failing request expected without reproducing it. Rejecting unversioned requests with a clear 400 turns a silent downgrade, which can take a long time to trace, into an error the caller sees on the first run.

Less coordination between teams. One organization-wide convention means one set of gateway rules, one dashboard layout, and one contract-test setup. Teams do not need to check each dependency's documentation to learn how to request a version, and the platform team maintains a single routing pattern.

Illustrative estimate (assumed inputs): assume an organization runs 4 deprecations a year. Assume that without version-and-caller telemetry, identifying the remaining callers takes 20 engineer-hours per deprecation (log digging, asking in team channels, temporarily blocking traffic to see who complains), and that with the telemetry in place it takes 2 hours. Assume the one-time setup for header versioning telemetry costs 16 hours.

  • Without telemetry: 4 × 20 = 80 hours per year.
  • With telemetry: 4 × 2 = 8 hours per year, plus 16 hours of setup in the first year, for 24 hours.

These inputs are assumptions, not measurements. Plug in your own deprecation count and investigation times to see whether the setup pays off in your environment.

Should you choose header or URL versioning? A decision checklist

With breaking changes caught in CI, the remaining question is how consumers ask for a version. For most internal platforms, the deciding factor is what your network path and teams can reliably support, not which approach is more elegant.

Factor URL path versioning Header versioning
Best fit Coarse, whole-API changes Representations that evolve independently per resource
Visibility Version appears in access logs and route metrics by default Requires explicit logging of the header at each hop
Routing Plain path-prefix rules work in any gateway or ingress Needs header-match rules and support at every intermediary
Tooling curl, browsers, and caches work with no extra setup Callers and caches must set or vary on the header
Failure mode Wrong path returns a visible 404 A dropped header silently falls back to the default version

Use this checklist to decide:

  • Default to URL versioning. It gives you deprecation tracking, routing, and debugging without extra work, because the version is part of the resource address.
  • Choose header versioning only if individual representations change on different schedules and you own every client library and proxy between caller and service.
  • Avoid header versioning if any proxy, sidecar, or team cannot guarantee that the header propagates. A stripped header produces a request that looks valid but gets the wrong version, and nothing in the logs shows it.
  • Pick one convention for the whole organization. If you mix strategies, every gateway rule, dashboard, and contract test needs two code paths, and consumers have to check each service to learn which one it uses.

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 microservice api versioning, 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.