Deploy Knative Serving on Kubernetes: Build Serverless Scale-to-Zero and Traffic Splitting

DevOps tutorial - IT technology blog
DevOps tutorial - IT technology blog

Context & Why

My phone buzzed at 2:14 AM with an alert: three worker nodes had hit 94% memory utilization, triggering an OOM kill storm across our production cluster. The strange part? Customer traffic was completely flat at barely 12 requests per minute.

Investigating the pod layout showed 48 idle microservices—internal PDF generators, daily digest parsers, and partner webhooks. Each sat hoarding 256MB of reserved memory and idle CPU slices just to maintain minimum replica counts. That baseline waste cost roughly $1,400 every month in idle cloud spend.

Standard Kubernetes deployments with Horizontal Pod Autoscaler (HPA) cannot natively drop to zero replicas without breaking new requests. When a call finally lands on a zero-replica deployment, standard ingress controllers return HTTP 503 errors while waiting minutes for the HPA to evaluate Prometheus metrics. Engineering teams usually swallow the cost, running over-provisioned baselines simply to prevent dropped connections.

Knative Serving solves this trade-off by decoupling incoming request ingress from pod replicas. An intelligent reverse proxy—the Knative Activator—intercepts incoming HTTP calls when pod counts drop to zero. It buffers connections in-flight, instructs the autoscaler to schedule a fresh pod, and releases the buffered traffic the instant the readiness probe passes. Beyond scale-to-zero, Knative splits live traffic across immutable revisions with weighted percentages down to 1% accuracy.

Installation

Before touching your production ingress, install Knative’s Custom Resource Definitions (CRDs) and core serving control plane. Verify first that your cluster runs Kubernetes v1.28+ with a standard CNI (such as Cilium or Calico) and an active default StorageClass.

Apply the official release manifests for Knative Serving:

# 1. Install Knative Serving CRDs
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.14.0/serving-crds.yaml

# 2. Install core Knative Serving control plane
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.14.0/serving-core.yaml

Stream pod startup across the knative-serving namespace until controller, autoscaler, and webhook pods show ready:

kubectl get pods -n knative-serving -w

Every Knative setup needs a networking layer to direct traffic. You can run Istio or Contour, but Kourier offers the lightest footprint—requiring only two Envoy-based ingress pods without the overhead of an entire service mesh:

# Install Kourier networking layer
kubectl apply -f https://github.com/knative/net-kourier/releases/download/knative-v1.14.0/kourier.yaml

# Configure Knative Serving to use Kourier as default ingress provider
kubectl patch configmap/config-network \
  --namespace knative-serving \
  --type merge \
  --patch '{"data":{"ingress-class":"kourier.ingress.networking.knative.dev"}}'

For staging, homelabs, or non-production clusters, configure automatic DNS via the sslip.io Magic DNS provider:

kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.14.0/serving-default-domain.yaml

Configuration

With the control plane running, you can deploy your first Knative Service (ksvc). Instead of maintaining separate Deployment, Service, and Ingress manifests, Knative bundles lifecycle, routing, and scaling policies into one cohesive definition.

Defining a Scale-to-Zero Service

Save the following manifest as service-v1.yaml. The annotations configure the Knative Pod Autoscaler (KPA) to terminate idle pods after 30 seconds of silence, calculating concurrency over a 60-second sliding window:

apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: payment-processor
  namespace: default
spec:
  template:
    metadata:
      name: payment-processor-v1
      annotations:
        autoscaling.knative.dev/class: "kpa.autoscaling.knative.dev"
        autoscaling.knative.dev/target: "10"
        autoscaling.knative.dev/scale-to-zero-pod-retention-period: "30s"
        autoscaling.knative.dev/window: "60s"
    spec:
      containers:
        - image: gcr.io/knative-samples/autoscale-go:0.1
          env:
            - name: APP_VERSION
              value: "v1.0.0"
          resources:
            limits:
              memory: "128Mi"
              cpu: "250m"
            requests:
              memory: "64Mi"
              cpu: "100m"

Apply the manifest:

kubectl apply -f service-v1.yaml

Managing Canary Traffic Splitting

Routing 100% of live traffic straight to a fresh build risks global outages. Knative treats each spec change as an immutable revision, letting you split traffic weights across releases cleanly.

Create service-traffic-split.yaml. Here, revision v1 retains 80% of customer traffic while canary candidate v2 takes the remaining 20%:

apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: payment-processor
  namespace: default
spec:
  template:
    metadata:
      name: payment-processor-v2
    spec:
      containers:
        - image: gcr.io/knative-samples/autoscale-go:0.1
          env:
            - name: APP_VERSION
              value: "v2.0.0"
          resources:
            limits:
              memory: "128Mi"
              cpu: "250m"
  traffic:
    - revisionName: payment-processor-v1
      percent: 80
    - revisionName: payment-processor-v2
      percent: 20

Apply the updated traffic split:

kubectl apply -f service-traffic-split.yaml

Verification & Monitoring

Now test whether the system actually tears down idle pods and buffers requests during cold starts.

Testing Scale-to-Zero Behavior

Watch pod lifecycle state while leaving the service alone for 60 seconds:

# Monitor pods transitioning from Running to Terminating
kubectl get pods -l serving.knative.dev/service=payment-processor -w

Within 45 to 60 seconds, pods transition to Terminating and disappear. Query the assigned URL:

URL=$(kubectl get ksvc payment-processor -o jsonpath='{.status.url}')
echo "Service available at: $URL"

Triggering Pod Activation Under Load

Fire a curl request directly at the endpoint while watching the terminal:

# Wake the sleeping service
curl -i $URL

The first response might take 600ms to 900ms. That delay is the cold start. Behind the scenes, the Activator paused the TCP connection, scheduled a container, passed health checks, and returned HTTP 200 with zero dropped packets. Subsequent calls respond in under 15ms.

Auditing Traffic Distribution

Send 20 requests in a loop to verify the 80/20 canary split:

for i in {1..20}; do
  curl -s $URL | grep -o 'v[1-2]\.0\.0'
done

Output will show approximately 16 hits to v1.0.0 and 4 hits to v2.0.0, matching the declared split without needing manual ingress rule recalculations.

Monitoring Metrics & Activator Health

During traffic surges, watch request queue depths on port 9090. Knative ships native Prometheus instrumentation across both the activator and autoscaler pods. Add these two queries to your Grafana dashboard:

# Calculated target replica count
knative_serving_autoscaler_desired_pods{namespace="default"}

# Request hold duration in the activator proxy
histogram_quantile(0.95, sum(rate(knative_serving_activator_request_latencies_bucket[5m])) by (le))

If your 95th-percentile activator latency climbs over 1.5 seconds, your bottleneck is container cold start time, not networking. Strip bloated base layers from your images, pre-pull images across your node pool, and tune readiness probe intervals so containers go live within hundreds of milliseconds.

Share: