Migrate a Production AI Stack Without a Flag Day
Move interfaces, state, models, routing, and ownership through expand, migrate, verify, and separately authorized contract stages while old and new paths can coexist safely.
- Authorship
- InterviewsVector
- Published / updated
- 2026-09-27 / 2026-09-27
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector teaching. Executable artifacts are deterministic illustrative audits with focused tests and recorded primary sources; they do not claim legal interpretation, policy compliance, live-system validation, architecture approval, deployment, migration execution, production readiness, or safety certification.
The decision in one pass
Avoid a flag day by making the target path additive before it is authoritative. Freeze source and target identities, interfaces, data meaning, evaluation policy, traffic policy, SLOs, and rollback requirements. Expand contracts and storage so old readers and writers continue to work; make dual writes idempotent and observable; backfill from a stable boundary with reconciliation; shadow representative work without duplicating side effects; compare semantic quality, safety, errors, latency, cost, and state; then move a bounded cohort or traffic fraction while the source remains ready. Hold on incomplete compatibility or evidence, roll back on demonstrated regressions, and stop and escalate rather than claiming rollback when source capacity or the rollback route is unavailable. After target traffic reaches its ceiling, verify through declared windows and reconcile every consumer, job, dataset, secret, alert, and recovery procedure. Contract only through a separate explicit change after approval and retained rollback evidence. The reference planner returns one replay-safe proposal from invented records; it does not migrate data, route traffic, or remove the old stack.
Why this matters
An AI stack is more than an endpoint. Prompts, model and tokenizer revisions, embeddings, vector indexes, schemas, tools, safety policy, evaluation sets, caches, traces, budgets, and human workflows encode contracts that may cross team and vendor boundaries. Replacing them together creates an unbounded causal surface: when quality, latency, or cost moves, nobody knows which change caused it, and state mutations may make rollback impossible. Parallel change preserves compatibility and observability long enough to learn, but only if dual-run behavior, evidence, and eventual retirement are explicitly designed.
You will be able to
- Decompose an AI stack migration into expand, migrate, verify, and independently authorized contract stages with a valid rollback path at every non-destructive step.
- Design compatibility, dual-write, backfill, shadow, comparison, canary, reconciliation, and traffic controls without duplicating irreversible side effects.
- Bind migration evidence to exact source, target, interface, data, evaluation, routing, rollback, and fixture identities.
- Distinguish incomplete readiness that should hold from measured target regression that should route back to the source.
- Defend when the old path may be retired and why full target traffic is not by itself proof that contraction is safe.
Prerequisite contract
Your Vector Loop for this lab
- 01
Model
Map every source and target interface, state owner, reader, writer, model and tokenizer, embedding and index, provider, side effect, SLO, evaluation, route, batch job, secret, dashboard, incident procedure, dependency, and retirement obligation.
- 02
Derive
Derive additive compatibility, dual-write and backfill semantics, idempotency keys, shadow isolation, comparison metrics, bounded traffic stages, reconciliation proofs, rollback triggers, verification windows, and contraction authorization.
- 03
Build
Build adapters, versioned contracts, deterministic transforms, replay-safe workers, shadow and canary routing, evidence joins, a transition ledger, and a pure next-action planner; keep live mutation behind separately authorized controllers.
- 04
Stress
Inject old clients, duplicate and reordered events, partial backfill, transform bugs, side-effect leakage, provider drift, comparison bias, stale caches, index skew, target regression, source loss, controller restart, and premature contraction.
- 05
Operate
Observe compatibility errors, dual-write and backfill coverage, reconciliation mismatch, shadow agreement, quality and safety slices, latency, cost, route fraction, state lag, rollback capacity, unknown consumers, and verification age by revision.
- 06
Defend
Defend the causal boundary of each stage, retry and rollback semantics, evidence representativeness, remaining consumers, source-retention cost, contraction authority, and the exact proof required to remove the old path.
Map the contracts before moving the implementation
Start by drawing the source and target as behavior and state contracts rather than boxes. Enumerate synchronous APIs, streaming events, schemas, vector and cache formats, model inputs and outputs, tool calls, policy decisions, batch jobs, human queues, dashboards, alerts, and recovery procedures. Identify every reader and writer, including scripts and analytical jobs that are absent from request traces. Freeze the baseline workload and evaluation contract so a target cannot appear equivalent merely because the question changed.
| Surface | Compatibility question | Rollback hazard |
|---|---|---|
| API and events | can old and new producers and consumers overlap? | new payload cannot be read by the source |
| state and schema | are writes additive, deterministic, idempotent, and reconcilable? | target writes destroy source meaning |
| model behavior | which slices define semantic agreement and allowed difference? | new outputs trigger irreversible downstream action |
| retrieval and embeddings | can revisions coexist without mixing incompatible vectors? | index or cache state cannot be reconstructed |
| operations | do both paths have capacity, ownership, telemetry, secrets, and runbooks? | source exists on paper but cannot receive traffic |
Sequence expand, migrate, verify, then contract
- 01ExpandAdd target interfaces, optional fields, adapters, versioned state, observability, and target capacity while preserving all source behavior. Prove mixed-version operation before sending target traffic.
- 02MigrateDual-write or transform replayably, backfill from a stable checkpoint, shadow representative reads, reconcile state, and move bounded cohorts or traffic only when compatibility and comparison gates pass.
- 03VerifyAt the declared target ceiling, observe complete windows, detect unknown consumers, reconcile state and outcomes, exercise rollback, and retain the source while evidence accumulates.
- 04Contract separatelyAfter explicit approval, remove source reads, writes, routes, state, credentials, dashboards, and support in small reviewable changes. Verify each removal; do not smuggle destructive cleanup into the traffic migration.
safe_next_stage = compatibility ∧ replayability ∧ reconciliation ∧ representative_evidence ∧ rollback_ready
Traffic percentage alone is not a migration stage. Advancement requires the cross-layer invariants that preserve old and new operation and make recovery possible.
Compare behavior without duplicating consequences
Shadow traffic is safe only when the target's effects are isolated. Reuse recorded inputs or mirror sanitized requests with stable identity, but suppress external writes, messages, billing, user-visible output, and tool actions unless a purpose-built sandbox captures them. Compare the right semantics: exact text equality may be meaningless for generative output, while matching availability can conceal quality or safety regression. Use task rubrics, calibrated evaluators, critical slices, deterministic fields, structured side-effect plans, latency, cost, and human review where consequence warrants it.
| Evidence | What it can show | What can still fool it |
|---|---|---|
| dual-write coverage | both state paths received declared writes | the transform may be consistently wrong |
| backfill completion | declared records were processed | late, deleted, or out-of-scope records may be absent |
| reconciliation | source and target state agree under a comparator | the comparator may ignore meaningful fields |
| shadow agreement | target behavior matches declared semantics on sampled work | traffic bias, evaluator blind spots, hidden side effects |
| canary outcome | real target behavior for a bounded cohort | small samples and delayed harm |
- Give every source event, backfill record, dual write, comparison, and retry a stable identity so duplicates and omissions are observable.
- Record transform and comparator revisions; changing either invalidates prior reconciliation evidence.
- Separate source-versus-target error and latency from shared dependency failures so rollback decisions have a causal basis.
- Preserve privacy, access, retention, and purpose constraints when copying or replaying production-derived data.
- Define how to compensate or manually reconcile any side effect that cannot be made idempotent or reversed.
Propose one replay-safe transition
The reference planner consumes invented aggregate evidence. Frozen records bind interface, data, evaluation, routing, rollback, and fixture identities to exact source and target revisions. It distinguishes compatibility and readiness gaps that hold from measured agreement, error, or latency regressions that roll exposed traffic back. If regression is present but source capacity or the rollback route is unavailable, it returns `STOP_AND_ESCALATE` and does not pretend traffic can be restored. It caps every advance, turns the traffic ceiling into an explicit verify transition, and refuses to authorize contraction without full traffic, verification windows, retained rollback evidence, and a separate approval.
1def plan_migration(contract: MigrationContract, evidence: MigrationEvidence) -> MigrationPlan:2 contract = validate_record(contract, MigrationContract)3 evidence = validate_record(evidence, MigrationEvidence)4 if evidence.scope != contract.scope or evidence.contract_content_id != contract.content_id:5 raise ValueError("evidence belongs to another migration contract")6 7 # Regressions roll back only while the source route remains viable;8 # otherwise stop and escalate. Readiness gaps hold, passing evidence9 # advances once, and contraction remains separately authorized.Expected output
example=illustrative_only
decision=ADVANCE_BOUNDED_TRAFFIC
phase=MIGRATE;source=ai-stack-v4;target=ai-stack-v5
target_traffic=0.25->0.50
claim=LOCAL_MIGRATION_PLAN_NOT_EXECUTION_OR_PRODUCTION_CERTIFICATIONVerify: python3 -m unittest discover -s courses/ai-engineering/reference-impl/architecture_migration -p 'test_*.py' -v
Choose the next reversible migration action
Inspect invented compatibility, dual-write, backfill, shadow, quality, latency, traffic, verification, and rollback evidence. Predict advance, hold, rollback, or separate contraction authorization before revealing the local decision; no system is changed.
Choose the next migration action
A reversible migration advances from complete evidence, not optimism. Inspect comparison coverage, outcome slices, state reconciliation, authority, and rollback readiness.
Illustrative migration records only. A real cutover requires system-specific data, safety, security, and operational approval.
| Signal | Declared constraint | Available evidence |
|---|---|---|
| comparison | ≥ 99.5% eligible records | 99.8% compared; exclusions classified |
| outcomes | no hard-slice regression | all hard slices pass at 10% exposure |
| state | reconciled through watermark | zero unresolved writes before cutoff |
| rollback | ≤ 5 minutes and tested | 3m 12s drill on the deployed revision |
Commit to a decision before revealing the bounded recommendation.
Rehearse the failures that make rollback dishonest
| Failure | Why a shallow plan misses it | Required defense |
|---|---|---|
| partial dual write | request success hides target omission | outbox or durable retry, idempotency, lag and dead-letter reconciliation |
| poisoned backfill | job completion counts processed records | deterministic transform, quarantine, checkpoints, source totals, semantic diff |
| shadow side effect | response is discarded but tools still execute | effect isolation, sandboxed credentials, plan-only tool adapters |
| source decay | old route exists but capacity or credentials were removed | continuous source health, capacity floor, rollback drills |
| unknown consumer | top services migrated while a batch job remains | consumer inventory, access and schema telemetry, deprecation window |
| controller replay | restart repeats a backfill or traffic increment | durable transition identity and idempotent desired-state reconciliation |
Rollback triggers should be observable and tied to the target: semantic regression on a critical slice, error-rate increase, tail-latency ratio, cost or capacity loss, reconciliation divergence, safety incident, or control failure. Decide whether recovery means route-only rollback, source-of-truth restoration, compensating writes, replay, or incident containment. A dual-write bug can corrupt both paths; keeping the source process alive does not undo that state.
Finish the migration without erasing its proof
Full target traffic begins verification; it does not prove that old readers, offline jobs, rollback data, dashboards, or human procedures are gone. Hold through a declared observation window, reconcile source and target, scan access and dependency evidence, exercise recovery, and obtain explicit contraction approval. Then retire one dependency at a time. Preserve decision records, migration manifests, transform versions, reconciliation results, incidents, and final state proofs even after temporary dual-run telemetry is removed.
- 01Prove target authorityConfirm all authorized traffic and state ownership use the target while quality, safety, reliability, latency, and cost remain inside the declared envelope.
- 02Prove consumer exitCombine repository, runtime, access, event, job, and owner evidence; one quiet log window is not proof that a monthly or disaster-recovery consumer migrated.
- 03Authorize contractionRecord accountable approval, residual risk, retention boundary, recovery alternative, sequencing, stop conditions, and the exact old capability each change removes.
- 04Verify every removalRemove routing, writes, reads, storage, credentials, capacity, alerts, code, and contracts in bounded steps with observation between them; archive the final evidence ledger.
Operate at three altitudes
Production lens
- — Correlate source and target identities, compatibility errors, dual writes, backfill checkpoints, reconciliation, shadow comparisons, quality and safety slices, latency, cost, traffic, rollback capacity, consumers, and controller transitions in one migration ledger.
- — Exercise duplicate and reordered events, partial writes, worker restart, corrupt transform, biased shadow sample, side-effect leakage, stale cache and index, target regression, source failure, rollback under load, unknown consumers, and aborted contraction.
- — Retain the source route, compatible state, capacity, credentials, telemetry, ownership, and runbook until explicit verification and contraction criteria pass; measure whether rollback works instead of inferring it from artifact existence.
Staff lens
- — Sequence migration ownership across product, platform, data, model, evaluation, security, safety, infrastructure, finance, support, and dependent teams so each transition has one authority and one observable exit criterion.
- — Budget the temporary complexity and cost of dual running, define a deadline and accountable owner for contraction, and refuse both a risky flag day and an endless half-migration with two permanent sources of truth.
Interview defense
Migrate a production AI feature from a managed model and legacy retrieval stack to a self-hosted model, new embeddings, and a new vector index without a flag day.
I would first freeze source and target identities, interface and data semantics, workload and evaluation slices, SLO and cost boundaries, side effects, consumers, and rollback state. I would expand with versioned adapters, separate embedding and index namespaces, idempotent dual writes, target capacity, and revision-bound telemetry while old readers keep working. A checkpointed backfill writes only the target namespace and reconciles counts and semantic samples. Shadow requests use sandboxed tools and suppress external effects; comparisons cover task quality, safety, deterministic fields, latency, cost, and critical cohorts. I would canary one bounded cohort, keep source capacity and compatible state, and roll back on target-attributable regression while holding on incomplete evidence. After full target traffic, I would verify through declared windows, prove every online and offline consumer exited, rehearse recovery, and request separate contraction approval. I would remove source dependencies one at a time and retain the transition ledger. Full traffic is not permission to delete the source.
Expect the interviewer to press on
- — How do you shadow requests that can call tools or send messages?
- — What evidence proves an embedding and index migration is semantically complete?
- — When does rollback require data repair rather than only routing traffic back?
Misconceptions to remove
“Blue-green deployment alone makes an AI stack migration reversible.”
It can preserve two compute environments, but schemas, state writes, embeddings, indexes, caches, tools, provider behavior, and external side effects still need compatibility, reconciliation, and recovery design.
“If shadow outputs usually look similar, the target is ready.”
Readiness also requires representative slices, meaningful semantic and safety comparators, isolated effects, complete state migration, operating capacity, latency and cost evidence, and a tested rollback route.
“Once one hundred percent of traffic reaches the target, the source can be deleted.”
Full traffic only begins verification. Offline consumers, delayed effects, unreconciled state, rollback evidence, retention obligations, and separate contraction authorization remain.
Check your model
1. Why must dual writes be idempotent and independently observable?
Retries, reordering, and partial failure are normal during migration. Stable identity prevents duplicate effects, while independent evidence distinguishes a successful source write from a missing or corrupt target write.
2. When should a migration hold rather than roll back?
Hold when compatibility, coverage, freshness, observability, capacity, or rollback evidence is incomplete but demonstrated target harm is absent. Roll exposed traffic back when target-attributable quality, error, latency, safety, or state evidence violates a hard boundary.
3. Why is contraction a separate authorized change?
It removes compatibility and recovery options and is often destructive. Separating it forces proof that consumers and state migrated, verification windows passed, residual risk is accepted, and each removal has an explicit recovery alternative.
Prove the mechanism
Extend the planner with immutable transition sequence numbers and separate reconciliation evidence for online writes, offline backfill, and shadow comparisons. Add duplicate-controller, stale-evidence, partial-write, rollback-after-target-write, and unknown-consumer cases without adding live mutation.
Add a production constraint
Design a cross-region migration that changes model provider, prompt contract, embedding model, vector index, policy engine, and telemetry schema. Specify expansion order, privacy-safe replay, side-effect isolation, data and index recovery, regional canaries, cost and quality gates, controller failover, rollback after state mutation, consumer proof, contraction, and a disaster-recovery exercise during the overlap window.
Artifact: Reversible AI stack migration plan
courses/ai-engineering/reference-impl/architecture_migration/migration_plan.py
Download reference implementationPrimary references and next links
References
- 1. Parallel Change
Martin Fowler. Primary author explanation of expand, migrate, and contract as a compatibility-safe approach for interfaces, databases, deployments, and remote APIs.
- 2. Deployments
Kubernetes. Official controller documentation for rolling updates, rollout status, revision history, and explicit rollback behavior.
- 3. Cloud Design Patterns
AWS Prescriptive Guidance. Official guidance describing incremental strangler-fig replacement as a way to reduce transformation risk compared with a big-bang migration.
Continue through the graph
- The Model-Serving Control Plane →
Use immutable revisions, bounded traffic stages, desired state, health, capacity, and rollback as migration primitives.
- Online Evaluation Without Shipping Blind →
Design representative canary evidence, guardrails, causal comparisons, and rollback triggers.
Glossary: parallel change · expand and contract · dual write · backfill · shadow traffic · reconciliation · canary · idempotency · compatibility window · contraction