3: Model Deployment

    Deployment Strategies

    A production endpoint is not a static artifact.

    Models are retrained on fresh data, hyperparameters are re-swept, feature engineering pipelines evolve, and bug fixes ship inside the inference code path that wraps the model.

    Every one of those changes produces a new registered model version, and every new version has to reach end users without dropping requests, without degrading latency past the negotiated service level, and without surfacing regressions on traffic that costs real money to lose.

    The deployment strategy is the contract that governs how a new version replaces the old one, and the two patterns the certification expects you to compare and operate are blue-green and canary.

    Comparison

    Blue-green and canary are not mutually exclusive primitives; on Mosaic AI Model Serving they are both implemented through the same low-level mechanism.

    A serving endpoint is a named resource that holds a list of served_entities and a traffic_config block.

    Each served_entity is a reference to a specific Unity Catalog model version (or, equivalently, a model alias) plus a workload sizing policy and scale-to-zero flag.

    The traffic_config block contains a list of routes, where each route names a served_entity_name and assigns it an integer traffic_percentage from 0 to 100.

    The sum across all routes must equal 100.

    The choice of deployment strategy is therefore the choice of which trajectory of traffic_config updates you apply over time, not the choice of a different deployment primitive.

    A blue-green deployment maintains exactly two served entities for the duration of the rollout. The blue entity holds the current production version and starts at 100% traffic; the green entity holds the candidate version and starts at 0% traffic.

    Once the green entity has warmed (the container is built, the model artifact is downloaded, dependencies are resolved, and the first invocation has completed successfully against synthetic traffic), the traffic flips atomically from 100/0 to 0/100. There is no intermediate state where the two versions share load.

    Rolling back is symmetric: flip back to 100/0 in a single API call. The strength of blue-green is its determinism.

    Either every request goes to the old version or every request goes to the new version; you never have to reason about partial exposure or about per-user routing fairness. The weakness is the corresponding weakness of any atomic switch: there is no blast-radius limit.

    If the green version contains a bug that surfaces only under production load, every user hits it the moment you cut over, and recovery time is measured by how fast you notice plus how fast you flip back. Blue-green is the right pattern when the test environment is high fidelity, when you have offline validation that has already eliminated regression risk to a high confidence level, and when traffic volume is moderate enough that a brief detection-and-rollback window does not translate into thousands of failed transactions.

    A canary deployment maintains the same two served entities but moves traffic in graduated steps. A canonical canary plan starts at 95/5, runs for a hold period (often 30 minutes to a few hours), checks an automated gate against latency, error rate, and any application-specific business metric the inference table can compute, then advances to 80/20, 50/50, 20/80, and finally 0/100. Each step is gated by the same metric checks; failure at any step rolls back to the previous split.

    The strength of canary is bounded blast radius. A regression at 5% exposure costs 5% of requests and surfaces before you commit the remaining 95%. The weakness is that the cutover takes longer, the dual cost of running both warm pools is higher, and the inference table contains rows from two versions that have to be joined back to the right model identifier when you compute drift or accuracy.

    Canary is the right pattern:

    • when traffic is large enough that a 5% slice is statistically meaningful within minutes,
    • when you cannot afford a multi-minute total outage window,
    • when the model produces user-visible output where regressions degrade revenue rather than just internal metrics.

    In practice

    A third pattern, shadow deployment, is sometimes confused with canary. In a shadow rollout the new version receives a duplicated copy of production requests but its responses are never returned to clients; only the live version's responses are returned. Shadow lets you measure end-to-end behavior of the candidate against real traffic without exposing users to its output.

    Mosaic AI Model Serving does not have a first-class shadow primitive; the customary workaround is to wrap the candidate inside a separate non-production endpoint and have an upstream client (or a Lakeflow Job consuming the inference table) duplicate requests to both endpoints, then compare responses offline. Treat shadow as a complement to canary, not a replacement: shadow proves that the model behaves correctly on real data, canary proves that real users tolerate its predictions.

    Evaluating Suitability for High-Traffic Applications

    Key points

    High-traffic applications introduce constraints that change which strategy is the right default.

    The first constraint is recovery time. At 50,000 requests per second a one-minute detection-and-rollback window means three million potentially affected requests; canary at 5% caps that exposure at 150,000 even if the regression is severe, while blue-green exposes all three million.

    The second constraint is provisioned throughput economics. Serving endpoints configured with provisioned throughput reserve dedicated capacity per served entity; running blue and green simultaneously at full provisioned throughput doubles the bill, which matters far more on a high-traffic endpoint than on a low-traffic one. Canary mitigates this by sizing the green entity small while it carries only 5% of traffic and resizing it as the split grows.

    The third constraint is statistical detection. With 50 requests per minute, a 5% canary takes hours to accumulate enough samples to detect a 2-point accuracy drop with confidence; on a high-traffic endpoint with 50,000 requests per minute the same canary yields meaningful signal in seconds, which means canary becomes both safer and more useful as traffic grows.

    The fourth constraint is request affinity. If the application has stateful behavior per user (for example, a recommendation model that personalises ranking based on the user's previous responses), randomly splitting an individual user between two model versions can produce visibly inconsistent recommendations within a single session.

    The mitigation is to route at the upstream client layer using a stable hash of the user ID rather than letting the endpoint randomise per request. Mosaic AI Model Serving routes per request by default; if you need session-level affinity you build it in the calling application by selecting an endpoint URL based on the hashed user ID.

    🎯 Scenario: A retail recommendation service handles 18,000 requests per second at peak with a 95th-percentile latency target of 80 ms. The team retrained the ranking model on an updated feature set and validated it offline against the holdout floor in Chapter 2. They face a choice between blue-green and canary. The risk profile says a wrong cut affects merchandising revenue within minutes. The team picks canary at 5/95, holds for 20 minutes, compares the inference table partition for the new version against the baseline drift profile, then promotes through 25/75 and 60/40 over the next two hours. A latency regression at 25/75 (the new version takes 130 ms p95 because the added feature lookup hits an offline table instead of an online table) triggers an automatic rollback to 5/95 before reaching the full cutover, and the team fixes the lookup before retrying. Blue-green would have exposed the full 18,000 rps to the latency regression in a single step.

    Implementing a Model Rollout Strategy Using Databricks Model Serving

    The implementation of any rollout strategy on Mosaic AI Model Serving comes down to two artefacts: the endpoint configuration and the orchestration that mutates it over time.

    The endpoint configuration is best authored declaratively (through Databricks Asset Bundles or Terraform) when it represents the steady state, and imperatively (through the Databricks SDK or the MLflow Deployments SDK) when it represents an in-flight rollout.

    The steady-state declarative form, expressed as a Databricks Asset Bundle resource, looks like this:

    resources:
     model_serving_endpoints:
     claims_classifier_endpoint:
     name: claims-classifier-prod
     config:
     served_entities:
     - name: champion
     entity_name: prod_ml.risk.claims_classifier
     entity_version: "27"
     workload_size: Medium
     workload_type: CPU
     scale_to_zero_enabled: false
     min_provisioned_throughput: 100
     max_provisioned_throughput: 800
     traffic_config:
     routes:
     - served_entity_name: champion
     traffic_percentage: 100
     auto_capture_config:
     catalog_name: prod_ml
     schema_name: risk
     table_name_prefix: claims_classifier_inference
     enabled: true
     tags:
     - key: environment
     value: prod
     - key: owner
     value: risk_ml_team
    

    This represents the steady state: one served entity, 100% traffic, inference capture enabled into the Unity Catalog table prod_ml.risk.claims_classifier_inference_payload.

    When a new candidate model version is registered and assigned the @challenger alias, the rollout job loads this endpoint, mutates served_entities and traffic_config, and applies the change with the Databricks SDK.

    The blue-green imperative form uses two calls. The first call adds the new served entity at 0% traffic so it has time to warm:

    from databricks.sdk import WorkspaceClient
    from databricks.sdk.service.serving import (
     EndpointCoreConfigInput,
     ServedEntityInput,
     TrafficConfig,
     Route,
     AutoCaptureConfigInput,
    )
    
    w = WorkspaceClient()
    endpoint_name = "claims-classifier-prod"
    
    new_version = w.registered_models.get_alias(
     full_name="prod_ml.risk.claims_classifier", alias="challenger"
    ).model_version
    
    w.serving_endpoints.update_config_and_wait(
     name=endpoint_name,
     served_entities=[
     ServedEntityInput(
     name="champion",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version="27",
     workload_size="Medium",
     workload_type="CPU",
     scale_to_zero_enabled=False,
     ),
     ServedEntityInput(
     name="challenger",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version=str(new_version),
     workload_size="Medium",
     workload_type="CPU",
     scale_to_zero_enabled=False,
     ),
     ],
     traffic_config=TrafficConfig(
     routes=[
     Route(served_entity_name="champion", traffic_percentage=100),
     Route(served_entity_name="challenger", traffic_percentage=0),
     ]
     ),
    )
    

    The update_config_and_wait call blocks until the new served entity reaches the READY state, which is when the container has built, the model has loaded, and the readiness probe has succeeded. Only at that point is it safe to send live traffic. The second call performs the atomic flip:

    w.serving_endpoints.update_config_and_wait(
     name=endpoint_name,
     served_entities=[
     ServedEntityInput(
     name="champion",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version="27",
     workload_size="Medium",
     workload_type="CPU",
     scale_to_zero_enabled=False,
     ),
     ServedEntityInput(
     name="challenger",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version=str(new_version),
     workload_size="Medium",
     workload_type="CPU",
     scale_to_zero_enabled=False,
     ),
     ],
     traffic_config=TrafficConfig(
     routes=[
     Route(served_entity_name="champion", traffic_percentage=0),
     Route(served_entity_name="challenger", traffic_percentage=100),
     ]
     ),
    )
    

    After a soak period during which the inference table is monitored for accuracy and latency regressions, the old served entity is removed (or, equivalently, the names are rotated: the old champion is dropped, the old challenger is renamed to champion, and the registry alias @champion is moved to point at the version the new champion serves).

    The canary imperative form is the same primitive applied iteratively.

    A canary controller, typically a Lakeflow Job notebook that runs after a candidate model is promoted to @challenger, walks a list of splits and gates each step:

    from databricks.sdk import WorkspaceClient
    from databricks.sdk.service.serving import (
     ServedEntityInput,
     TrafficConfig,
     Route,
    )
    import time
    
    CANARY_STEPS = [
     {"champion": 95, "challenger": 5, "hold_minutes": 30},
     {"champion": 75, "challenger": 25, "hold_minutes": 60},
     {"champion": 40, "challenger": 60, "hold_minutes": 60},
     {"champion": 0, "challenger": 100, "hold_minutes": 0},
    ]
    
    
    def apply_split(w, endpoint_name, champion_version, challenger_version, split):
     w.serving_endpoints.update_config_and_wait(
     name=endpoint_name,
     served_entities=[
     ServedEntityInput(
     name="champion",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version=str(champion_version),
     workload_size="Medium",
     scale_to_zero_enabled=False,
     ),
     ServedEntityInput(
     name="challenger",
     entity_name="prod_ml.risk.claims_classifier",
     entity_version=str(challenger_version),
     workload_size="Small",
     scale_to_zero_enabled=False,
     ),
     ],
     traffic_config=TrafficConfig(
     routes=[
     Route(served_entity_name="champion",
     traffic_percentage=split["champion"]),
     Route(served_entity_name="challenger",
     traffic_percentage=split["challenger"]),
     ]
     ),
     )
    
    
    def gate_passes(spark, endpoint_name, split_start_time, error_rate_floor=0.005):
     df = spark.read.table("prod_ml.risk.claims_classifier_inference_payload")
     window = df.filter(
     (df.served_entity_name == "challenger")
     & (df.request_time > split_start_time)
     )
     total = window.count()
     if total < 500:
     return False
     error_rate = window.filter(window.status_code >= 400).count() / total
     return error_rate <= error_rate_floor
    
    
    def run_canary(spark, w, endpoint_name, champion_v, challenger_v):
     for step in CANARY_STEPS:
     apply_split(w, endpoint_name, champion_v, challenger_v, step)
     split_start = time.time()
     time.sleep(step["hold_minutes"] * 60)
     if step["hold_minutes"] > 0 and not gate_passes(
     spark, endpoint_name, split_start
     ):
     apply_split(
     w, endpoint_name, champion_v, challenger_v,
     {"champion": 100, "challenger": 0},
     )
     raise RuntimeError(
     f"Canary gate failed at split {step}, rolled back to 100/0"
     )
    

    The auto_capture_config from the endpoint definition is what makes the gate possible: every request and response is written to the inference table the controller reads on each iteration. Without inference capture there is no automated gate, and canary degenerates into time-based promotion that gives you the cost of canary without the safety.

    💡 Exam Trap: A common wrong answer claims that Mosaic AI Model Serving has a dedicated deployment_strategy: canary parameter that the controller sets to "canary" or "blue-green". There is no such parameter. The endpoint exposes served_entities and traffic_config; the strategy is whatever sequence of updates you apply. If the question presents a hypothetical strategy field, the answer that mentions traffic_config routes with integer percentages is the one grounded in the actual API.

    💡 Exam Trap: Another trap asks how to "promote" a canary by changing the @champion alias in Unity Catalog. Moving an alias does not change endpoint routing on its own. If the served entity references a specific entity_version (the typical configuration shown above), the endpoint continues to serve that frozen version even after the alias moves. To get alias-tracking behaviour you must define the served entity with entity_version omitted and entity_name pointing at the alias path prod_ml.risk.claims_classifier@champion, which causes the endpoint to follow the alias. Most production endpoints pin to explicit versions because version-pinning is what makes rollback deterministic.

    ⚠️ Anti-Pattern: Sending the first live request to a newly added served entity before it has reached READY state. The serving plane is still building the container; the request will either time out or land on the old entity by fallback, masking the cold-start failure. Always either call update_config_and_wait (which blocks until READY) or poll the endpoint state with w.serving_endpoints.get(name=endpoint_name) until state.config_update == "NOT_UPDATING" and pending_config is None before advancing the traffic split.

    📊 Limit: A serving endpoint supports up to 15 served entities at once, with the sum of traffic_percentage across routes equal to 100. Workload sizes are Small, Medium, and Large. Scale-to-zero is mutually exclusive with provisioned throughput, and the cold start of a scale-to-zero endpoint typically takes between 30 seconds and a few minutes depending on container size. Always verify the live published limits in the Databricks documentation before the exam, because they evolve.

    Comparing Blue-Green and Canary Side by Side

    The decision between strategies is not abstract; it is a per-endpoint choice driven by traffic volume, regression tolerance, and statistical detection windows. The following decision tree captures the typical reasoning path.

    Decision Tree: Choosing Between Blue-Green and Canary

    The two patterns are summarised in the following matrix.

    DimensionBlue-GreenCanary
    Exposure during cutover0% then 100% atomicGraduated steps (5, 25, 60, 100)
    Blast radius if regression appearsEntire request volumeLimited to current split percentage
    Time to fully promoteSingle API call after warm periodHours, governed by hold periods
    Cost during rolloutBoth entities warm at full sizeBoth entities warm; challenger often smaller initially
    Rollback complexitySingle flip back to 100/0Reapply previous split, then 100/0
    Statistical detection on low-volume endpointsEqually bad either wayWorse because each split has fewer samples
    Inference table cardinalityTwo version IDs over the cutover windowTwo version IDs over the entire rollout window
    Best fitInternal services, batch fan-out, well-validated changesUser-facing endpoints with revenue exposure

    The cheat sheet at the end of the chapter consolidates these into single-row reminders, but the matrix above is the comparison you should be able to reproduce from memory before sitting the exam.

    Decision Anchor

    Choose blue-green when the candidate has passed a high-fidelity integration test that includes load testing at expected production rps, when the endpoint is internal or back-office (so a brief regression is acceptable), and when the cost of running two full-sized served entities for the cutover window is bounded. Choose canary when the endpoint serves user-visible traffic at high volume, when a regression has direct revenue or trust consequences, when the inference table accumulates enough samples in the first hold period to make automated gating statistically meaningful, and when you have an inference table monitor (Chapter 2's InferenceLog profile) that can produce a gating signal within the hold window.

    Default to canary on any endpoint above roughly 1,000 requests per second; default to blue-green on low-traffic internal endpoints where canary cannot detect anything meaningful inside an operational window.

    Rollback, Version Cleanup, and Alias Hygiene

    A deployment strategy is incomplete without a rollback path.

    On Mosaic AI Model Serving rollback is the same update_config_and_wait call with the previous traffic split.

    The complication is the registry alias. If the rollout job moved @champion to point at the new version before the canary completed, a partially rolled-back endpoint now contradicts the alias.

    The disciplined pattern is to move @champion only after the final 100/0 split has cleared its hold period. Until then the alias remains on the old version and the new version carries @challenger.

    If rollback is triggered the alias has not moved and there is nothing to undo on the registry side; if the rollout completes, the alias move is the final step that signals "this is the new production version, retraining jobs and downstream consumers should now reference it."

    Version cleanup is the parallel concern. Each rollout produces a new model version, and the registry accumulates them. The retention policy depends on the lifecycle target:

    • keep the last N versions (often 10)
    • archive older ones via client.delete_model_version, never the entire registered model.

    Always retain at least:

    • the version presently referenced by @champion
    • the version presently referenced by @challenger
    • the version one rollback step behind both, because emergency rollback may need to reach the version before the one previously serving.

    🎯 Scenario: A team operates a fraud scoring endpoint with three rollouts per week. After six months the registered model prod_ml.risk.fraud_scorer has 78 versions, most of them long-since archived candidates that never made it to production. A nightly Lakeflow Job lists all versions, filters out the ones referenced by any active alias (@champion, @challenger, @last_known_good) and any version produced in the last 14 days, then calls delete_model_version on the rest. The retention floor of 14 days plus the alias protection covers the emergency rollback window. Without this job the registry browse view becomes unusable and search_model_versions API calls slow under the accumulated history.

    ⚠️ Anti-Pattern: Deleting a model version that is still referenced by an active served entity. The endpoint configuration holds the version string, but the artifact resolution happens at container build time; deleting the version causes the next config update to fail and any restart of the existing replicas to fail. Always check w.serving_endpoints.get(...) for each endpoint and confirm the version is not in config.served_entities[*].entity_version before deletion.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Machine Learning Professional learning hub.