Kubernetes Lesson 35 of 70

Lesson 35 of 70 · 7 min read · Updated

Canary and Blue/Green Releases with Gateway API Traffic Weights

The PedalShare pricing team has a new fare calculator. Sending all riders to it at once is risky, so the team wants to start with a small share of traffic, let QA reach it on purpose, and switch back in seconds if something goes wrong. With the Gateway API, all of this is the weight field on backendRefs. No service mesh and no controller-specific annotations are needed.

This lesson runs a canary from 10% to 50% to 100%, then a blue/green switch and rollback, on NGINX Gateway Fabric. It also shows two cases where weights do not do what people expect.

Technical Requirements

  1. The gateway-lab cluster with NGINX Gateway Fabric 2.8.1 and the public Gateway
  2. Sample repository: Fcakiroglu16/dotnetacademy, branch gateway-api-traffic-splitting
  3. scripts/port-forward.sh from the repository. Plain kubectl port-forward exits after one broken connection, for example when NGINX reloads. The script restarts it and keeps localhost:8080 open.

The pricing team runs both versions side by side, each with three replicas and its own Service:

kubectl apply -f k8s/apps/pricing-api.yaml
kubectl get deploy -n pedalshare-pricing
NAME READY UP-TO-DATE AVAILABLE
pricing-api-v1 3/3 3 3
pricing-api-v2 3/3 3 3

Core Concepts

Weights are proportions

Each entry in backendRefs has a weight (default 1). A request goes to a backend with probability weight / sum of weights within that rule. The weights do not have to add up to 100: 9 and 1 give the same split as 90 and 10.

Weights (v1 / v2)Share of v2
1 / 1 (default)50%
90 / 1010%
3 / 125%
0 / 100100%

The split is per request and random. It is not sticky: one rider can hit v1 and then v2. If the two versions must not mix within a session, add a header-based rule (shown below) or use session persistence, which is still an experimental feature in Gateway API.

Canary and blue/green are the same mechanism

  1. Canary: shift traffic in steps (10%, 50%, 100%) while you watch error rates and latency.
  2. Blue/green: run both versions at full size and switch with weights 100/0 to 0/100. A rollback is the reverse edit.

Both versions keep running during the change, so a rollback does not need to start new Pods. It only changes the proxy configuration.

Weights and backend health

A weight is applied before any health check. If a backend with weight 10 has no ready endpoints, about 10% of requests fail, and the route status still says ResolvedRefs=True, because the Service exists. Weights do not move traffic away from an unhealthy backend for you. That is the job of your rollout tooling or of a person watching the canary.

Hands-On: Kubernetes Commands

scripts/port-forward.sh & # keeps localhost:8080 -> NGF open
kubectl apply -f k8s/06-traffic-splitting/01-canary-10.yaml
scripts/count-versions.sh 1000 # sends 1000 requests, counts versions

count-versions.sh calls GET /fares/quote?minutes=25 with Host: pricing.pedalshare.local and counts the version field in the answers. Extra arguments go to curl:

scripts/count-versions.sh

#!/usr/bin/env bash
# Sends N requests to the pricing API and counts which version answered.
# Usage: scripts/count-versions.sh [requests] [extra curl args...]
set -uo pipefail
n=${1:-200}; shift || true
for _ in $(seq 1 "$n"); do
body=$(curl -s -H 'Host: pricing.pedalshare.local' "$@" 'localhost:8080/fares/quote?minutes=25')
[[ $body =~ \"version\":\"([^\"]+)\" ]] && echo "${BASH_REMATCH[1]}" || echo "error"
done | sort | uniq -c

To change a split during a release, edit the weights and apply again, or patch them in place:

kubectl patch httproute pricing -n pedalshare-pricing --type=json \
-p='[{"op":"replace","path":"/spec/rules/0/backendRefs/0/weight","value":50},
{"op":"replace","path":"/spec/rules/0/backendRefs/1/weight","value":50}]'

In a GitOps setup, the weights live in Git and each step is a commit, so the history of the rollout is the Git history.

Step-by-Step Example

Step 1: Canary at 10%

k8s/06-traffic-splitting/01-canary-10.yaml

# Weighted split: v1=90, v2=10. Weights are relative, they do not need to add up to 100.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: pricing
namespace: pedalshare-pricing
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: http
hostnames:
- pricing.pedalshare.local
rules:
- matches:
- path: {type: PathPrefix, value: /fares}
backendRefs:
- {name: pricing-api-v1, port: 80, weight: 90}
- {name: pricing-api-v2, port: 80, weight: 10}
$ kubectl apply -f k8s/06-traffic-splitting/01-canary-10.yaml
$ scripts/count-versions.sh 1000
899 v1
101 v2

Step 2: Let QA reach the canary on purpose

QA should not depend on luck to test v2. A rule with a header match has higher precedence than the weighted rule, so requests with X-PedalShare-Canary: always always go to v2, and everyone else keeps the 90/10 split:

k8s/06-traffic-splitting/02-canary-10-with-header.yaml

# Same 90/10 split, plus a rule that always sends QA traffic to v2.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: pricing
namespace: pedalshare-pricing
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: http
hostnames:
- pricing.pedalshare.local
rules:
- matches:
- path: {type: PathPrefix, value: /fares}
headers:
- {name: X-PedalShare-Canary, value: always}
backendRefs:
- {name: pricing-api-v2, port: 80}
- matches:
- path: {type: PathPrefix, value: /fares}
backendRefs:
- {name: pricing-api-v1, port: 80, weight: 90}
- {name: pricing-api-v2, port: 80, weight: 10}
$ kubectl apply -f k8s/06-traffic-splitting/02-canary-10-with-header.yaml
$ scripts/count-versions.sh 100 -H 'X-PedalShare-Canary: always'
100 v2
$ scripts/count-versions.sh 1000
891 v1
109 v2

Step 3: 50% and then 100%

The metrics look good, so the team moves to 50/50 and then to 0/100. Only the weights change:

$ kubectl apply -f k8s/06-traffic-splitting/03-canary-50.yaml
$ scripts/count-versions.sh 1000
512 v1
488 v2

$ kubectl apply -f k8s/06-traffic-splitting/04-cutover.yaml
$ scripts/count-versions.sh 1000
1000 v2

At this point, v1 still runs and takes no traffic. That is the blue/green position: v2 is live, v1 is the standby.

Step 4: Roll back

A pricing bug shows up after the cutover. The rollback sets the weights back to 100/0:

k8s/06-traffic-splitting/06-rollback.yaml

# Weighted split: v1=100, v2=0 (rollback). Weights are relative, they do not need to add up to 100.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: pricing
namespace: pedalshare-pricing
spec:
parentRefs:
- name: public
namespace: pedalshare-infra
sectionName: http
hostnames:
- pricing.pedalshare.local
rules:
- matches:
- path: {type: PathPrefix, value: /fares}
backendRefs:
- {name: pricing-api-v1, port: 80, weight: 100}
- {name: pricing-api-v2, port: 80, weight: 0}
$ kubectl apply -f k8s/06-traffic-splitting/06-rollback.yaml
$ until curl -s -H 'Host: pricing.pedalshare.local' localhost:8080/fares/quote \
| grep -q '"version":"v1"'; do sleep 0.2; done
rollback visible after 0s
$ scripts/count-versions.sh 300
300 v1

The first request after the apply already reached v1. The v1 Pods were running the whole time, so the rollback takes as long as one configuration update.

Step 5: Two cases to know

All weights at zero. A rule whose backends all have weight 0 has no destination. NGF answers 500:

$ kubectl apply -f k8s/06-traffic-splitting/05-all-zero.yaml
$ curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: pricing.pedalshare.local' localhost:8080/fares/quote
500

A canary without ready Pods. Back at 90/10, the v2 Deployment is scaled to zero, as if every v2 Pod were crashing:

$ kubectl apply -f k8s/06-traffic-splitting/01-canary-10.yaml
$ kubectl scale deploy pricing-api-v2 -n pedalshare-pricing --replicas=0
$ for i in $(seq 1 300); do curl -s -o /dev/null -w '%{http_code}\n' \
-H 'Host: pricing.pedalshare.local' localhost:8080/fares/quote; done | sort | uniq -c
272 200
28 503
$ kubectl get httproute pricing -n pedalshare-pricing -o jsonpath=\
'{range .status.parents[*].conditions[*]}{.type}={.status}{"\n"}{end}'
Accepted=True
ResolvedRefs=True

About 10% of the requests fail with 503, and the route status looks healthy. Watch the canary's error rate during a rollout, and set its weight to 0 when it fails.

Results

Weights v1 / v2Requestsv1v2
90 / 101000899101
90 / 10 + header rule1000891109
Header X-PedalShare-Canary: always1000100
50 / 501000512488
0 / 100 (cutover)100001000
100 / 0 (rollback)3003000
Edge caseResult on NGF 2.8.1
All backends at weight 0500
90 / 10 with no ready v2 Pods28 of 300 requests return 503, ResolvedRefs=True

Summary

  1. weight on backendRefs splits traffic by proportion, per request. It is core Gateway API and works the same on any implementation.
  2. Canary releases change the weights in steps, blue/green flips them between 100/0 and 0/100, and a rollback is one more edit that takes effect at once because both versions keep running.
  3. A header-match rule beats the weighted rule, so testers can always reach the new version.
  4. Weights ignore backend health. A canary with no ready Pods fails its share of requests while the route status stays green, so watch the canary's metrics.

The last lesson of the series shares one Gateway between teams in different namespaces with ReferenceGrant, and routes gRPC traffic with GRPCRoute.