Sub topic 3
Splitting Traffic Between Model Versions
This chapter assumes you can serve a model behind an HTTP or RPC endpoint, read short Python and YAML snippets, and understand proportions and percentages. It covers how to send some requests to a stable model and some to a candidate. Later chapters build shadow, canary, and A/B rollouts on this mechanism.
Why traffic splitting comes first
Every rollout strategy in this tutorial depends on one decision: for each request, which model version should handle it, or which versions should see it? Shadow deployments copy requests to a candidate. Canary releases send a small share of real traffic to it. A/B tests assign users to variants and compare outcomes. All three need a router that makes this choice reliably.
A router has three properties you will want to control:
- Share. What fraction of traffic goes to each version.
- Stickiness. Whether the same user or entity keeps getting the same version across requests.
- Location. Where the decision is made: network infrastructure, an application gateway, or code inside the service.
Where to split
You can make the split at several layers. Each layer trades control for convenience.
| Layer | Example | Strengths | Limits |
|---|---|---|---|
| Service mesh or ingress | Istio VirtualService, Envoy, NGINX | No application code changes. Easy to change weights. | Usually per request, not per user. Limited access to business identifiers. |
| API gateway or load balancer | Weighted target groups, gateway plugins | Simple, managed, and familiar. | Coarse control. Sticky sessions may be tied to cookies or IPs. |
| Application code | A router or feature flag library | Full control over the assignment unit, salt, and logging. | You own the code and its bugs. |
| Model server | Multi-model endpoints with traffic weights | Versions share one deployment. | Tied to the serving platform's features. |
A common pattern combines two layers. The mesh handles coarse canary percentages, and application code handles experiments that need user-level assignment.
Weighted routing in a service mesh
In Istio, a VirtualService defines weights across subsets of a service. The subsets themselves (here stable and candidate) are defined in a DestinationRule that maps each name to pod labels.
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: fraud-model
spec:
hosts:
- fraud-model
http:
- route:
- destination:
host: fraud-model
subset: stable
weight: 95
- destination:
host: fraud-model
subset: candidate
weight: 5Weights in one route must sum to 100. This configuration sends about 95% of requests to the stable subset and about 5% to the candidate.
The word "about" matters. The mesh picks a destination per request, using a random draw. With 1,000 requests you might see 41 or 58 candidate requests instead of exactly 50. The share converges to 5% only as volume grows.
A matching DestinationRule looks like this:
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: fraud-model
spec:
host: fraud-model
subsets:
- name: stable
labels:
version: v1
- name: candidate
labels:
version: v2If a subset has no healthy pods, requests routed to it fail. A weight is a routing instruction, not a guarantee of capacity, so make sure the candidate deployment has enough replicas for its share.
Per-request versus per-user assignment
The assignment unit is the thing you randomize: a request, a session, a user, a device, an account, or a group such as a store or region. The choice has consequences.
- Per request. Simple and gives the fastest sample growth. Suitable for stateless checks such as error rate and latency. Unsuitable when one user's experience spans many requests, because a user can see both models.
- Per user. Each user sees one version for the whole experiment. Needed for outcomes measured per user, such as conversion or retention.
- Per cluster. Randomize whole groups when users influence each other, for example sellers in a marketplace. This reduces interference but gives fewer independent units and less statistical power.
Choose the unit to match the metric you will judge by. If the outcome is "did this user convert", assign by user. The statistical consequences are covered in later chapters.
Deterministic, sticky assignment with hashing
To make assignment sticky without storing a lookup table, hash a stable identifier. The same input always gives the same output, so the same user always lands in the same bucket.
import hashlib
def bucket(unit_id: str, salt: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest()
return int(digest, 16) % buckets
def choose_variant(unit_id: str, salt: str, candidate_percent: float) -> str:
threshold = int(candidate_percent * 100) # percent of 10000 buckets
return "candidate" if bucket(unit_id, salt) < threshold else "stable"
print(choose_variant("user-123", "ranker-v2-exp1", 5))How it works:
- The salt and the unit ID are joined and hashed with SHA-256.
- The hash is converted to an integer and reduced modulo 10,000, giving a bucket from 0 to 9,999.
- Buckets below the threshold go to the candidate. With 5 percent, the threshold is 500, so buckets 0 to 499 are the candidate.
Using 10,000 buckets gives a resolution of 0.01 percent, which is useful when a canary starts at a fraction of a percent.
Why the salt matters
The salt names the experiment. Two properties follow from it.
- Independence between experiments. If every experiment hashed only the user ID, the same users would always fall in the low buckets. They would receive every candidate, and results from different experiments would be correlated. A different salt per experiment reshuffles users.
- Reshuffling on purpose. If an experiment is contaminated and must restart, change the salt to draw a fresh assignment.
Do not use Python's built-in hash() for this. For strings it is randomized per process, so different servers would disagree about the same user.
Ramping up without reshuffling
Because the threshold is the only thing that changes, raising a canary from 5 percent to 25 percent keeps the original 5 percent in the candidate group. Buckets 0 to 499 stay in, and buckets 500 to 2,499 are added. Users never flip back and forth between versions during a staged ramp. This only holds when the salt stays the same, so keep it fixed for the whole rollout.
Rolling back is the reverse: set the threshold to 0. Users return to stable immediately.
Keeping other things stable
Stickiness depends on the identifier you hash, so check these cases:
- Anonymous users. If the user is not logged in, you may only have a cookie or device ID. The user may get a new assignment on a new device or after clearing cookies.
- Identifier changes. If a user ID is created at signup, a user may be anonymous before signup and identified after. Pick one unit and handle the transition explicitly.
- Missing IDs. Decide what happens when the ID is absent. Sending those requests to stable is the safe default. Log them so you can see how often it happens.
- Caches. A CDN or response cache keyed only on the URL can serve one version's response to users in the other group. Include the variant in the cache key or bypass the cache for experiment traffic.
- Retries. A retry should reach the same version as the original request, or the observed error rates will blur.
Visualizing a routed request
The log entry is part of the routing design. If the variant is not recorded with each request, you cannot later tell which users saw which model. The next chapter covers what to log.
Common errors
- Mismatched weights. Weights that do not sum to 100 are rejected or behave unexpectedly, depending on the platform.
- Missing subset definitions. A VirtualService that references a subset not defined in a DestinationRule fails requests routed to it.
- Reusing a salt across experiments. This correlates assignments and makes results hard to interpret.
- Changing the salt mid-experiment. Users are reshuffled, so their earlier exposure contaminates the new groups.
- Different hash implementations in different services. If the gateway and the model service both assign users with different code, the two can disagree. Assign once, then pass the variant downstream in a header.
- Assuming the split is exact. A 5 percent target never yields exactly 5 percent in a finite sample. A large, unexplained gap is a symptom worth investigating, and later chapters cover it as sample ratio mismatch.
Checking your split
Before trusting any rollout, verify the router. A quick simulation shows whether the hash spreads users evenly:
import hashlib
def bucket(unit_id: str, salt: str, buckets: int = 10000) -> int:
digest = hashlib.sha256(f"{salt}:{unit_id}".encode()).hexdigest()
return int(digest, 16) % buckets
def candidate_share(salt: str, percent: float, users: int = 100000) -> float:
threshold = int(percent * 100)
hits = sum(1 for i in range(users) if bucket(f"user-{i}", salt) < threshold)
return hits / users
print(candidate_share("ranker-v2-exp1", 5))
print(candidate_share("ranker-v2-exp2", 5))Both numbers should be close to 0.05. In production, run the same check on logged assignments, comparing the observed share with the intended one.
Exercise
A team runs an A/B test where the outcome is whether each user makes a purchase. They route traffic with an Istio weighted route of 90/10. Users complain that the product ranking changes between page loads. What is the problem, and how would you fix it?
Show answer
The mesh picks a version independently for each request, so a user's page loads can be served by different models. The assignment unit is the request, but the outcome is measured per user. Fix it by assigning at the user level: hash the user ID with an experiment-specific salt in the gateway or application, then pass the chosen variant downstream (for example in a header that the mesh routes on). Log the variant with every request.
Exercise
A canary uses choose_variant with a threshold of 5 percent. The team raises it to 20 percent and also changes the salt "to be tidy". What goes wrong?
Show answer
Changing the salt reshuffles every user's bucket. Many users who were in the 5 percent candidate group move back to stable, and many stable users move to the candidate, so exposure is no longer a clean ramp-up. Any per-user metrics now mix users who saw both versions. Keep the salt fixed and only raise the threshold, which preserves the original candidate users.