Client-side apply resets the replicas an HPA set; server-side apply conflicts; forcing repeats the outage. Field managers, the documented handover and a CI check.
The deploy that halves capacity
The catalogue API at Belgavi's Book Store runs as a Kubernetes Deployment with a HorizontalPodAutoscaler. During an evening sale the autoscaler has it at 7 replicas. At 19:05 the CI pipeline deploys a one-line image change with kubectl apply -f deploy.yaml, and the manifest, written months ago before autoscaling was added, still says replicas: 3. The Deployment drops to 3 replicas, latency climbs, and a few minutes later the autoscaler scales back up. Every deploy during busy hours repeats it.
Nothing here is a bug in Kubernetes. Two writers, the pipeline and the autoscaler, both claim the same field, and the way each write is made decides who wins. This guide explains field management as the Kubernetes documentation defines it, shows what client-side apply, server-side apply and forced server-side apply each do in this situation, and gives the safe procedure for handing spec.replicas to the autoscaler, with a small model and a CI check.
Field managers and managedFields
Since Kubernetes 1.22 server-side apply is stable, and the API server tracks, for every object, which field manager last asserted each field. The record lives in metadata.managedFields. A field manager is a name: kubectl uses its own, controllers use theirs, and you can choose one with --field-manager.
The documented rules that matter here are few:
- An apply that would change a field another manager owns is a conflict, and the request is rejected unless it is forced.
- When two appliers set a field to the same value, they share ownership.
- An applier that omits a field it previously applied gives up its claim. If no other manager owns the field, the field is removed from the object or reset to its default; for a Deployment,
spec.replicasdefaults to 1. - Non-apply writes (create, update, patch) never conflict. Whenever a write changes a field's value, ownership moves to the manager that made the change.
The autoscaler writes replicas through the scale subresource, which is an update, so it never conflicts and it becomes the field's owner each time it changes the value.
Three ways to deploy the same manifest
The companion example models these rules for scalar fields and replays the evening three ways: deploy, autoscaler scales to 7, deploy again.
| Deploy method | After the second deploy | Owner of spec.replicas |
|---|---|---|
kubectl apply (client-side) | replicas 3 | the pipeline |
kubectl apply --server-side | conflict, deploy fails, replicas stay 7 | the autoscaler |
kubectl apply --server-side --force-conflicts | replicas 3 | the pipeline |
Client-side apply computes a patch from the manifest, the live object and the kubectl.kubernetes.io/last-applied-configuration annotation. A field present in the manifest always wins, and nothing warns that someone else changed it. That is the 19:05 incident.
Server-side apply notices that the autoscaler owns the field with a different value and refuses the request. That is better: the deploy fails loudly instead of halving capacity. But it fails every time, and the fix many pipelines then reach for is --force-conflicts, which the documentation describes as "overwrite value, become sole manager". Forced apply reproduces the client-side incident, with an audit trail.
Removing the field is right, but timing matters
The real fix is to stop asserting spec.replicas from the manifest once an autoscaler manages it. The Kubernetes documentation walks through exactly this case and points out a race: if the pipeline removes replicas from its manifest before the autoscaler has written the field and become its owner, the field has no owner, and the API server resets it to the default of 1.
The model shows both paths:
| Sequence | Replicas afterwards |
|---|---|
Pipeline applies without replicas before the autoscaler ever wrote it | 1 (default) |
Documented handover: a temporary manager applies replicas: 3 alone, then the pipeline drops the field | 3, until the autoscaler writes; then the autoscaler owns it |
The documented handover uses a manifest with only the field and a private field manager name, applied server-side:
# replicas-handover.yaml: only the field being handed over
apiVersion: apps/v1
kind: Deployment
metadata:
name: catalog-api
namespace: shop
spec:
replicas: 3kubectl apply -f replicas-handover.yaml --server-side --field-manager=handover-to-hpa --validate=false
kubectl apply -f deploy-without-replicas.yaml --server-sideThe first command makes handover-to-hpa a co-owner with the same value. The second, with replicas removed, releases the pipeline's claim while the temporary manager still holds the field, so nothing resets. When the autoscaler next changes the value, it takes ownership and, as the documentation notes, the temporary manager no longer owns any fields and disappears. If the first command reports a conflict, the autoscaler already owns the field, and the pipeline can drop it straight away.
The simpler alternative in the documentation is to leave replicas in the manifest and switch the pipeline to server-side apply without forcing: the next deploy after the autoscaler writes will conflict, and at that point it is safe to remove the field.
The model in a few lines (simplified)
def server_side_apply(self, manager, config, force=False):
conflicts = [f for f, v in config.items()
if f in self.values and self.values[f] != v and self.owners.get(f, set()) - {manager}]
if conflicts and not force:
raise Conflict(...)
previously = {f for f, o in self.owners.items() if manager in o}
for f, v in config.items():
changed = self.values.get(f) != v
self.values[f] = v
self._own(f, manager, shared=not changed) # same value: share; new value: sole owner
for f in previously - set(config): # fields this manager stopped applying
self.owners[f].discard(manager)
if not self.owners[f]:
del self.owners[f]
self.values[f] = DEFAULTS.get(f) # reset to the default (replicas: 1)It is a teaching model of the documented rules for scalar fields, not an implementation: real server-side apply handles lists, maps, associative keys, subresources and API versions. Its value is that the five scenarios above become eight unit tests that anyone on the team can read.
A CI check that prevents the fight
The durable fix is to make the conflict impossible to reintroduce. A small check over the rendered manifests (after Helm, Kustomize or whatever templating you use) flags any Deployment or StatefulSet that sets spec.replicas while an HPA in the same namespace targets it.
def lint_replicas(objects):
targets = {(o.get('metadata', {}).get('namespace', 'default'), o['spec']['scaleTargetRef']['kind'], o['spec']['scaleTargetRef']['name'])
for o in objects if o.get('kind') == 'HorizontalPodAutoscaler'}
return [f'{o["kind"]}/{o["metadata"]["name"]} sets spec.replicas but is scaled by an HPA'
for o in objects
if (o.get('metadata', {}).get('namespace', 'default'), o.get('kind'), o.get('metadata', {}).get('name')) in targets
and 'replicas' in o.get('spec', {})]Run it on the output of the templating step, not on the source files, because charts often set replicas through a value that is only empty when autoscaling is enabled.
Tradeoffs and operational notes
- Switching a pipeline from client-side to server-side apply is supported in place:
kubectl apply --server-sidetakes over the fields recorded in the last-applied annotation. Do it for one environment first and read the first conflicts carefully; each one is a field someone else changes. - Do not force by default.
--force-conflictsis appropriate for controllers that own a resource outright, as the documentation recommends, and for deliberate takeovers. In a human-authored pipeline it hides exactly the information server-side apply was designed to give you. - GitOps tools that apply on a loop face the same question. Argo CD, for example, can be told to ignore differences in a field such as
spec.replicas; use that, or remove the field from the source. - Other shared fields behave the same way: annotations written by admission controllers, resource requests set by a vertical autoscaler, image tags set by a rollout tool. Field ownership is the general tool; replicas is just the most common example.
Reading the evidence on a live object
Before changing anything, look at who owns the field today. kubectl get with --show-managed-fields prints one entry per manager, with the operation (Apply or Update), the subresource if any, a timestamp and a fieldsV1 map of the fields that manager owns. On a Deployment that the pipeline applies and an autoscaler scales, expect an Apply entry for the pipeline's manager and an Update entry on the scale subresource for the autoscaler, with f:replicas under whichever of them changed the value last. If the pipeline still uses client-side apply, its entry is an Update by a kubectl manager and the object also carries the last-applied annotation. Those entries tell you which of the three behaviours in the table above you will get on the next deploy.
Verification
- Read the owners:
kubectl get deploy catalog-api -n shop -o yaml --show-managed-fieldslists each manager and the fields it owns. - In a test cluster, deploy with the autoscaler active and confirm replicas do not change, then run the handover and confirm the temporary manager disappears after the autoscaler's next write.
- Add the lint to CI and seed it with one known bad manifest so you know it fires.
When none of this applies
A Deployment without an autoscaler has one writer for spec.replicas, the pipeline, and client-side apply is fine. The problem exists only where two writers share a field. The question to ask of every field in a manifest is the same: who else changes this, and which of us should own it?