---
title: "Kubernetes API Server Explained: The Life of a Request"
description: "Follow a kubectl request through the Kubernetes API server: authentication, RBAC, admission control, etcd and watches, plus what 401, 403, 409 and 422 mean."
url: "https://opsfolk.com/blog/kubernetes-api-server-explained-the-life-of-a-request"
author: "ilyas"
author_url: "https://opsfolk.com/members/ilyas"
published: "2026-10-19T10:45:42.506Z"
updated: "2026-11-27T20:19:15.408Z"
category: "Kubernetes"
series: "Kubernetes Internals: How a Cluster Really Works"
series_part: 1
series_parts: 9
series_url: "https://opsfolk.com/blog/series/kubernetes-internals-how-a-cluster-really-works"
reading_minutes: 28
image: "https://media.opsfolk.com/2026/10/3842ff5ba6e25e7cc5b4e573-2400x1350.webp"
---

# Kubernetes API Server Explained: The Life of a Request

Every `kubectl apply` you run, every controller that reconciles a Deployment, and every kubelet that starts a container talks to the same component: the **kube-apiserver**. It is the only door into a Kubernetes cluster, and every change to cluster state walks through it.

In this part of *Kubernetes Internals: How a Cluster Really Works*, we follow a single request from your terminal to etcd and back. You will see how the API server decides who you are, what you may do, whether your object is acceptable, how it is stored, and how the rest of the cluster finds out it changed. By the end, error codes like 401, 403, 409 and 422 will tell you exactly which stage turned a request away.

*New to the series? Start with the series overview or read the previous article.*

## What Is the Kubernetes API Server?

> **Definition:** The Kubernetes API server (kube-apiserver) is the control plane component that exposes the Kubernetes REST API. It authenticates, authorizes and validates every request, stores cluster state in etcd, and notifies clients when that state changes.

Think of the API server as the cluster's front desk and filing system in one. Users, controllers, the scheduler and every kubelet are all clients of the same HTTP API. None of them talk to each other directly; they read and write objects through the API server and react to changes they are told about.

Three properties shape everything in this article:

- **It is the only component that talks to etcd.** Every other component goes through the API, so every write passes the same security and validation checks.
- **It is stateless.** All state lives in etcd, so you can run several API server replicas behind a load balancer for high availability.
- **It is declarative storage, not a scheduler or orchestrator.** The API server records what you want. Controllers, the scheduler and kubelets do the work of making it real.

![kubectl, kube-controller-manager, kube-scheduler and every kubelet talk only to kube-apiserver, the one component that reads and writes etcd](https://media.opsfolk.com/2026/10/4ea51b20e51072ad863f32e7-1344x920.webp)


## The Kubernetes Request Flow at a Glance

A write request passes ten stages before it is stored, and any of them can reject it. Reads skip admission and storage writes, but still pass authentication and authorization.

![Kubernetes API server request flow · 10 stages and their rejection codes](https://media.opsfolk.com/2026/10/6ed016dc85a392c98174f572-1344x1040.webp)


Most rejection codes belong to one stage, so the status code tells you where to look first. Two, 403 and 409, can come from more than one, and their message says which stage refused the request.

**How a Kubernetes API request is processed, step by step:**

1. kubectl resolves the resource and sends an HTTPS request.
2. The handler chain accepts it: TLS, timeouts and request parsing.
3. Authentication identifies the caller; API Priority and Fairness then queues the request.
4. Authorization checks the caller may perform this action (usually RBAC).
5. The body is decoded, defaulted and converted to the internal version.
6. Mutating admission can change the object.
7. Object validation checks the object is well formed.
8. Validating admission enforces policy.
9. The object is converted to its storage version and written to etcd.
10. The response returns, and watchers are notified of the change.

### Authentication vs Authorization vs Admission Control

These three gates are easy to confuse. The table shows how they differ.

|  | Authentication | Authorization | Admission control |
| --- | --- | --- | --- |
| Question answered | Who are you? | Are you allowed to do this? | Is this object acceptable, and should it be changed? |
| Order | 1st | 2nd | 3rd, after both pass |
| Runs on | Every request | Every request | Write requests only (create, update, patch, delete, connect) |
| Inspects | Credentials (certificate, token) | User, groups, verb, resource, namespace | The full object |
| Can modify the request | No | No | Yes (mutating phase) |
| Typical mechanisms | X.509, ServiceAccount tokens, OIDC, webhook | Node, RBAC, webhook | Built-in plugins, webhooks, CEL policies |
| Rejection code | 401 Unauthorized | 403 Forbidden | Usually 403 Forbidden; 422 Invalid is common for validation and policy failures |

## Step 1: How kubectl Builds an API Request

kubectl is just an HTTP client. Before it sends anything, it needs three things: where the server is, who you are, and which URL your command maps to.

The first two come from your **kubeconfig** (`~/.kube/config` or the file in `$KUBECONFIG`). A *cluster* entry holds the server URL and its CA certificate. A *user* entry holds your credentials: a client certificate, a token, or an exec plugin that fetches a token from your cloud provider. A *context* ties a cluster, a user and a default namespace together.

### API Discovery and the Local Cache

kubectl does not have Kubernetes resources hard-coded. When you type `kubectl get deploy web`, it has to learn that `deploy` is a short name for `deployments`, in the `apps` group, version `v1`, and that the resource is namespaced.

It learns this from the **discovery endpoints**, `/api` and `/apis`, which list every group, version and resource the server offers, with short names and supported verbs. Because this list rarely changes, kubectl caches it on disk under `~/.kube/cache/discovery/`, one folder per server. Most commands hit the cache instead of the server. When kubectl can't find a resource in the cache, for example right after you install a new CRD, it refreshes the cache and tries again.

Newer clusters also support **aggregated discovery**, which returns every group and version in one or two responses instead of one request per group. On clusters with many CRDs, this makes discovery much faster.

### REST Paths, API Groups and Versions

With discovery done, kubectl builds the URL. Kubernetes uses two path shapes:

| Resource kind | Path pattern | Example |
| --- | --- | --- |
| Core group (legacy) | `/api/v1/namespaces/{ns}/{resource}/{name}` | `/api/v1/namespaces/default/pods/web-0` |
| Named group | `/apis/{group}/{version}/namespaces/{ns}/{resource}/{name}` | `/apis/apps/v1/namespaces/default/deployments/web` |
| Cluster-scoped | Same, without `namespaces/{ns}` | `/apis/rbac.authorization.k8s.io/v1/clusterroles/view` |

The HTTP method carries the verb: `GET` is get or list (or watch with `?watch=true`), `POST` creates, `PUT` updates, `PATCH` patches and `DELETE` deletes. Subresources such as `/status`, `/scale`, `/log` and `/exec` hang off the object's path.

**Tip: see the raw HTTP calls.** Raise kubectl's verbosity to watch the requests it sends:

```bash
kubectl get pods -v=6   # request URLs and status codes
kubectl get pods -v=8   # adds request and response headers and bodies
```

In the output you'll see a `GET` to `/api/v1/namespaces/default/pods?limit=500`. kubectl pages large lists in chunks of 500, and it asks the server to format the output as a table, which is why custom columns from CRDs show up in `kubectl get`.

![kubectl verbose output showing API server requests](https://media.opsfolk.com/2026/10/69f2c6ec62a0ef8d61cdcdbc-1344x1072.webp)


## Step 2: Entering the API Server (TLS and the Handler Chain)

The request reaches the API server over HTTPS, usually on port 6443. The TLS handshake proves the server's identity to kubectl. If your kubeconfig uses a client certificate, kubectl presents it here too, and the authentication step reads it later.

Inside, the request does not go straight to code that knows about Pods or Deployments. It first passes a **handler chain**: a stack of HTTP filters that wrap the real API handler, each doing one job and handing the request on. In the order a request meets them, the main filters are:

1. **Panic recovery:** a bug in any later stage returns a 500 error instead of crashing the server.
2. **Request info:** parses the URL into structured fields (verb, API group, resource, namespace, name, subresource). Every later stage uses these fields.
3. **Timeouts:** ordinary requests get a deadline (60 seconds by default, set with `--request-timeout`). Long-running requests such as watches, `exec` and `logs -f` are exempt.
4. **Authentication:** identifies the caller (Step 3).
5. **Audit:** records the request according to the audit policy.
6. **Impersonation:** applies `--as` and `--as-group`, if the caller is allowed to impersonate.
7. **API Priority and Fairness:** queues the request so no single client can overload the server.
8. **Authorization:** checks the caller may perform the action (Step 4).

Only after all of these does the request reach the handler for its resource, where decoding, admission and storage happen.

This order explains a few behaviours. Audit logs record who made a request because audit runs after authentication. Priority and Fairness can give different users different limits for the same reason. And a request rejected by authorization never gets as far as admission webhooks.

A note on routing: some paths aren't served by kube-apiserver's own code. The **aggregation layer** forwards groups registered through an `APIService`, such as `metrics.k8s.io` from metrics-server, to another server. The request still passes the same authentication and authorization first.

![Kubernetes API server handler chain and API Priority and Fairness](https://media.opsfolk.com/2026/10/39b06b6e374799e910fc3f14-1344x1040.webp)


## Step 3: Kubernetes Authentication (Who Are You?)

Authentication turns a credential into an identity. The API server runs a list of configured **authenticators** and tries each in turn; the first one that recognises the credential wins. The result is a small record: a username, a UID, a list of groups and optional extra fields. Every later stage works with that record, not with the credential.

### X.509 Client Certificates

If the client presented a certificate signed by the cluster's client CA, the certificate's Common Name (CN) becomes the username and each Organization (O) becomes a group. Kubelets authenticate this way as `system:node:<node-name>` in the group `system:nodes`. Admin kubeconfigs generated by kubeadm do too. Certificates are simple and need no external service, but they can't be revoked individually, so keep them short-lived.

### ServiceAccount Tokens

Workloads inside the cluster use **ServiceAccount tokens**: JWTs signed by the API server. Pods receive *bound* tokens through a projected volume. They expire, they are tied to the specific Pod, and the kubelet rotates them. The identity looks like `system:serviceaccount:<namespace>:<name>`, with the groups `system:serviceaccounts` and `system:serviceaccounts:<namespace>`.

### OIDC and Webhook Token Authentication

For people, most production clusters use an external identity provider. With **OIDC**, the API server validates a token issued by your provider (such as Okta, Entra ID, Keycloak or Dex) and maps its claims to a username and groups. With **webhook token authentication**, the API server sends the token to an external service in a `TokenReview` request and trusts its answer. Managed Kubernetes services often use one of these to connect cloud IAM identities to the cluster.

### There Is No User Object

Kubernetes does not store users. There is no `kubectl get users`. An identity exists only inside a certificate or token, and authorization rules refer to it by name. To see what the API server thinks you are, run:

```bash
kubectl auth whoami
```

If a request carries no credentials and anonymous access is enabled, it continues as `system:anonymous` in the group `system:unauthenticated`, and authorization will usually reject it. A credential the server can't validate gets **401 Unauthorized**, as does any unauthenticated request when anonymous access is disabled. A `403` that mentions `system:anonymous` therefore means no credentials were sent, not that you lack a permission.

### Right After Authentication: API Priority and Fairness

Once the API server knows who is calling, **API Priority and Fairness (APF)** decides when the request may run. This is why it sits after authentication: it classifies requests by user and group.

- A **FlowSchema** matches the request by user, group, verb or resource and assigns it to a priority level.
- A **PriorityLevelConfiguration** owns a share of the server's concurrency, measured in *seats*. Default levels include `system`, `leader-election`, `workload-high`, `workload-low` and `global-default`.
- Within a level, requests are split into *flows* (for example, one per user) and queued fairly, so one noisy client fills its own queues rather than everyone's.
- When the queues are full, the request is rejected with **429 Too Many Requests**, and well-behaved clients retry.

Watch a CI bot share a priority level with three people, then turn fair queuing off.

**Fair queuing in a priority level.** One priority level with four seats, each request holding one for a quarter of a second, shared by a CI bot and three people who send two requests a second each. With fair queuing, each client has its own queue of up to 20 and the seats take from the queues in turn: with the bot at 30 a second, people wait 0.13 s on average and none is refused, while 362 of the bot's 586 requests get 429. With one queue for everyone, people wait 1.1 s and 70 of their 117 requests get 429. Real APF deals each flow into a few of many queues; here each client has its own.

Inspect the configuration with `kubectl get flowschemas` and `kubectl get prioritylevelconfigurations`.

![Kubernetes authentication flow in the API server](https://media.opsfolk.com/2026/10/3fc7b24547a2a6158c734198-1344x1176.webp)


## Step 4: Kubernetes Authorization and RBAC (What Can You Do?)

Authorization answers one question: may this identity perform this action on this resource? It never looks at the request body. It only sees the attributes parsed earlier: user, groups, verb (`get`, `list`, `watch`, `create`, `update`, `patch`, `delete`), API group, resource, subresource, namespace and name.

### The Authorizer Chain

The API server runs the authorizers listed in its configuration, typically `Node,RBAC`. Each authorizer can **allow**, **deny** or **have no opinion**. The first allow or deny decides; if every authorizer has no opinion, the request is rejected with **403 Forbidden**.

- **Node** limits each kubelet to the objects it needs: its own Node, the Pods scheduled to it, and the Secrets and ConfigMaps those Pods use.
- **RBAC** handles everyone else, using rules stored as API objects.
- **Webhook** asks an external service, for organisations with central policy.

One special case: members of the `system:masters` group skip authorization entirely. Keep that group for break-glass credentials only.

### RBAC in Brief

RBAC uses four object types. A **Role** (namespaced) or **ClusterRole** (cluster-wide) lists allowed verbs on resources. A **RoleBinding** or **ClusterRoleBinding** grants that role to users, groups or ServiceAccounts.

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deployer
  namespace: team-a
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "create", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ci-deployer
  namespace: team-a
subjects:
- kind: ServiceAccount
  name: ci
  namespace: team-a
roleRef:
  kind: Role
  name: deployer
  apiGroup: rbac.authorization.k8s.io
```

RBAC is purely additive: there are no deny rules. A user can do something if any binding allows it.

### Testing Permissions with kubectl auth can-i

You don't need to trigger a 403 to find out what's allowed:

```bash
kubectl auth can-i create deployments -n team-a
kubectl auth can-i create deployments -n team-a --as=system:serviceaccount:team-a:ci
kubectl auth can-i --list -n team-a
```

When a request is denied, the 403 message names the user, verb, resource, group and namespace. Those are exactly the attributes you need to fix the Role.

*RBAC has more depth than fits here; we cover aggregation, escalation rules and least-privilege design in a dedicated article.*

![Kubernetes RBAC Role and RoleBinding diagram](https://media.opsfolk.com/2026/10/6b5b4fad16b6b98ce6868789-1344x816.webp)


## Step 5: From JSON to Go Object: Decoding, Defaulting and Internal Versions

The request is now authorized and reaches the handler for its resource, here Deployments. This is the stage most people skip over, and it explains a lot of surprising behaviour.

### External Versions vs the Internal Version

Every built-in resource has one or more **external versions**, the ones you write in `apiVersion`, such as `apps/v1`. Inside the API server, each resource also has a single **internal version**: a Go type that belongs to no API version at all. Users never see it, and it is never stored.

The request body is turned into that internal object in three steps:

1. **Decode.** The server reads `apiVersion` and `kind` and deserializes the JSON, YAML or protobuf into the Go type for that external version.
2. **Default.** Defaulting functions fill in fields you left out. For an `apps/v1` Deployment, that includes `replicas: 1`, a `RollingUpdate` strategy with 25% max surge and 25% max unavailable, and `revisionHistoryLimit: 10`.
3. **Convert.** The versioned object is converted to the internal version.

The order matters. Defaulting runs on the *versioned* object, before conversion, because defaults can differ between versions. Older beta Deployment versions, for example, filled in the label selector from the Pod template, while `apps/v1` requires you to set it.

### Why Kubernetes Uses an Internal Version

Conversion works hub-and-spoke: every external version converts to and from the internal version, never directly to another external version. Validation, admission and the resource's own logic are written once, against the internal type. Adding a new API version then means writing two conversion functions, not a new copy of every rule.

It also explains why you can create an object as one version and read it back as another. The API server converts on the way in and again on the way out.

### The CRD Exception

Custom resources work differently, because there is no Go type to convert into. The API server keeps CRD objects as **unstructured JSON** throughout the pipeline:

- **Defaulting and pruning** come from the CRD's OpenAPI schema: `default` values are applied and unknown fields are dropped.
- **Conversion between versions** is either `None` (only `apiVersion` changes, so the schemas must be compatible) or `Webhook`, which calls a conversion webhook you run.
- **One version is marked `storage: true`.** That is the version written to etcd.

![Kubernetes API version conversion to internal and storage versions](https://media.opsfolk.com/2026/10/6848ae411b3f1026daf0f4ed-1344x936.webp)


## Step 6: Kubernetes Admission Controllers and Validation

Admission control is the last line of defence before storage, and it only runs on writes: create, update, patch, delete and connect (such as `exec`). A `get`, `list` or `watch` never reaches it. It runs in three phases, always in this order:

1. **Mutating admission** may change the object.
2. **Object validation** checks the final object is well formed.
3. **Validating admission** accepts or rejects it, without changing it.

Admission logic comes from two places: **built-in plugins** compiled into the API server and switched on with `--enable-admission-plugins`, and **dynamic admission** you add at runtime with webhooks or CEL policies.

### Mutating Admission

Mutating admission fills in and rewrites. Built-in examples include `ServiceAccount`, which assigns a default ServiceAccount to Pods; `LimitRanger`, which applies default resource requests; and `DefaultStorageClass`, which sets a storage class on new claims. Mutating webhooks extend this. Service meshes inject sidecar containers this way, and secret managers inject agents.

A webhook receives an `AdmissionReview` containing the object and returns a JSON patch. Don't rely on the order of mutating webhooks. If a later webhook changes something an earlier one cares about, the earlier one can be called again when it sets `reinvocationPolicy: IfNeeded`.

### Object Validation

Next, the resource's own logic prepares and validates the object. On create, the server sets system fields such as `uid`, `creationTimestamp` and `generation`, and ignores any `status` you sent for resources with a status subresource. Then the validation rules run: names must be valid, required fields present, and immutable fields unchanged. For a Deployment, the selector must match the Pod template's labels.

For CRDs, validation comes from the OpenAPI schema plus any CEL rules in `x-kubernetes-validations`.

A failure here returns **422 Unprocessable Entity** with a list of field errors, each naming the exact field path. Validation runs *after* mutation on purpose: it must check the object as it will be stored, including changes made by webhooks.

### Validating Admission

Validating admission enforces policy on the final, valid object. Built-in examples are `ResourceQuota`, which rejects requests that would exceed a namespace's quota, and `PodSecurity`, which enforces the Pod Security Standards. Policy engines such as OPA Gatekeeper and Kyverno plug in here as validating webhooks. Validating webhooks run in parallel, and any one of them can reject the request.

### Admission Webhooks vs CEL Policies

Webhooks are flexible, but each one is a network call to a service you must run, scale and secure. **ValidatingAdmissionPolicy** offers an alternative: rules written in CEL and evaluated inside the API server, with no extra service.

```yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: max-replicas
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - apiGroups: ["apps"]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["deployments"]
  validations:
  - expression: "object.spec.replicas <= 5"
    message: "Deployments may run at most 5 replicas."
```

A `ValidatingAdmissionPolicyBinding` then applies the policy to the namespaces you choose. **MutatingAdmissionPolicy** is the newer CEL-based counterpart for mutation; check its feature status for your Kubernetes version before relying on it.

### failurePolicy: What Happens When a Webhook Is Down

Every webhook declares a `failurePolicy`:

- **`Fail`** (the default) rejects every matching request when the webhook can't be reached or times out. The client gets a 500 Internal error that names the webhook.
- **`Ignore`** lets matching requests through unchecked. A webhook that hangs still holds each one for the full `timeoutSeconds` first.

Compare a webhook that hangs with one that refuses connections, under each policy.

**A webhook's failurePolicy and timeout.** Twenty seconds of requests to an API server with one validating webhook, each placed by when it was sent and how long it took, from 10 ms to 30 s. Reads never reach admission and take about 40 ms whatever the webhook does. Healthy, writes take about 80 ms. When the webhook hangs, every write waits the whole timeoutSeconds, 10 s here: then Fail refuses it with a 500, and Ignore lets it through unchecked, just as late. When it refuses connections, both answer at once. Slow, it answers in 2 to 4 s, and a shorter timeout fails some writes.

`Fail` is safer for security policy, but a broken webhook that matches Pods in `kube-system` can stop a cluster from healing itself. Exclude system namespaces with a `namespaceSelector`, keep `timeoutSeconds` low (the default is 10), and run critical webhooks with several replicas.

![Kubernetes admission control order: mutating, validation, validating](https://media.opsfolk.com/2026/10/cd1c73aded4a725d7fad19af-1344x840.webp)


## Step 7: Storage Version and etcd

The object has passed every check. Now it must be written to etcd, the cluster's key-value store, and only the API server does that.

### Converting to the Storage Version

The internal object is converted once more, to the resource's **storage version**: the single external version the API server uses for etcd. For built-in resources this is usually the preferred stable version; for CRDs it's the version marked `storage: true`. The stored version can differ from the one you sent, and it can change across upgrades. Before an old version is removed, objects stored in it must be rewritten to the new one, a process called storage version migration.

### Serialization, Encryption and Keys

The object is then serialized: built-in resources as **protobuf**, custom resources as **JSON**. If you configured encryption at rest, for example for Secrets, the serialized bytes are encrypted at this point. The result is written under a predictable key:

```text
/registry/<resource>/<namespace>/<name>
/registry/deployments/team-a/web
```

If you read that key with `etcdctl`, you'll see binary data: a short `k8s` prefix followed by protobuf. That is expected.

### resourceVersion and Optimistic Concurrency

Kubernetes never locks objects. It uses **optimistic concurrency** instead, built on etcd's revision numbers:

- Every object carries `metadata.resourceVersion`, which reflects the etcd revision of its last change. Treat it as an opaque string, not a number to compare.
- A **create** is an etcd transaction that succeeds only if the key doesn't exist yet. Otherwise you get **409 AlreadyExists**.
- An **update** sends the `resourceVersion` the client last read. The transaction succeeds only if the object hasn't changed since. If someone else wrote first, you get **409 Conflict**, with a message asking you to apply your changes to the latest version.

Contention makes this worse than it sounds. Add writers, or lengthen the time between read and write, and count the refusals.

**Writers racing on one object.** Twenty seconds of writers updating one object. Each reads it, works for the time set, and writes with the resourceVersion it read; a write that lands after someone else's is refused with 409 Conflict, and the writer reads again and retries. One writer is never refused. Three writers at 300 ms store 40 updates and are refused 20 times. Six at 1000 ms store 18 and are refused 77 times, one of them 15 times in a row: past a few writers, more writers add conflicts, not updates.

The fix is always the same: read the object again, reapply your change and retry. Controllers do this constantly. A `PATCH` without a `resourceVersion` avoids the conflict, because the server applies the patch to whatever version is current.

![Kubernetes optimistic concurrency with resourceVersion](https://media.opsfolk.com/2026/10/fd43343bcf36e9dd2c00f1d3-1344x1232.webp)


## Step 8: The Response and the Kubernetes Watch API

Once etcd confirms the write, the API server converts the stored object back to the version the client asked for and returns it: **201 Created** for a create, **200 OK** for an update or patch. The response contains everything the server added: `uid`, `resourceVersion`, `creationTimestamp` and all the defaults. That is why `kubectl get deploy web -o yaml` shows many fields you never wrote.

Notice what hasn't happened yet: no ReplicaSet exists and no container is running. The API server's job ends at recording your intent. Everything else happens because other components are **watching**.

### How Watches Work

A watch is a long-running `GET` with `?watch=true`. Instead of returning once, the server streams events as they happen: `ADDED`, `MODIFIED` and `DELETED`, plus periodic `BOOKMARK` events that carry the latest `resourceVersion`.

The API server doesn't open an etcd watch for every client. It keeps a **watch cache**: one etcd watch per resource type, plus an in-memory window of recent objects and events. That cache fans changes out to thousands of client watches and serves many list requests without touching etcd. If a client asks to resume from a `resourceVersion` that has fallen out of the window, the server answers **410 Gone**, and the client must list again.

### Informers: How Controllers Consume Watches

Controllers rarely call the watch API directly. They use **informers** from client-go, which:

1. **List** all objects of a type once, then **watch** for changes from that `resourceVersion`.
2. Keep a local, indexed cache, so controllers read from memory, not from the API server.
3. Call event handlers that push object keys onto a work queue for the controller's reconcile loop.

This is why Kubernetes controllers don't poll, and why one API server can serve a large cluster.

### The Chain Reaction After You Create a Deployment

Each reaction below is a new request through the same pipeline you just followed:

1. The **Deployment controller** sees the new Deployment and creates a ReplicaSet.
2. The **ReplicaSet controller** sees the ReplicaSet and creates Pods.
3. The **scheduler** sees Pods with no node assigned, picks a node for each, and writes a binding.
4. The **kubelet** on that node sees a Pod bound to it, starts the containers and reports the Pod's status.

*We follow each of these in later articles: How the Kubernetes Scheduler Works and Controllers and the Reconcile Loop.*

![Kubernetes watch API and informers](https://media.opsfolk.com/2026/10/e0c98a80faacd41b2ccaa8e3-1344x864.webp)


## Server-Side Apply: How the API Server Tracks Field Ownership

So far, the client sent a complete object or a patch. **Server-side apply (SSA)** changes that: the client sends the configuration it *wants*, and the API server works out the merge, records who owns each field and detects conflicts.

### Client-Side Apply vs Server-Side Apply

Classic `kubectl apply` does the merge on your laptop. kubectl compares three things: the last configuration you applied (stored in the `kubectl.kubernetes.io/last-applied-configuration` annotation), your file, and the live object. From that it computes a patch. This has real limits:

- Only kubectl understands the logic, so other tools can't apply the same way.
- The annotation duplicates the whole object, and large objects can exceed the annotation size limit.
- Kubernetes has no record of which actor set which field, so tools overwrite each other silently.

With `kubectl apply --server-side`, kubectl sends your configuration as a `PATCH` with the content type `application/apply-patch+yaml` and a **field manager** name. The API server performs the merge itself.

### managedFields and Field Managers

The API server records ownership in `metadata.managedFields`: one entry per manager, listing the fields it set. kubectl hides this by default; show it with `--show-managed-fields`:

```yaml
metadata:
  managedFields:
  - manager: kubectl
    operation: Apply
    apiVersion: apps/v1
    fieldsType: FieldsV1
    fieldsV1:
      f:spec:
        f:replicas: {}
        f:template:
          f:spec:
            f:containers:
              k:{"name":"web"}:
                f:image: {}
  - manager: kube-controller-manager
    operation: Update
    subresource: status
    # fields under status...
```

The API server tracks ownership for every write, not only applies. Ordinary updates appear with `operation: Update`.

### Where Server-Side Apply Fits in the Pipeline

An apply request takes the normal path through authentication and authorization. In the resource handler, the API server merges your configuration with the live object, updates `managedFields` and checks for conflicts. This all happens **before admission**. From there, the merged object goes through mutating admission, validation, validating admission and storage exactly like an update.

### Field Ownership Conflicts

A conflict happens when you apply a *different* value to a field that another manager owns. The API server rejects the request with **409 Conflict** and names the fields and their owners. Applying the *same* value is fine; the field becomes shared.

The classic case is `spec.replicas` on a Deployment scaled by a HorizontalPodAutoscaler. You have two clean options:

- **Give up the field:** remove `replicas` from your manifest and let the autoscaler own it.
- **Take the field:** re-run with `--force-conflicts` when you really mean to override the other manager.

If you remove a field from your configuration and no other manager owns it, the API server deletes it from the object. Ownership is what makes removal safe.

### Why Server-Side Apply Matters

SSA lets several actors share one object safely: a GitOps tool owns the spec, an autoscaler owns the replica count, and a controller owns the status, with no one overwriting the others by accident. That is why controllers and GitOps tools such as Flux and Argo CD support it, and why it is worth making your default for declarative workflows.

![Kubernetes server-side apply field ownership conflict](https://media.opsfolk.com/2026/10/80131980147dc9a3e5830a5d-1344x936.webp)


## Putting It Together: Tracing a `kubectl apply --server-side` End to End

Let's follow one real command. A developer, Jane, signs in through OIDC and creates a new Deployment called `web` in the namespace `team-a`:

```bash
kubectl apply --server-side -f web.yaml
```

1. **kubectl builds the request.** It finds `deployments` in the `apps/v1` group from its discovery cache and sends a `PATCH` to `/apis/apps/v1/namespaces/team-a/deployments/web` with the apply content type and the field manager `kubectl`.
2. **The handler chain accepts it.** TLS completes, and request info records the verb `patch`, group `apps`, resource `deployments`, namespace `team-a` and name `web`.
3. **Authentication** validates Jane's OIDC token and produces her username and groups. **APF** assigns the request a priority level; on a quiet cluster it runs immediately.
4. **Authorization:** a RoleBinding grants Jane's group a Role that allows creating and patching Deployments in `team-a`.
5. **Apply and decoding:** `web` doesn't exist yet, so the apply creates it. The server decodes the `apps/v1` object, fills in defaults such as the rolling update strategy, converts it to the internal version and records `kubectl` as the owner of every field Jane set.
6. **Admission and validation:** built-in mutating plugins run. Validation confirms the selector matches the Pod template labels. Then the `max-replicas` policy from Step 6 checks that `replicas` is 5 or fewer.
7. **Storage:** the object is converted to its storage version, serialized as protobuf and written to `/registry/deployments/team-a/web`, which gives it a `resourceVersion`.
8. **Response:** the server returns **201 Created**, and kubectl prints `deployment.apps/web serverside-applied`.
9. **Watches fire:** the Deployment controller creates a ReplicaSet, the ReplicaSet controller creates Pods, the scheduler binds them to nodes, and the kubelets start the containers. Each of those is another trip through the same pipeline.

### Testing the Whole Pipeline with Server-Side Dry Run

Add `--dry-run=server` to run every stage, including authorization, mutating admission, validation and validating admission, without writing to etcd:

```bash
kubectl apply --server-side --dry-run=server -f web.yaml
kubectl diff -f web.yaml   # also uses a server-side dry run
```

This catches RBAC gaps, policy violations and validation errors in CI before anything reaches the cluster. Webhooks are only called during a dry run if they declare they have no side effects, so a webhook that can't support dry runs causes the request to fail.

![Life of a kubectl apply request across Kubernetes components](https://media.opsfolk.com/2026/10/b0a2fd2227c5d8fd8de5a3e7-1344x1320.webp)


## Debugging and Observing API Server Requests

The status code is the first clue. Pick what goes wrong and watch where the request stops.

**Where a request stops.** The stages of the API server as a track, from the handler chain to the response. A request moves down it and stops at the stage that refuses it, with that stage's code: 401 at authentication, 429 at Priority and Fairness, 403 at authorization, 409 before admission when another manager owns a field, 500 when a mutating webhook is down, 422 at validation, 403 again at validating admission when a quota is used up, and 409 at etcd for a stale resourceVersion. A read has no body, so it skips the four stages that check one, and none of their refusals can stop it.

When a request fails or the API server slows down, four tools tell you which stage is responsible: audit logs, server logs, metrics and raw API calls.

### Kubernetes Audit Logs

Audit logs answer "who did what, when, and what happened?". An **audit policy** file, passed with `--audit-policy-file`, decides how much to record for each request. The first matching rule wins, and each rule sets a level:

| Level | What is recorded |
| --- | --- |
| `None` | Nothing |
| `Metadata` | User, verb, resource, timestamps and response code |
| `Request` | Metadata plus the request body |
| `RequestResponse` | Metadata plus request and response bodies |

```yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: None            # skip noisy, low-value events
  resources:
  - group: ""
    resources: ["events"]
- level: Metadata        # never log Secret contents
  resources:
  - group: ""
    resources: ["secrets", "configmaps"]
- level: RequestResponse # full detail for writes
  verbs: ["create", "update", "patch", "delete"]
- level: Metadata        # everything else
```

Events go to a **log backend** (a file set with `--audit-log-path`, with rotation flags) or a **webhook backend** that ships them to an external collector. Each event records the user, the verb, the object, the response code and the authorization decision with its reason:

```json
{
  "apiVersion": "audit.k8s.io/v1",
  "kind": "Event",
  "stage": "ResponseComplete",
  "verb": "patch",
  "requestURI": "/apis/apps/v1/namespaces/team-a/deployments/web?fieldManager=kubectl",
  "user": { "username": "jane@example.com", "groups": ["platform-team", "system:authenticated"] },
  "objectRef": { "apiGroup": "apps", "resource": "deployments", "namespace": "team-a", "name": "web" },
  "responseStatus": { "code": 201 },
  "annotations": { "authorization.k8s.io/decision": "allow" }
}
```

If you find older guides that mention **AuditSink** or dynamic audit configuration: that alpha API was removed in Kubernetes 1.19. Audit is configured only through the policy file and backend flags. On managed clusters, enable audit logs through your provider's control plane logging instead.

### API Server Logs

Server logs show startup problems, webhook call failures and etcd errors. Where you find them depends on how the cluster runs:

- **kubeadm and similar (static Pods):** `kubectl logs -n kube-system kube-apiserver-<node-name>`, or on the node, the container logs under `/var/log/pods/`.
- **systemd services:** `journalctl -u kube-apiserver`. Some older installs write to `/var/log/kube-apiserver.log`.
- **Managed clusters (EKS, GKE, AKS):** the control plane isn't visible to you; enable and read its logs through the provider's logging service.

### Key API Server Metrics

The API server exposes Prometheus metrics at `/metrics`; try `kubectl get --raw /metrics`. The most useful ones:

- `apiserver_request_total`: requests by verb, resource and response code. Watch for spikes in 429 or 5xx.
- `apiserver_request_duration_seconds`: latency by verb and resource.
- `apiserver_flowcontrol_rejected_requests_total` and `apiserver_flowcontrol_request_wait_duration_seconds`: APF rejections and queueing time.
- `apiserver_admission_webhook_admission_duration_seconds`: how long each webhook takes, the usual culprit when writes are slow.

To graph p99 latency by verb, excluding long-running watches:

```promql
histogram_quantile(0.99,
  sum by (le, verb) (
    rate(apiserver_request_duration_seconds_bucket{verb!~"WATCH|CONNECT"}[5m])
  )
)
```

![Kubernetes API server request latency by verb](https://media.opsfolk.com/2026/10/87c2654eabd108c71872d6e2-1344x840.webp)


Writes spike while reads stay flat: the pattern a slow admission webhook produces, since admission only runs on writes.

### Calling the API Directly

To rule kubectl out, call the API yourself. `kubectl proxy` handles authentication, so plain `curl` works:

```bash
kubectl proxy --port=8001 &
curl http://localhost:8001/apis/apps/v1/namespaces/team-a/deployments/web
kubectl get --raw '/readyz?verbose'   # health of each internal check
```

## Key Takeaways

- The API server is the only component that talks to etcd, so every change passes the same checks.
- Authentication (401) decides who you are, authorization (403) decides what you may do, and admission decides whether the object is acceptable.
- API Priority and Fairness runs right after authentication, so it can share capacity fairly between users.
- Defaulting runs on the versioned object, before conversion to the internal version that validation and admission use.
- Admission only runs on writes: mutating admission, then object validation (422), then validating admission.
- Kubernetes uses optimistic concurrency: a stale `resourceVersion` gets 409 Conflict, and the fix is to re-read and retry.
- The API server records intent and notifies watchers; controllers, the scheduler and kubelets do the actual work.
- Server-side apply moves merging and field ownership to the server, so several tools can safely manage one object.

## FAQ

### What does the Kubernetes API server do?

It exposes the Kubernetes REST API. It authenticates, authorizes and validates every request, stores cluster state in etcd, and streams changes to the components that watch it.

### What is the difference between authentication and authorization in Kubernetes?

Authentication identifies the caller from a certificate or token and fails with 401. Authorization checks whether that identity may perform the action, usually with RBAC, and fails with 403. See the [comparison table](#authentication-vs-authorization-vs-admission-control) above.

### What are admission controllers in Kubernetes?

Admission controllers inspect write requests after authorization. Mutating admission can change the object, and validating admission can reject it. They are built-in plugins, webhooks or CEL-based policies.

### What is server-side apply in Kubernetes?

Server-side apply is a way of applying configuration where the API server performs the merge and records which manager owns each field in `managedFields`. It detects conflicts between managers instead of overwriting silently. Use it with `kubectl apply --server-side`.

### Does the API server store data?

No. The API server is stateless. All cluster state lives in etcd, and the API server keeps only an in-memory watch cache. That is why you can run several replicas.

### What happens if the API server goes down?

Running containers keep running, because kubelets don't need the API server to keep existing Pods alive. But nothing can change: no deployments, no scaling, no scheduling and no self-healing until it returns. Production clusters run several API server replicas for this reason.

### How do controllers find out about changes?

Through watches. Controllers use informers, which list objects once, then watch for changes and keep a local cache. The API server pushes events to them; they don't poll.

## What's Next

You've followed a request from your terminal to etcd and seen how its effects spread through the cluster. Next in *Kubernetes Internals: How a Cluster Really Works*, we open up one link in that chain: [How the Kubernetes Scheduler Works (and Why Pods Stay Pending)](https://opsfolk.com/blog/kubernetes-scheduler-explained-why-pods-stay-pending) shows how the scheduler picks a node for each new Pod, and how to find out why a Pod never gets one.
