Knative Serving

repository·main·Indexed 11 days ago

https://github.com/knative/serving

A serverless infrastructure layer on top of Kubernetes that enables deployment of containerized applications with automatic scaling, including scaling to zero. It features a request-driven autoscaling system comprising the Autoscaler, Activator, and queue-proxy sidecar to manage concurrency, load balancing, and rapid scaling based on demand.

Tokens
19.2K
Snippets
27
Records
95
Agent score
91%

What's inside Knative Serving

  1. Overview of Knative Serving

    main

    Knative Serving is a project built on Kubernetes designed to deploy and serve applications and functions as serverless containers. It provides middleware primitives that enable rapid deployment, automatic scaling (including scaling down to zero), advanced routing and network programming, and point-in-time snapshots of deployed code and configurations.

    For detailed usage instructions, refer to the Knative documentation site. For technical specifications, consult the docs folder within this repository.

  2. Understand the structure of Knative Serving configuration

    main

    The Knative Serving configuration is organized into functional modules. When managing or extending the deployment, you can navigate the directory structure based on these categories:

    • Core: The essential elements required for Knative Serving to function. This includes:
      • roles/: Cluster roles for core controllers and Kubernetes RBAC integration.
      • configmaps/: Configuration settings for core components.
      • resources/: Serving resource definitions.
      • webhooks/: Mutating and validating admission webhook configurations.
      • deployments/: Executable components and their associated resources.
    • hpa-autoscaling/: Configuration for extending the core with HPA-class autoscaling.
    • namespace-wildcards/: Configuration for provisioning wildcard certificates per-namespace.
    • cert-manager/: Configuration for integrating the cert-manager certificate implementation.
    • Rendered Views: The *.yaml files in the root directory are symlinks that represent specific, fully-rendered views of the entire Knative Serving configuration.
  3. Trace the Networking and Traffic Flow

    main

    Traffic reaches your application through a layered networking stack:

    1. Route Controller: Creates a Knative Ingress resource describing how external traffic reaches Revisions.
    2. Networking Plugin: A plugin (such as Istio, Kourier, or Contour) watches these Ingress resources and converts them into provider-specific resources (e.g., Istio VirtualService or HTTPProxy).
    3. ServerlessService (SKS) Controller: Manages Kubernetes Services and Endpoints that ultimately point to your revision pods.

    Traffic flow: Service/Route $\rightarrow$ Knative Ingress $\rightarrow$ Networking Plugin $\rightarrow$ Native Resources $\rightarrow$ Pods.

    ┌─────────────────┐     ┌─────────────┐     ┌─────────────────────────────────────────────┐
    │ Service/Route   │────►│   Ingress   │────►│    Networking Plugin                        │
    │   Controller    │     │ (Knative)   │     │    (Istio/Kourier/Contour)                  │
    └─────────────────┘     └─────────────┘     └──────────────────────────────┬──────────────┘
                                                                              │
                                                                              ▼
                                                                Converts to native resources
                                                                (VirtualService, HTTPProxy, etc.)
  4. The Metric Controller's role in autoscaling metrics

    main

    The Metric controller (pkg/reconciler/metric/) manages the metrics collection infrastructure for autoscaling by watching autoscaling.internal.knative.dev/v1.Metric resources.

    Key Responsibilities:

    • Registers/updates Metric resources with the metrics Collector.
    • The Collector scrapes metrics from revision pods or the activator.
    • Updates Metric status to Ready (collection working), NotReady (endpoints unavailable), or Failed (stats not being received).
    • Cleans up collection when Metrics are deleted.
  5. How scaling to zero works

    main

    A revision scales to zero when there are no more requests in the system. The process follows these steps:

    1. Detection: The autoscaler scrapes revision pods and receives 0 concurrency, and the activator also reports 0.
    2. Mode Switch: The autoscaler instructs the SKS to switch to Proxy mode so all traffic is directed to the activators.
    3. Verification: The SKS's public service is probed to ensure it is successfully returning responses from the activator.
    4. Removal: Once the activator is routable and a configurable grace period (defined by scale-to-zero-grace-period) has passed, the last pod of the revision is removed.
  6. Configure Knative Serving v1 Configuration

    main

    A Configuration represents the "floating HEAD" of a linear history of Revisions. Users trigger the creation of new Revisions by updating the Configuration's spec.

    Key fields in serving.knative.dev/v1.Configuration:

    • apiVersion: serving.knative.dev/v1
    • kind: Configuration
    • spec.template: A RevisionTemplateSpec that holds the latest specification for the Revision to be stamped out.
    • status: Contains the name of the latest created revision and the latest ready revision.
  7. How KPA (Knative Pod Autoscaler) works

    main

    The KPA controller (pkg/reconciler/autoscaling/kpa/) implements Knative's native autoscaling algorithm for autoscaling.internal.knative.dev/v1alpha1.PodAutoscaler resources with the kpa.autoscaling.knative.dev class annotation. It supports scale-to-zero and scale-from-zero.

    Key Responsibilities:

    • Decider Management: Creates/updates Deciders that make scaling decisions based on metrics.
    • Metric Collection: Reconciles Metric resources for scraping request metrics from pods.
    • SKS Management: Reconciles ServerlessService (SKS) resources to manage traffic routing during scaling.
    • Pod Scaling: Scales the underlying deployment based on Decider recommendations.
    • Activation/Deactivation: Marks PA as "Activating" (scaling from zero), "Active" (sufficient pods ready), or "Inactive" (scaled to zero).
    • Activator Management: Computes the required number of activator pods based on burst capacity.
  8. The Service Controller's role in orchestration

    main

    The Service controller (pkg/reconciler/service/) is the top-level orchestrator for serving.knative.dev/v1.Service resources. It provides a simplified interface for deploying serverless applications by managing the lifecycle of Configuration and Route resources.

    Key Responsibilities:

    • Creates and reconciles a Configuration resource based on the Service's spec.template.
    • Creates and reconciles a Route resource to handle traffic splitting.
    • Propagates status from Configuration (revision readiness) and Route (URL, traffic) back to the Service.
    • Handles BYO (Bring Your Own) revision names by serializing Configuration and Route reconciliation.
    • Validates that the Service owns its Configuration and Route.
  9. Understand the Knative Serving Controller Architecture

    main

    Knative Serving uses a hierarchical reconciliation pattern where higher-level resources manage lower-level ones. Understanding this hierarchy is essential for debugging resource lifecycle issues and understanding how changes propagate through the system.

    Key Architectural Principles

    • Ownership & Garbage Collection: Child resources are linked to parents via OwnerReferences. Deleting a parent resource triggers Kubernetes to automatically garbage collect all its owned children.
    • Status Propagation: Status information flows upward. For example, the readiness of a Deployment affects the Revision status, which in turn affects the Configuration status (via LatestReadyRevisionName), ultimately updating the Service status.
    • Reconciliation Triggers: Controllers react to changes in their primary watched resource, changes in owned child resources, or changes in tracked (but not owned) resources.
    • Idempotency: All reconcilers are idempotent; running them multiple times with the same input results in the same state.

    Controller Binaries

    Knative Serving logic is split into two main binaries:

    1. controller: Handles most core resources including Service, Configuration, Revision, Route, SKS, and Certificate.
    2. autoscaler: Handles the Metric controller and the core autoscaling decision logic.
  10. Trace the Deployment Flow for a new Knative Service

    main

    When a user creates a Knative Service, a cascade of resource creation occurs across several controllers:

    1. Service Controller: Creates a Configuration (defining desired state) and a Route (defining traffic routing).
    2. Configuration Controller: Creates a Revision (an immutable snapshot of code and config).
    3. Revision Controller: Creates the underlying Kubernetes Deployment, a PodAutoscaler (to manage scaling), and optionally an Image Cache resource.

    This hierarchy ensures that a high-level Service abstraction is correctly decomposed into low-level Kubernetes primitives.

    User creates Service
            │
            ▼
    ┌───────────────────┐     ┌─────────────────┐     ┌────────────┐
    │ Service Controller│────►│  Configuration  │────►│  Revision  │
    └───────────────────┘     │    Controller   │     │ Controller │
                              └─────────────────┘     └─────┬──────┘
                                                            │
                              ┌─────────────────────────────┼─────────────────────────────┐
                              │                             │                             │
                              ▼                             ▼                             ▼
                       ┌────────────┐              ┌───────────────┐              ┌─────────────┐
                       │ Deployment │              │ PodAutoscaler │              │ Image Cache │
                       │  (K8s)     │              │   (PA)        │              │ (optional)  │
                       └────────────┘              └───────────────┘              └─────────────┘
  11. Understand the core components of Knative Serving

    main

    Knative Serving consists of four primary components that manage the lifecycle of your services. All these components are deployed into the knative-serving namespace:

    • Controller: Responsible for updating the cluster state to match the user's desired state.
    • Webhook: Handles validation of objects and actions performed on Knative resources.
    • Activator: Brings back scaled-to-zero pods and forwards incoming requests to them.
    • Autoscaler: Scales pods up or down based on incoming request volume.

    Note that while the system components live in knative-serving, the sub-resources created by the controller (like Deployments and ReplicaSets for your specific services) are created in the same namespace as your Knative Service, not in the knative-serving namespace.

  12. How the ServerlessService (SKS) Controller manages traffic routing

    main

    The ServerlessService (SKS) controller manages the Kubernetes Services and Endpoints required to route traffic to revision pods or to the activator during scale-to/from-zero events. It operates in two primary modes:

    1. Serve mode (Private Service): Creates a Kubernetes Service with pod selectors pointing directly to revision pods. This is used when pods are ready and receiving traffic.
    2. Proxy mode (Public Service): Creates a Kubernetes Service without selectors, where endpoints are managed manually. This mode points to activator pod IPs to handle requests when services have scaled to zero. In this mode, the controller selects a consistent subset of activator endpoints per revision (Endpoint Subsetting).

    The controller handles transitions between these modes as pods become ready or unready and provides fallbacks (e.g., falling back to Proxy mode if no revision pods are ready, or falling back to Serve mode if no activator pods are available).