惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
Apple Machine Learning Research
Apple Machine Learning Research
The GitHub Blog
The GitHub Blog
博客园 - 聂微东
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
B
Blog
博客园 - Franky
小众软件
小众软件
Recorded Future
Recorded Future
B
Blog RSS Feed
爱范儿
爱范儿
宝玉的分享
宝玉的分享
L
LangChain Blog
博客园 - 【当耐特】
The Register - Security
The Register - Security
P
Proofpoint News Feed
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
雷峰网
雷峰网
Last Week in AI
Last Week in AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
M
MIT News - Artificial intelligence
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
aimingoo的专栏
aimingoo的专栏
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
阮一峰的网络日志
阮一峰的网络日志
有赞技术团队
有赞技术团队
G
Google Developers Blog
S
SegmentFault 最新的问题
Microsoft Security Blog
Microsoft Security Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
client-go Deep Dive: Informer — The Core of Kubernetes Controller Development
James Lee · 2026-05-19 · via DEV Community

If you've ever built a Kubernetes controller — or wondered how kube-controller-manager keeps thousands of resources in sync — the answer is Informer. It's the single most important component in client-go, and mastering it is the foundation of all Kubernetes development.


1. The Problem Informer Solves

Kubernetes components need to constantly watch and query cluster resources. Take the Deployment controller: it must track every Deployment and its ReplicaSets in real time, continuously reconciling actual state toward desired state.

Doing this naively creates serious problems:

Problem Impact
Polling the API Server repeatedly Crushes API Server and etcd under query load
No middleware between components Must guarantee message reliability, ordering, and real-time delivery over raw HTTP
Multiple controllers watching the same resource Duplicate List/Watch calls, redundant serialization/deserialization

Informer solves all three — with a local cache, a shared watch connection, and an event subscription model.


2. How Informer Works: List/Watch

The core mechanism is List/Watch:

Informer starts
     │
     ▼
LIST  ── fetch ALL resources of interest from API Server
     │    store full snapshot in local cache (Indexer)
     ▼
WATCH ── open a long-lived HTTP connection to API Server
     │    receive incremental change events (Add/Update/Delete)
     ▼
Update local cache on every event
(cache stays in sync with etcd without polling)

Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Controllers query the local cache (Indexer) — extremely fast, zero API Server load
  • A single Watch connection replaces thousands of polling requests
  • Cache is always consistent with etcd state

3. The Informer Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Informer Framework                       │
│                                                                 │
│  API Server                                                     │
│      │  List / Watch                                            │
│      ▼                                                          │
│  ┌──────────┐    events    ┌─────────────┐                      │
│  │ Reflector│ ──────────► │  DeltaFIFO  │                      │
│  │(List/Watch)│           │  (event queue)│                     │
│  └──────────┘             └──────┬──────┘                      │
│                                  │ Pop                          │
│                                  ▼                              │
│                          ┌───────────────┐                      │
│                          │   Controller  │ (Informer internal)  │
│                          │ processLoop() │                      │
│                          └──────┬────────┘                      │
│                    ┌────────────┴──────────────┐                │
│                    ▼                           ▼                │
│             ┌────────────┐           ┌──────────────────┐       │
│             │  Indexer   │           │  ShareInformer   │       │
│             │(local cache│           │  distribute()    │       │
│             │ ThreadSafe)│           └────────┬─────────┘       │
│             └────────────┘                    │                 │
│                    ▲                          ▼                 │
│                    │ Lister           AddEventHandler           │
│             ┌──────┴──────┐          (user callbacks)          │
│             │ Your        │                  │                  │
│             │ Controller  │◄─── WorkQueue ───┘                  │
│             └─────────────┘                                     │
└─────────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode


4. The Complete Data Flow (Step by Step)

① Controller starts Reflector
   Reflector calls List → fetches ALL resources → stores in DeltaFIFO
   Reflector calls Watch → streams future change events into DeltaFIFO

② Controller's processLoop() calls DeltaFIFO.Pop()
   Pops events one by one → passes to HandleDeltas callback

③ HandleDeltas: if event type is Add / Update / Delete
   → stores/updates/removes object in Indexer (local cache)
   → Indexer is backed by ThreadSafeMap (concurrent-safe in-memory store)

④ HandleDeltas also calls distribute()
   → fans out event to all registered ShareInformer listeners

⑤ Your controller registers via informer.AddEventHandler()
   On event: adds resource key to WorkQueue

⑥ Your controller's worker goroutine calls WorkQueue.Get()
   → runs reconciliation logic
   → if error: re-enqueues with rate limiting for retry

Enter fullscreen mode Exit fullscreen mode

⚠️ Important distinction: The "Controller" in steps ①② is an Informer-internal component (k8s.io/client-go/tools/cache/controller.go) that manages the Informer's startup flow. The "controller" in steps ⑤⑥ is your application controller that reconciles resource state.


5. Best Practice: Clientset + Informer

The recommended pattern in Kubernetes development:

┌─────────────────────────────────────────────────┐
│  Use Clientset for:  Create / Update / Delete   │
│  Use Informer for:   Read / List / Watch        │
└─────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

Never use clientset.CoreV1().Pods().List() in a hot path — always query the Informer's local cache via Lister.


6. Code Walkthrough

Step 1 — Build a Clientset from kubeconfig

func GetKubeClient(cfgpath string) (*kubernetes.Clientset, *restclient.Config) {
    kubeconfig, err := clientcmd.BuildConfigFromFlags("", cfgpath)
    if err != nil {
        panic(err)
    }
    clientset, err := kubernetes.NewForConfig(kubeconfig)
    if err != nil {
        panic(err)
    }
    return clientset, kubeconfig
}

Enter fullscreen mode Exit fullscreen mode

Step 2 — Define the Controller struct

type KubeController struct {
    kubeConfig  *restclient.Config
    status      int32
    clientset   *kubernetes.Clientset
    factory     informers.SharedInformerFactory

    // One Informer + Lister + HasSynced per resource type
    podInformer coreinformers.PodInformer
    podsLister  corelisters.PodLister
    podsSynced  cache.InformerSynced
    // ... deployments, services, etc.
}

Enter fullscreen mode Exit fullscreen mode

Step 3 — Initialize with SharedInformerFactory

func NewKubeController(
    kubeConfig *restclient.Config,
    clientset *kubernetes.Clientset,
    defaultResync time.Duration,
) *KubeController {
    kc := &KubeController{kubeConfig: kubeConfig, clientset: clientset}

    // SharedInformerFactory ensures all informers for the same resource
    // share ONE Reflector — no duplicate List/Watch calls
    // defaultResync=0: List once at startup, no periodic re-sync
    kc.factory = informers.NewSharedInformerFactory(clientset, defaultResync)

    kc.podInformer = kc.factory.Core().V1().Pods()
    kc.podsLister  = kc.podInformer.Lister()
    kc.podsSynced  = kc.podInformer.Informer().HasSynced

    return kc
}

Enter fullscreen mode Exit fullscreen mode

Step 4 — Start the factory and wait for cache sync

func (kc *KubeController) Run(stopCh chan struct{}) {
    defer utilruntime.HandleCrash()

    // Start all informers registered with this factory
    kc.factory.Start(stopCh)

    // Block until the initial List is complete and cache is populated
    if !cache.WaitForCacheSync(stopCh,
        kc.podsSynced,
        kc.deploymentsSynced,
        kc.servicesSynced,
    ) {
        utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))
        return
    }

    kc.status = 1 // signal: cache is ready, safe to query
    <-stopCh
}

Enter fullscreen mode Exit fullscreen mode

Step 5 — Query the cache via Lister (never hit the API Server)

func main() {
    clientset, kubeConfig := GetKubeClient("conf/config")
    kc := NewKubeController(kubeConfig, clientset, time.Second*3000)

    stopCh := make(chan struct{})
    go kc.Run(stopCh)

    // Wait for cache to be ready before querying
    for kc.status != 1 {
        time.Sleep(time.Second)
    }

    // Query from local cache — fast, no API Server call
    pod, err := kc.podsLister.Pods("tech-daily").Get("hello-omega-deployment-7d8ff89d87-25kb4")
    if err != nil {
        log.Fatalf("get pod err: %s", err)
    }
    log.Printf("pod is running on node: %s", pod.Spec.NodeName)
}

Enter fullscreen mode Exit fullscreen mode


7. SharedInformer: Why It Matters

If you instantiate multiple Informers for the same resource type, each one creates its own Reflector and makes its own List/Watch call — wasting resources and adding API Server load.

SharedInformer solves this by maintaining a single Reflector per resource type, shared across all consumers:

// Internal structure of SharedInformerFactory
type sharedInformerFactory struct {
    client           kubernetes.Interface
    lock             sync.Mutex
    defaultResync    time.Duration
    customResync     map[reflect.Type]time.Duration

    // Key insight: one SharedIndexInformer per resource type
    // All calls to factory.Core().V1().Pods() return the SAME informer
    informers        map[reflect.Type]cache.SharedIndexInformer
    startedInformers map[reflect.Type]bool
}

Enter fullscreen mode Exit fullscreen mode

Without SharedInformer:
Controller A → Reflector A → List/Watch Pods
Controller B → Reflector B → List/Watch Pods   ← duplicate!
Controller C → Reflector C → List/Watch Pods   ← duplicate!

With SharedInformerFactory:
Controller A ──┐
Controller B ──┼──► Single Reflector → List/Watch Pods once  ✅
Controller C ──┘

Enter fullscreen mode Exit fullscreen mode


8. Summary

Component Role
Reflector Calls List/Watch against API Server; feeds events into DeltaFIFO
DeltaFIFO FIFO queue storing resource change events with their delta type
Controller (internal) Drives the Informer loop; pops from DeltaFIFO via processLoop
HandleDeltas Routes events to Indexer (for storage) and ShareInformer (for callbacks)
Indexer Thread-safe in-memory cache; backed by ThreadSafeMap
Lister Read interface over Indexer — fast local queries, no API Server calls
ShareInformer Fan-out mechanism; delivers events to all AddEventHandler subscribers
WorkQueue Rate-limited, deduplicating queue; bridges event callbacks and controller workers

Informer is the backbone of every Kubernetes controller. Once you understand its List/Watch → DeltaFIFO → Indexer → WorkQueue pipeline, the architecture of kube-controller-manager, custom controllers, and Operators all become clear.


Next in this series: Reflector: How client-go Syncs with the API Server (Part 2)


Follow the series for more deep dives into Kubernetes development.