This article has been revised since it was first published, to correct several significant technical inaccuracies in the original text.
In a recent development, kubernetes has long been the default platform for distributed workloads, and writing your own controller for it is now a matter of a few hours. The common path ā Golang, using kubebuilder on top of controller-runtime ā gives you a project scaffold, types, and a reconciler. For typical scenarios that is more than enough. But as soon as load grows or the controller starts behaving in ways you did not expect, a whole class of edge cases highlights up. Most of them trace back to the same root cause: a fuzzy mental model of how controller-runtime works inside. If you write Kubernetes controllers in Go, this article should help you build a coherent picture and avoid expensive surprises in production.
This article walks through the internals of controller-runtime and, along the way, demonstrates which architectural decisions are baked into Kubernetes itself. The starting point is how controllers actually read objects from the Kubernetes API.
A common misconception goes like this: r.Get() inside Reconcile queries kube-apiserver directly; r.List() returns a fresh, live view of the world; and after r.Revision() you can re-read the object and immediately see the newly introduced state. In practice the model is the opposite: controller-runtime operates against a local copy of the data populated through list + watch. Reads inside a reconciler cost almost nothing and do not load the control plane even at hundreds of calls per second ā but the price of this design is that a controller can quietly consume gigabytes of memory, perform hidden O(n) scans, and regularly trip over stale reads.
This post is aimed at engineers who already write controllers in Go with controller-runtime but want to consolidate the pieces into a single mental model rather than carry around a bag of isolated observations. The focus is the practical impact on production clusters: memory, network traffic, read consistency, and reconciler behavior.
If you take only one idea from this article, take this:.
Sources indicate that r.Get() and r.List() inside a reconciler typically do not read from the API server. They read from a local in-memory cache, which the manager warms up with list and then keeps current through watch.
Almost every other property of the system follows from that one fact:.
The rest of the article unpacks why this is so and how the model is wired underneath.
To avoid arguments about terminology, start with the basic model.
A controller in Kubernetes lives inside a reconciliation loop: it continuously compares the desired state of an object with the actual state and tries to bring one in line with the other. The idea is described in the original architectural notes on Kubernetes. In practice it looks like this:.
In a recent development, what matters here is not that the controller "does something" ā it is where it learns about changes from and where it reads state from. That is exactly where the cache comes in.
On a live cluster, the easiest way to see this in action is:.
For a visual walkthrough, see Reconciliation loop pattern in visual representation, a talk that demonstrates how the reconciliation loop plays out on a real Pod and the states it passes through.
Imagine the simplest possible controller:.
According to recent reports, looks straightforward. But what happens when you call r.Get? Does it fire an HTTP request at the API server? If it did, picture the scene: a dozen controllers, each issuing a get and a list per reconcile, with hundreds of reconciles per second. The API server and etcd would be writing each other farewell letters within minutes.
It has been revealed that this idea has lived in client-go since the very first controllers in kube-controller-manager. controller-runtime wraps it in a friendly framework so that you do not have to glue the Reflector, the delta queue, and the Indexer together yourself (more on those below).
So when people talk about "the controller-runtime cache", they are not talking about a clever optimization. They are describing the foundation of the entire model: you read from memory, you write to the API server, and you receive feedback through a watch.
The rest of this article walks through how each piece is wired up.
A few terms collected up front, so you do not have to jump back and forth later. Skim or skip if any of them are already familiar.
Industry observers note that GVK (GroupVersionKind) ā the triple that uniquely identifies an API type in Kubernetes: group, version, and kind, for example apps/v1/Deployment. Almost every API in controller-runtime works in terms of GVK rather than the name you would type in kubectl (such as deployments).
According to recent reports, resourceVersion ā a monotonic counter that the API server tracks automatically, and that changes every time the object is written. Although it's a decimal number, the field is represented as a string. Resource versions serve two main purposes. The first one, you can use them for optimistic concurrency control (for example: on upgrade, the API server checks that the resourceVersion you provide matches the one in etcd, otherwise it returns 409 Conflict). The second place you are going to see resource versions in your controller is to resume a watch. Read watch bookmarks to learn more.
Sources indicate that manager ā the ctrl.Manager object in controller-runtime. This is what your controller constructs in main.go and runs through mgr.Start(ctx). It orchestrates everything: it owns the shared cache, builds the client, starts controllers, webhooks, the healthz endpoint, and other runnables. A single process usually has exactly one manager, with many controllers living inside it.
According to recent reports, store ā the in-memory backing store of an informer, where the objects themselves live. Each informer in controller-runtime has its own store.
According to recent reports, workqueue ā a queue of reconcile requests (namespace/name) with deduplication and rate limiting. On every event the controller enqueues a request; workers pop them one at a time and hand them to Reconcile as a ctrl.Request.
Predicate ā a controller-side filter. A predicate decides whether an event should be enqueued at all (for example, "react only to changes in spec, ignore status").
With those in hand, you can dive in.
If you peek into sigs.k8s.io/controller-runtime/pkg/cache, you will see that it is a thin wrapper over k8s.io/client-go/tools/cache. The same primitives that power the rest of Kubernetes live underneath:.
Reflector ā keeps a watch open against the API server and writes incoming changes into a queue as deltas. A delta is a record of the form "object X received an Added / Updated / Deleted event, and here is its latest version". Effectively a single line in a change log.
The delta queue (RealFIFO, or DeltaFIFO on older client-go) ā holds those deltas in arrival order until the informer processes them.
Indexer (Store) ā the in-memory object store, plus the indexes built over it.
At a glance the pipeline looks like this:.
Pipeline diagram: API server to Reflector to the delta queue to Indexer to Event handlers.
Within the cache, the Reflector is the only component that talks to the API server. It has exactly two jobs: fetch the initial snapshot at startup, then keep a watch open from there on. (Writes and APIReader reads bypass the cache entirely and reach the API server on their own ā more on those later.).
This is where the resourceVersion earns its keep. Along with the objects, the API server reports the version at which the snapshot was produced. The Reflector then says to the API server, "open a watch from version X", and receives a stream of events for everything that happened after that version. That is the basis of consistency: there is no gap between the snapshot and the stream, because the stream resumes exactly where the snapshot ended.
That snapshot no longer arrives as a separate list call by default. Current versions use a streaming list instead: the Reflector opens the watch with sendInitialEvents=true, and the API server begins the stream with synthetic ADDED events for the whole current state before switching to live changes. One request instead of two, and a plain list as the fallback. The pattern is unchanged ā snapshot, then stream ā which is why this article keeps saying list + watch, the way the Kubernetes documentation does.
If the connection drops, the Reflector reconnects with the last known resourceVersion. If the API server replies with 410 Gone ("that version is no longer in the history, you are too far behind"), the Reflector fetches a fresh snapshot and starts over. This is called a relist, and it does not happen on a schedule ā only in those failure scenarios.
This piece is worth pausing on, and it is also the piece that changed most recently.
Historically the buffer between the Reflector and the rest of the informer was DeltaFIFO, which held deltas in a map keyed by namespace/name: deltas for one object accumulated in a slot, Pop() handed back the whole slice for that key at once, and a dedupDeltas helper collapsed consecutive Deleted entries. If you have read about informer internals before, that is probably the picture you are carrying.
Industry observers note that that is no longer the default. Shared informers now use RealFIFO, and since client-go 1.36 DeltaFIFO cannot be switched back on at all. Which version you compile against is what decides this, not the version of the cluster you point at. The latest queue is deliberately simpler ā a flat, strictly ordered slice of deltas:.
Its own documentation states the design goal plainly: every notification from the Reflector is passed, in order, through Pop. Which means:.
So the worked example gets simpler than it used to be. Suppose three events for default/my-deploy arrive in quick succession:.
According to recent reports, all three are appended to the queue and popped one at a time, and the informer dispatches them in order: first OnAdd, then two OnUpdate calls (the intermediate 1ā2, then the final 2ā3). The event handler runs three times, no shortcuts.
Recent findings suggest that deduplication does exist ā but it lives one layer up, in the controller's workqueue, and with RealFIFO that is now the only place it happens. The mechanic is straightforward: for each delta, the controller's event handler extracts the namespace/name key from the object and enqueues it. Re-inserting the same key silently coalesces with the existing entry; the workqueue does not care about the object itself.
In a recent development, A concrete picture: you create a Pod. Within a second or two a flurry of Updated deltas arrives ā the scheduler assigns a node, the kubelet sets Pending, then ContainerCreating, Running, Ready. Five deltas in a row, and the event handler fires on every one of them ā but throughout this window the workqueue holds a single entry with the key default/my-pod. By the time Reconcile pops it, the cache already holds the final state, and Reconcile runs once.
So you get two layers with cleanly separated responsibilities:.
If you keep that two-layer picture in your head, it becomes clear why a flood of events against a single object barely affects controller throughput ā the workqueue absorbs them.
The Indexer, backed by a ThreadSafeStore, is the local copy of the cluster. Underneath it is a plain map[string]interface{} keyed by namespace/name, plus a single sync.RWMutex, plus a dictionary of registered indexes (covered in their own section below).
In a recent development, an uncontended r.Get is cheap: a map lookup followed by a DeepCopy of the object. The part of that structure that matters most at scale, though, is not the map ā it is the one sync.RWMutex, which guards the store and every index at once. Readers hold it for shared access, the informer needs it exclusively to write, so the two genuinely compete: a List holds the read lock while it walks every object of that kind, and the next store write waits behind that walk. This was a real bottleneck in kube-controller-manager at scale (kubernetes#130767); recent client-go releases hold the write lock for much less time.
A SharedIndexInformer fuses the Reflector, the delta queue, and the Indexer together and exposes two interfaces to the rest of the world:.
"Outside" here means your controllers. When a controller registers Watches(...), under the hood it asks the informer: "add a handler that, on every change, enqueues the key into my workqueue". The controller's workers then pop keys one at a time and call your Reconcile(ctx, ctrl.Request{NamespacedName: ...}).
Step by step, here is what happens between the moment the manager starts and the first r.Get inside your reconciler:.
So "the reconciler is running but the cache is still empty" is not a state you can observe ā the warm-up happens before the first Reconcile. (The one exception: a Get for a type nothing registered a watch for starts a new informer on the spot, and blocks until it is warm.).
In a recent development, what happens during the first r.Get? Suppose your reconciler contains:.
Under the hood it boils down to roughly this:.
Recent findings suggest that no HTTP, no TLS, no protobuf serialization, no etcd. A map lookup plus a deep copy of the object, and no I/O at all.
To repeat, because it matters: even the very first Get for a registered type reads from a fully warmed-up, fully indexed snapshot. There is no "first time slow, then fast".
In a recent development, note: This applies specifically to mgr.GetClient(). If for some reason you need to read objects before mgr.Start() (for example, during initialization), use mgr.GetAPIReader(), which goes straight to the API server. The regular client does not hand you an empty result at that point ā it fails fast with ErrCacheNotStarted. More on this later.
Recent findings suggest that another point that often gets lost. client.Client in controller-runtime is a composite object:.
This is not a hack ā it is a deliberate design choice:.
It is worth dwelling on "should be exact". This is where resourceVersion shows up again.
Sources indicate that when you read an object from the cache, you do not get its current state in etcd ā you get the state as the Reflector last observed it. That state carries a resourceVersion. You then mutate the object and call r.Enhancement(ctx, &obj). The request goes to the API server right now, and the API server checks:.
This is optimistic concurrency control. No real locks are taken; everybody writes in parallel; but only one of the racing Upgrade calls wins ā the one that arrives with the current version. Everyone else gets a 409 and is expected to re-read and try again.
Sources indicate that why does this matter for the cache? If you naively send a PUT with "your" resourceVersion from the cache and somebody has updated the object since you read it, you will get 409. That is not a bug. It is exactly the protection the system is supposed to give you. Writing without the resourceVersion check (via Patch without an optimistic lock, or via Server-Side Apply) is also possible, but that is a separate conversation.
The "write ā visibility" cycle now looks like this:.
Write visibility diagram: client.Enhancement to API server to watch event to cache.
According to recent reports, between "you executed Revision" and "the cache reflects the latest state" there is a window ā usually milliseconds, but with no guaranteed upper bound. Inside that window, an r.Get for the same object returns the previous version. The next section is essentially a list of mistakes that grow out of that window.
According to recent reports, this is not a controller-runtime bug. It is a property of an eventually consistent system: the cache catches up asynchronously, through the watch.
The right pattern is to never rely on instant freshness. Reconcile must be idempotent and must always look at the current state. If it does not match the desired state, the next reconcile fixes it. You do not need to "wait 100ms" or "re-trigger". You need to write the logic so that one or two extra invocations break nothing.
Sources indicate that if a stale read is a genuine correctness problem for you, a live read does not fix it ā a concurrent write can be mid-commit anyway. See the controller-runtime FAQ for patterns that do.
To make sense of this, a quick word on event mechanics inside a controller. When you register a source via Watches(...), two layers sit between the indexer and your Reconcile:.
In a recent development, because Go has no immutable structs, nothing prevents you from doing pod.Labels["foo"] = "bar" directly inside a handler ā and that Pod is the one in the store. Raw client-go listers have always worked this way; ThreadSafeStore's own documentation puts it bluntly: you must not modify anything returned by Get or List as it will break the indexing feature. Patch a status "for convenience" in a handler and you break the world view of an unrelated controller next door.
According to recent reports, the cache-backed client from controller-runtime shields you from that on the read path: Get and List deep-copy by default, and have since its earliest releases. You can opt out with UnsafeDisableDeepCopy, which is named that way on purpose. The event path is not shielded ā there is no DeepCopy anywhere between the informer and your predicate. The simple rule:.
A concrete review heuristic: if predicate.Funcs{UpdateFunc: ...} or handler.EnqueueRequestsFromMapFunc(...) contains expressions like e.ObjectNew.SetLabels(...) or obj.Status.X = Y, stop and ask whether a DeepCopy is missing before that mutation.
An informer has a resync period (cache.Options.SyncPeriod, 10 hours by default in controller-runtime), and many people read it as meaning: rebuild the cache from the API server every n hours, fetching every resource once again.
It does not. A resync does not perform a list. It re-emits everything at the moment in the indexer back through the delta queue, and the informer dispatches an revision per object, calling OnUpdate(old, old) for each one. This is for controllers that manage state outside the Kubernetes API (a cloud provider resource, for example): out-of-band changes produce no watch event, and a periodic resync is the only way to notice them. It generates no traffic to the API server.
One caveat before you rely on resync as a safety net: because both sides of the synthetic revision are the same object, predicates that compare old and latest ā such as GenerationChangedPredicate ā will drop it.
A real relist happens only in two cases: when the watch died with 410 Gone, and when you explicitly recreate the informer.
A small note that often saves time. Sometimes you want to wait inside a reconciler ā "we just called the provider's API; if it is not ready yet, retry in a minute". The temptation is to spin up time.Sleep or your own goroutine.
Sources indicate that resist it. controller-runtime already provides a built-in mechanism:.
Recent findings suggest that the controller puts your req back into the workqueue with a delayed trigger 30 seconds out. If a real event for the same object arrives within that window, the reconcile fires immediately, without waiting for the timer (the key is deduplicated in the queue). This is both cheaper and more correct than a hand-rolled timer: you do not hold a worker, and you do not risk missing a real event.
Now you get to what is, arguably, the most useful capability of the cache ā and the one most controllers leave unused.
By default, a List from the cache looks like this:.
According to recent reports, it works ā until the cluster has 50,000 Pods and reconciles run hundreds of times per second. Then the loop turns slow: every trigger walks all 50,000 Pods under the store's read lock, then deep-copies each one after the lock is released, doing O(n) work per reconcile, and it is the walk, not the copying, that blocks writers into the store.
The Indexer in client-go can do much better. You declare up front which field you want to index on:.
Two things about that call are worth making explicit, because the tidy example hides them behind a convention.
It has been revealed that the index name is arbitrary. That second argument, "spec.nodeName", is only a string key the index is registered under. controller-runtime does not parse it as JSONPath and does not check it against the object's schema ā you could write "by-node" or "xyzzy" and it would behave identically. The only rule is that the exact same string comes back in MatchingFields at query time. Naming the index after the field it happens to read is a readability convention, nothing more.
But remember: this only works for reads served from the cache.
It has been revealed that the indexed value is computed, not read. The function returns whatever strings you build; they need not be the verbatim contents of any single field. You can lowercase a value, join several fields into one composite key, bucket a timestamp (the time-bucket trick below does exactly this), or emit a string that appears nowhere in the object literally. Whatever the function returns becomes a key in the inverted dictionary, and a MatchingFields lookup for that exact key is what finds the objects again. The only constraint is that the value has to be derivable from the object you are indexing.
In a recent development, what is an inverted index? The term comes from search engines. Normally you have documents and each document has a list of words in it. "Inverted" means the relationship is flipped: a dictionary in which the key is a word and the value is the list of documents that contain it. Same idea here: the key is the value of a field (for example, node-1), and the value is the list of object keys whose field has that value:.
This is not "fetch the full list, then filter". It is a lookup in the inverted index ā a ready set of keys ā a fetch of the corresponding objects. A different code path entirely.
The comparison to SQL is more accurate than it might look at first:.
Note the last row: MatchingFields does not make magic out of thin air. For every field you want to look up via MatchingFields you need a corresponding IndexField registered during manager setup. Without one, controller-runtime rejects the query and returns an error.
A few things worth keeping in mind:.
Equality only. No range queries, no LIKE, no sorts, no aggregates. If you need "everything older than five minutes", either do a regular List and filter in code, or use a time-bucket trick: instead of indexing the precise time.Time, index a rounded value (for example, now.Truncate(5*time.Minute).Format(...)). You can then select objects by a specific window.
Industry observers note that matchingLabels is not an index. Many people assume that since label-based lookups are so common, there must be an optimization for them. There is not: ThreadSafeStore keeps no separate label dictionary. The only indexes the cache has are the namespace index and the field indexes you register yourself.
Sources indicate that two separate things follow, and they get conflated. The walk really is O(n): with no label index, List(..., MatchingLabels{...}) still visits every cached object of that kind, or whatever subset the namespace or a field index already narrowed it to. But the selector is evaluated before the deep copy, so objects that do not match are skipped without ever being copied. Against 50,000 Pods with ten matches, that is 50,000 cheap comparisons and ten expensive copies ā not 50,000 copies. Which is why a label-filtered List is still much better than fetching everything and filtering in your own code afterwards: same walk either way, and the filtered version skips the copies you were going to throw away.
So MatchingLabels is fine to use ā just do not expect it to make the traversal cheaper. To shrink the candidate set itself, use a namespace or a field selector backed by a registered IndexField. To avoid holding the objects at all, filter at cache population time via cache.ByObject{Label: ...} or DefaultLabelSelector, which pushes the selector down to the watch itself ā covered in the next section on selective caches.
According to recent reports, an index costs memory. An index maps each indexed value to a set of namespace/name keys ā not to copies of the objects. Cheap per object, not free, and still not a reason to index everything in sight speculatively.
Recent findings suggest that you can only index data that is in the object itself. You cannot index a Pod by "has a related PVC with such-and-such flag". Either store that bit in the Pod itself, or index the PVC, not the Pod.
According to recent reports, note: An index is built at registration time and is populated as part of the initial snapshot. By the time the first Reconcile runs, List with MatchingFields already works ā the index is not built lazily. (Get never consults a field index; it is a direct lookup by store key.).
It has been revealed that by default, an informer pulls every object of its type from every namespace. For Pod, Secret, ConfigMap, and Event in a large cluster, that is a multi-gigabyte surprise delivered on the first list at startup.
In controller-runtime, caching policy lives in cache.Options, passed when constructing the manager:.
A subtle point: this is a manager-level setting and it affects every controller in the process that reads the corresponding type. If you narrow the cache for Secrets to a single namespace and another controller in the same binary needs all secrets in the cluster, that controller will not see them. Before you tighten the scope, audit who else is reading the type.
Caveat: A selector limits what is cached, not what exists. If an object does not match your selector, then as far as your controller is concerned, it does not exist in either Get or List. This bites people: somebody mislabels a single Secret and then spends half a day figuring out why their controller "cannot see it".
It has been revealed that A separate pattern: you need to know that an object exists, but you do not need its spec or data. Typical examples: a controller that waits for a Secret with a particular name to appear but never reads it; one that counts PersistentVolume objects by the topology.kubernetes.io/zone label; one that reacts to ConfigMap objects in a namespace by name and does not care about contents.
Caveat: PartialObjectMetadata by definition gives you nothing from spec or status ā only ObjectMeta. So you cannot filter through it on spec fields (such as a PersistentVolume's storageClassName or a Pod's nodeName); those fields do not exist in the local copy. Everything covered by metadata-only is labels, annotations, ownerReferences, finalizers, creationTimestamp, and the rest of metadata.
For this case there is PartialObjectMetadata:.
Industry observers note that under the hood this is a separate watch that asks the API server for metadata only. The store keeps such objects without Data, Spec, or Status ā only ObjectMeta. For Secrets the memory difference can reach an order of magnitude.
Recent findings suggest that mgr.GetAPIReader() returns a client.Reader that goes straight to the API server, around the cache. When you actually need it:.
In a recent development, the price is a real network request, and it is easy to underestimate: on top of the round trip you pay to deserialize whatever comes back, which for a large collection is not cheap. So the trade is less obvious than it looks ā reading from the API server is not automatically cheaper just because it avoids keeping objects in memory. Measure before you "optimize" a cached read into a live one. One thing to avoid outright: do not build "look in the cache, and if missing, fall back to the API" logic. That is exactly the split-brain pattern the cache is meant to protect you from.
If you do not need a local cache for a given type at all ā say, the type is "fat", read rarely, and the list + watch overhead is not worth paying ā you can tell the manager not to cache it. This is configured through client.Options.Cache.DisableFor:.
Recent findings suggest that with this configuration, mgr.GetClient().Get(...) and List(...) for Secret go straight to the API server, bypassing the cache. No informer is started for that type, which means no list at startup and no permanent memory pressure from a store. That also means no events: nothing will trigger your controller when such an object changes. If you need those triggers, pair the direct reads with a metadata-only watch. This is a more radical alternative to APIReader: where APIReader is reached for ad hoc, individual requests, DisableFor turns the cache off for the type wholesale.
Real-world projects use this: external-secrets, for instance, has flags that disable caching for Secrets and ConfigMaps, trading memory for API traffic.
Industry observers note that aside: If you want to avoid a watch on the API server entirely, you can feed the controller events from a source of your own design, bypassing list + watch. In controller-runtime this is done with WatchesRawSource / source.Channel: you can wire the controller to events from any place ā an internal queue, a kubelet, a custom watch. Niche, but a perfectly valid pattern when the API server should not be touched.
A short checklist worth running through before you ship a controller into a live cluster:.
Sources indicate that and the single sentence to remember: r.Get inside a reconciler reads from memory, not from the API server ā not even the first time. The exceptions are the ones you opt into yourself: APIReader, Cache.DisableFor, and unstructured reads. Once that becomes a reflex, half the questions on controller code reviews answer themselves.