Watch Mechanism

What is Watching?

In Kubernetes, "watching" is a mechanism that allows clients (like the Kubelet, scheduler, or custom controllers) to subscribe to changes in the state of resources. Instead of polling the API server for updates.

How Watching Works

  1. Setting Up a Watch:

    • A client (e.g., kubelet, scheduler, custom controller) initiates a watch request to the API server for a specific resource or a set of resources.
    • The request typically specifies the resource type (e.g., Pods, Nodes, ConfigMaps) and any filtering criteria.
  2. Initial List:

    • The API server responds with the current state of the specified resources, essentially a snapshot at that point in time.
    • This is often called a "list" operation, where the client gets the current items that match the criteria.
  3. Watch Stream:

    • After providing the initial list, the API server keeps the connection open and sends a stream of updates (events) as they occur.
    • These updates can be of different types:
      • ADDED: A new resource has been created.
      • MODIFIED: An existing resource has been changed.
      • DELETED: A resource has been deleted.
  4. Handling Events:

    • The client processes these events in real-time, updating its local state or taking appropriate actions based on the type of event.
    • For example, a kubelet may start new containers, or a scheduler may assign new Pods to nodes.
  5. Connection Management:

    • The watch connection remains open as long as possible. If the connection is interrupted (e.g., network issues, API server restarts), the client needs to re-establish the watch.
    • Kubernetes clients typically include logic to handle reconnections gracefully, resuming from the last known state using a resource version.

Summary