Using Kubernetes ConfigMaps as a Real-Time State Store
A Python demo shows how Kubernetes' watch API turns ConfigMaps into a real-time pub/sub change feed using asyncio, without polling or pod restarts.
Most teams treat Kubernetes ConfigMaps as static config, read once at pod startup and left stale until a restart or a polling loop catches up. This article's demo instead taps into the Kubernetes API's built-in watch stream, where the server pushes ADDED, MODIFIED, and DELETED events over a long-lived connection, and turns that stream into a real-time asyncio-based pub/sub system using the async-first kr8s client.
The architecture has three layers: a Watcher holding one persistent connection to the API, a Notifier that fans events out to per-client asyncio.Queue instances, and independent client tasks reacting differently to the same event. Dropped connections are handled by wrapping the watch loop in a retry-on-failure pattern that catches httpx.ReadError and reconnects transparently, while an asyncio.Lock in the Notifier prevents the subscriber list from being mutated mid-broadcast.
The demo illustrates this with three clients — a Logger that records every event, a Counter that tracks a running total, and a Filter that reacts only to ADDED events — all sharing a single watch connection. In production, equivalent clients could invalidate caches, hot-reload in-memory config, or toggle feature flags, each maintaining its own view of state without polling or restarts.
The key takeaway is that Kubernetes already ships a reactive state store: the ConfigMap's data is the state, the watch API is the change feed, and a simple fan-out broker is all that's needed to deliver it to multiple observers — no external message broker required.