Sub topic 14
Evolving compatibly and retiring old versions
This chapter covers the part of API versioning that comes after the first release: how to change an API without forcing a new version, and how to remove a version once clients have moved on. It assumes you can configure ApiVersionConfigurer, use the version attribute on mappings, and read a baseline such as 2.0+. Those are covered in earlier chapters.
Versions are a cost, not a goal
Every version you serve is code you test, document and secure. A new version also asks every client to change something. The best evolution strategy is to need new versions rarely and to retire them on a schedule.
Spring's versioning support makes it cheap to run several versions side by side. That is a reason to be disciplined, not a reason to bump the version for every change.
Compatible and breaking changes
A change is compatible if a client written against the old contract keeps working without edits. That depends on how clients read responses and build requests, so judge each change by what existing clients do.
| Change | Usually compatible? | Why |
|---|---|---|
| Add a new optional response field | Yes | Clients that ignore unknown JSON properties are unaffected. |
| Add a new endpoint | Yes | No existing client calls it. |
| Add an optional request field or query parameter | Yes | Old requests omit it and get the old behavior. |
| Add a value to an enum in a response | Risky | Clients with a strict enum parser can fail. |
| Rename or remove a response field | No | Clients that read it break. |
| Split one field into two, as in `name` to `firstName` and `lastName` | No | The old field disappears. |
| Make an optional request field required | No | Old requests now fail validation. |
| Change a field's type or format | No | Parsers fail or misread the value. |
| Tighten validation | Usually no | Requests that used to succeed are now rejected. |
| Change status codes or error body shape | No | Clients branch on them. |
The "Risky" row depends on your clients. If you publish an API to external consumers, assume some of them parse strictly. Say in your documentation that clients must tolerate unknown fields and unknown enum values. That rule is what makes additive changes safe.
Match the change to the mechanism
Additive changes need no new mapped method. They only need new code in the existing handler. The first versioning example in this tutorial used this account shape:
record AccountV2(long id, String firstName, String lastName) {}Suppose you now add an optional email to the response. That is compatible, so the handler for 2.0+ stays as it is. You can still add "2.1" to the supported versions if you want clients to be able to ask for it by name:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0", "2.1")
.setDefaultVersion("1.0");
}
}The mapping @GetMapping(path = "/{id}", version = "2.0+") is a baseline. It matches 2.0, 2.1 and any later supported version. So the new minor version needs no new method unless its behavior differs. When a minor version does differ, add a second method with version = "2.1+". Spring picks the closest matching baseline for a request, so the 2.1+ method wins for 2.1 and later, and the 2.0+ method still serves 2.0.
A new major version, such as 3.0, is for changes you cannot make compatibly. Make the breaking change there, and keep the older handlers running until clients have moved.
Keep the number of live versions small
Each live version needs its own controller methods, tests and documentation, and a fix may have to be applied in several places. Three habits keep that manageable:
- Share logic below the controller. Controller methods for different versions should call the same service and only differ in how they shape the response. Then a bug fix lands once.
- Isolate version-specific types. Keep
AccountV1andAccountV2as separate response records instead of one class full of nullable fields and conditionals. - Set a support policy before you need it. For example: at most two major versions live at once, and a deprecated version stays available for a fixed notice period.
The lifecycle of a version
A version moves through stages. Each stage should have a visible signal to clients.
The stages mean the following:
- Current: the recommended version. It is documented and supported.
- Deprecated: it still works, but clients are told to move. Signal this with the deprecation and sunset headers described in the previous chapter, and in your release notes and documentation.
- Sunset: the announced end date has been reached. It may still run briefly while you watch for stragglers.
- Removed: the version is no longer supported and the code is deleted.
Deprecating a version does not change how Spring matches requests. It only adds information to responses. The actual removal is a configuration and code change that you make.
Watch usage before you remove anything
Do not remove a version on the date alone. Check who still calls it. The version is part of every request, so it is easy to count. Options include:
- Log or tag the resolved version in your access logs or metrics, for example a counter labeled by version and client identifier.
- Check whether any caller you know about is still sending the old version, such as a partner or a mobile app release that cannot be updated quickly.
- Watch the trend. A flat, nonzero count a week before the sunset date means you should contact those clients.
Mobile apps are the usual problem. An old app build can stay in use long after a new one ships, so allow a longer notice period when mobile clients depend on a version.
Retiring a version in Spring
Removing a version has three parts, and they should land together.
- Remove it from the supported versions.
- Remove or merge the controller methods that served it.
- Check the default version, if you set one.
Here is the configuration after retiring 1.0 and 1.1:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("2.0", "2.1")
.setDefaultVersion("2.0");
}
}The default version changed from 1.0 to 2.0. A default that points at a removed version leaves every client that omits the header with an error. It is also easy to forget, because tests that always send a header do not catch it.
The controller loses getV1, and the 2.0+ method becomes the only handler:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/accounts")
public class AccountController {
record AccountV2(long id, String firstName, String lastName) {}
@GetMapping(path = "/{id}", version = "2.0+")
public AccountV2 get(@PathVariable long id) {
return new AccountV2(id, "Ada", "Lovelace");
}
}After this change, a request that sends X-API-Version: 1.0 is no longer a supported version. As covered in the error-handling chapter, Spring rejects it as an invalid version, and the client gets a 400 response. A client that sent no header now receives the 2.0 response, which is a breaking change for it. Moving the default is therefore itself a compatibility decision. Announce it in the same notice as the removal.
Choosing what clients see after removal
A 400 for an unsupported version is accurate, but it does not tell the client the version used to exist. If you want a clearer signal, such as 410 Gone with a link to a migration guide, you can handle the invalid-version exception in an @ExceptionHandler and build that response yourself. The trade-off is that a typo like 2.00x would also receive "Gone". Decide whether you can tell retired versions from garbage values before you add that handling.
Pitfalls to check before a removal
- Tests that still use the removed version. They will fail with 400s, which is useful: search the test suite for the version string before you merge.
- Documentation and OpenAPI descriptions that still list the version.
- Baselines that depended on the old version. If
getV1was1.0and another method was1.1+, removing 1.0 and 1.1 from the supported list changes which methods are reachable. Re-read everyversionattribute in the controller. - Internal callers. Other services in your own system may call the old version with
RestClient. Search for the version string in client code too. - Gateways and caches that key on the version header. If a cache or proxy stores responses per version, purge entries for the removed one.
A practical retirement checklist
- Release the successor version and mark the old one deprecated in responses and documentation.
- Announce the sunset date, with a notice period that fits your clients.
- Track calls to the old version until they reach zero or the date arrives.
- Contact remaining callers directly.
- Remove the version from
addSupportedVersions, update the default, and delete the version-specific handlers. - Update tests, documentation and any client code in the same change.
- Deploy, then watch the error rate for 400s caused by the removed version.
Exercise
Your AccountController has getV1 mapped with version = "1.0" and getV2 mapped with version = "2.0+". The supported versions are 1.0, 1.1, 2.0 and 2.1. You add an optional email field to the account response for 2.1 clients and need no other changes. What must you change in the controller, and why?
Show answer
Nothing in the controller, assuming the email addition is made inside the existing 2.0+ handler's response. The 2.0+ baseline already matches 2.1, so the same method serves it. Adding an optional response field is compatible, so 2.0 clients that ignore unknown properties keep working. You only need to add "2.1" to the supported versions (if it was not there already) so clients can request it by name.
Exercise
You retire versions 1.0 and 1.1 by removing them from addSupportedVersions and deleting getV1. The default version is still 1.0. What happens to a client that sends no version header, and what should you have changed?
Show answer
The default points at a version that is no longer supported, so the request cannot resolve to a version you serve and the client gets an error. You should have changed the default to a supported version such as 2.0 in the same change. Doing so also means clients without a header now get the 2.0 response, so announce that change along with the removal.
Exercise
Why should you track how often each version is called before removing it, instead of relying only on the announced sunset date?
Show answer
Some clients, especially old mobile app builds and partner integrations, may not move by the sunset date. Per-version call counts show who is still using the old version, so you can contact them or extend the notice period before their requests start failing.