AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals

Migrating AI Prototypes to Reliable Production Without Disrupting Users

Question 21 of 47 · Updated

On this page

Treat the live prototype as an existing product with real obligations, not as disposable experimental code. Establish an explicit continuity contract, inventory its state and dependencies, build the smallest production-ready target that preserves that contract, introduce compatible interfaces and data changes, migrate through bounded rehearsals and evidence-gated user cohorts, and retain a verified recovery path until every relevant consumer and state transition has been reconciled. Do not combine a rewrite, a new model, a new datastore and a new permission system into one unobservable cutover if they can be safely separated.

Original curriculum question: How would you migrate an AI prototype into a reliable production architecture without disrupting existing users?

Module 01 — Architecture fundamentals | ASD-008. This capstone applies the first seven architecture lessons to an already-used product: choose the mechanisms (ASD-001), specify measurable outcomes (ASD-002), size resources (ASD-003), define execution contracts (ASD-004), choose sourcing (ASD-005), enforce authority independently of predictions (ASD-006), and choose a sustainable deployment topology (ASD-007). Existing MLOps lessons on shadow deployments, inference API evolution, canarying and rollback address model-serving releases; the ML quality lessons address slice-specific rollbacks, and the agent curricula address workflow or memory migration. They are prerequisites here. Our distinctive objective is the *whole-product transition* from an experiment that already has users to an owned operational system: preserving identity, user-visible state, outstanding commitments, historical artifacts, client support, authorization and recovery across coordinated application, data, runtime and operational changes. ASD-007 covers the justification and mechanics of extracting a service; extraction is optional in this lesson. ASD-089 concerns coexistence of a legacy rules engine and AI-assisted decision service, ASD-029 concerns provider replacement, and ASD-200 concerns consolidation of multiple mature AI products. None is assumed necessary for this first productionization journey.

All organizations, resource rates, monetary examples, traffic volumes, thresholds and recovery objectives are fictional teaching assumptions, not production measurements or universal requirements. The code example was executed locally, but no real infrastructure migration was attempted.

1. Identify what users rely on today#

A prototype can accumulate obligations before it has a formal production designation. People may use saved conversations, share artifact links, depend on document revisions, expect credits to be correct or submit background jobs that outlive their browser. A team that rewrites the prototype without mapping those obligations may preserve the screen while losing the product.

Imagine a small document-assistance application. It initially ran in one process, used local disk for uploaded files, stored conversations in a lightweight database, relied on a hosted language model, and generated long reports inside web requests. Several departments now use it daily. The goal is to introduce durable jobs, governed storage, authorization, versioned model configuration, monitoring and recoverable operations while preserving their existing useful workflows.

Interview users, support, domain/policy owners, engineering, security and operations. Inventory the following, using actual request traces, code and storage inspection, approved stakeholder evidence and support records:

Inventory areaQuestions to answer
ClientsWhich web, mobile, partner and scheduled clients are still supported? Which response shapes or links do they depend on?
IdentityHow are accounts, organizations, memberships, roles and resource ownership represented?
Durable recordsWhich documents, conversations, artifacts, settings, credits and receipts are authoritative?
Outstanding workWhich uploads, jobs, notifications and external actions have been accepted but not completed?
AI configurationWhich model, prompt, tool, feature, embedding/index and evaluator versions produced previous results?
DependenciesWhich vendors, credentials, local files, databases, network services, rate limits and undocumented configuration are involved?
Operational stateWhere are backups, logs, queues, service owners, deployment history and incident procedures?
Data obligationsWhich retention, deletion, consent, residency, licensing and access commitments apply?

Classify unknowns as risks to investigate rather than assume they are absent. A folder named temporary may hold the only copy of an accepted upload. A session token may embed identity semantics the new service interprets differently. A low-volume partner integration may not show up in one day's traffic. Audit jobs on their actual logical schedule, not only the public API.

The continuity target is not preserving every historical bug. It means preserving the supported, authorized business contract and explicitly communicating legitimate changes. If the prototype exposes restricted data or has a severe security problem, immediately contain that behavior and provide safe support or alternative access; continuity never requires keeping an unsafe route alive.

2. Make continuity measurable before changing architecture#

Define what disruption means for each supported task. A request receiving HTTP 200 is not necessarily a successful migration if its saved conversation disappears or its answer violates current access policy. Likewise, a brief planned write pause may be acceptable if stakeholders agree and queued work is durably accepted; it is not literal zero downtime.

Example continuity requirements:

ConcernIllustrative acceptance contract
IdentityExisting authorized users retain canonical account and tenant identity; no unauthorized identity merges
Document stateEvery eligible document revision and deletion is reconciled at the cutover boundary
User historyExisting conversation and artifact references remain valid or have documented, authorized replacement behavior
Accepted jobsEvery previously accepted logical job reaches an accounted-for state; no silent loss or duplicate business effect
Online experienceSupported task-level quality and latency satisfy approved stage-specific gates
SafetyMandatory authorization and data-use controls pass; severe violations trigger containment
RecoveryTested compatible routing/state recovery and accountable handling of ambiguous effects
CommunicationUsers know about legitimate maintenance windows, new limits and changed capabilities

Assign each requirement an owner, baseline evidence, metric contract, test suite and stop rule. The baseline should measure real existing behavior, including failed tasks, slow requests, manual support effort and important workload slices. A prototype may have poor telemetry, so first introduce bounded, privacy-safe observation and reconstruct what is legitimately knowable. Do not invent historical baseline values.

Preserve the old interface only where it is appropriate and permitted. If legacy authorization is unsafe, use an independently enforced compatibility layer or disable the unsafe capability. Make feature restrictions visible. This is safer than implementing a fallback that can restore the original vulnerability.

3. Assess technical debt by impact and migration dependency#

Do not equate technical debt with unattractive code. The priority is debt that blocks a trustworthy release or endangers accepted user commitments.

DebtExamplePriority and treatment
Integrity and securityTenant ID taken from untrusted request, credentials embedded in codeContain immediately; define trusted authority and rotate credentials
Durable stateUploaded file exists only on a disposable serverPreserve, inventory, back up and migrate before replacing server
ReproducibilityMutable model alias, unrecorded prompt and index versionsPin compatible release bundles; record limitations of past outputs
Operational fragilityNo readiness checks, unbounded retry loopsAdd deadlines, admission, recovery and meaningful health checks
Product contractLong report can be lost after client disconnectIntroduce durable job identity and explicit result delivery
MaintainabilityEntangled modules and duplicated validationRefactor behind tested ports when useful
Cosmetic or speculative optimizationRewriting working UI solely to change frameworkDefer unless it is needed to satisfy a measured requirement

A risk register should record the affected user task, probability/uncertainty of failure, severity, current control, proposed remediation, dependency and responsible owner. High-impact unknown state is often more urgent than a known inefficient implementation.

Before copying or replaying old data, confirm the permitted purpose, retention and access boundaries. A production migration is not permission to collect all historical prompts or send restricted documents to new systems. If rights or provenance cannot be established, quarantine the relevant subset under approved handling and resolve the obligation with the domain owner.

4. Target architecture: preserve product continuity, change implementation deliberately#

The following target is one possible design, not a mandated microservices architecture. It keeps a modular business core, external durable storage, a separate report worker and an independently governed inference interface. Small local models may remain local if validated.

Loading diagram…

The core owns current permissions and business state, not the model. The index is derived from canonical authorized documents, with explicit version and freshness. Background work is accepted durably before acknowledgment. Artifacts have immutable identities or versioned references, and access is rechecked at delivery. Each runtime has meaningful readiness, resource limits and an accountable owner.

Define a production release manifest that identifies application code and dependencies, model and calibration/prompt configuration, feature/embedding/index compatibility, tool capabilities, API/event contracts, data schema and migration stage, control policies and evaluator versions. Use immutable digests where appropriate. Mutable aliases may select an approved release, but the actual executing artifacts must be observable.

Separate concerns to reduce change risk. If replacing local files with a durable store is independent of changing the model, migrate storage while retaining behavior first. If a new job lifecycle is essential, introduce that contract behind a compatible endpoint before major user interface changes. A stable facade can hide implementation transitions but must not conceal changed semantic behavior from clients.

5. Plan a migration graph rather than a big-bang rewrite#

A useful sequence is stabilize, expand, populate, reconcile, rehearse, expose, transfer authority, observe and retire. These steps may overlap or be repeated by capability. The dependency graph determines which transitions are safe, not the calendar alone.

Loading diagram…

The diagram is conceptual. Some applications transfer read traffic before write authority; others cannot serve the candidate until both are coherent. Keep a per-capability compatibility and ownership matrix. A read path may use a derived replica under an approved freshness contract, but a hard invariant must be checked against the authoritative owner.

For each change, identify prerequisites, supported combinations, rollback point, resource demand, owners, evidence and stop conditions. Freeze unrelated risky changes during critical transitions when appropriate. A candidate that changes multiple dimensions at once makes root cause and rollback harder; if dependencies force a joint change, rehearse the complete bundle.

6. Isolate fragile dependencies before moving real traffic#

Prototype dependencies often mix mutable local files, global variables, unrestricted network calls and runtime secrets. Put controlled interfaces around externally observable capabilities: document storage, inference, retrieval, jobs, identity and billing. These may be modules or services; process extraction is not required unless a real boundary warrants it.

Preserve semantic contracts, not just method names. A replacement storage adapter must preserve canonical IDs, authorization, versioning and error distinctions. A new model adapter must preserve supported response meaning or negotiate a new contract. An asynchronous report adapter must represent accepted versus completed work honestly.

Remove hardcoded credentials and rotate exposed secrets. Apply least-privilege service identities, dependency inventory and pinned reviewed artifacts, resource budgets and bounded retries. Separate production credentials from development and shadow credentials. Avoid introducing a large new platform if the existing team cannot operate it.

Set explicit timeouts and bulkheads for each dependency. For example, isolate expensive report workers from short interactive questions, and keep migration backfill from saturating primary storage. A model outage may justify returning verified document metadata without a generated answer if the product allows it, not fabricated content. A missing authorization service requires fail-closed behavior for affected protected operations.

Establish a known healthy stable route, even if that means hardening the existing prototype first. Recovery cannot depend on returning to an unpatched system or an unprovisioned old instance.

7. Data migration: establish authoritative state and a consistent cut#

Data migration is often the most consequential part of productionization. Copying rows while users continue to write them can produce a target that never corresponds to a coherent source state. A count of copied documents cannot demonstrate correct content, ownership, version or deletion state.

Use a source-specific mechanism to establish a consistent snapshot with a corresponding change position. This could be a database-native replication snapshot with a compatible log position, an exported transactionally consistent snapshot with an outbox boundary, or a bounded write pause when that is the approved practical approach. The exact guarantees depend on the database, replication protocol and configuration.

A robust conceptual sequence:

  1. Inventory canonical records, keys, data classes, schema mappings, deletion state and dependent references. Back up and test restore before risky changes.
  2. Start capture of changes with a boundary tied to a consistent source snapshot. Ensure the change-log retention covers the entire backfill plus recovery.
  3. Copy the snapshot into staging in bounded, restartable partitions. Record expected key ranges and checksums.
  4. Apply subsequent changes idempotently, ordered as required by source semantics. Preserve tenant identity, monotonic entity revisions and tombstones.
  5. Reconcile at a coherent position. Validate key sets, canonical payload equivalence after approved transformations, ownership, referential integrity, deletion state and outstanding jobs/receipts.
  6. If required, establish a short write fence or another tested atomic ownership-handoff mechanism, drain in-flight source writes, capture the final position and verify that target state has applied all required changes through that position.
  7. Switch authoritative write ownership exactly once under a fenced routing policy, then resume permitted mutations. Reconcile independently after the handoff.
Loading diagram…

The diagram does not imply that snapshot and log capture are automatically consistent, nor that one generic SQL command works for all systems. Establish the source-specific relationship before copying. For partitioned event logs, a checkpoint can require one position per partition and a coherent transaction/snapshot boundary, not one maximum offset.

If events can arrive out of order, version-aware updates prevent an older snapshot row from overwriting a newer revision. A deletion tombstone prevents a delayed old event from resurrecting a removed record. Keep tombstones for the authorized replay horizon or use another durable deletion/version mechanism; do not retain deleted sensitive content just to facilitate replay. If an equal revision arrives with conflicting payload, flag an integrity problem rather than choose whichever arrived last.

In a source-to-target migration, do not allow two unrelated writers to modify the same authoritative entity indefinitely. Bidirectional replication is not a substitute for defining conflict and invariant ownership. If rollback requires returning write authority to the old store after the target accepted writes, a coherent reverse migration or compatible shared authoritative store must already exist. Otherwise a roll-forward repair or controlled restricted service mode may be the only safe option.

8. Worked migration capacity and cutover example#

Consider 2.4 million document metadata records and tombstones. Suppose the backfill can sustain 400 records/s after limiting its effect on primary serving. Pure copying takes 2,400,000/400 = 6,000 seconds or 100 minutes. Suppose changes arrive at an average of 25 events/s during that period and are buffered for subsequent replay. The backlog at the end of copying is approximately 150,000 events.

If the replay worker processes 125 events/s while new changes continue at 25/s, ideal net drain is 100/s. Catch-up takes roughly 1,500 seconds or 25 minutes. This illustrative fluid model assumes constant rates, sufficient log retention, no retry overhead and a replay implementation whose per-event work matches the benchmark. Parallel snapshot plus replay may reduce the observed backlog, but contention can lower both rates.

For a final write-fence window, suppose 600 events remain after draining accepted writes, with no more source writes permitted. At a validated 125 events/s the arithmetic replay time is 4.8 seconds. Add reconciliation, ownership transfer, routing propagation and verification. An approved 30-second write-pause objective is plausible only if the whole rehearsed sequence fits; the 4.8-second arithmetic is not a guarantee. If an existing client cannot tolerate even a short write pause, design a tested alternative that preserves a single authoritative commit boundary or durably accepts commands with clear completion semantics. Do not silently drop submissions during the fence.

Use source and target resource budgets, queue age, log-retention horizon and actual progress telemetry. Stop or throttle if backfill harms the stable product. A source snapshot copied successfully is not a readiness certificate if change capture lost events.

For derived embeddings, it may be simpler to regenerate the target index from approved current source records using the intended embedding release. Record the mapping between source revision and index generation. Validate permission filters, retrieval quality, completeness and stale/deleted records separately from canonical metadata. Index similarity and row counts do not establish authorization or semantic equivalence.

9. Backward compatibility across applications, jobs and artifacts#

Use expand–migrate–contract where practical. First add compatible structures, such as optional fields or new tables, without removing supported old ones. Populate and validate the new representation. Update readers and writers in a controlled sequence. Remove the old representation only after all supported consumers, in-flight work and recovery procedures no longer depend on it.

For a document assistant:

Existing surfaceCompatibility plan
Old document linkResolve stable document ID through an authorized mapping; never treat a redirect as permission
Conversation recordsPreserve tenant, order, message IDs and approved retention; adapt older schemas
Report requestPreserve the documented response or introduce explicit negotiated job semantics
Accepted background workKeep logical job ID, pinned input/contract, owner and current status
Model outputPreserve score/label meaning and approved artifact lineage or introduce a new version
Saved reportPreserve immutable version/reference, access checks and accurate provenance
Credits or billingReconcile stable logical charge and receipt IDs; no duplicate charge for a retry

A new optional field can still break strict clients. Test actual supported client versions, scheduled consumers, replay readers and fallback routes. Avoid repurposing fields, silently coercing missing values to zero, or changing meaning behind an unchanged schema. Old artifacts may lack complete provenance because the prototype did not record it; mark unknown metadata honestly rather than invent model digests.

For pending report jobs, define whether they finish in the old runtime, resume from a compatible checkpoint, or are explicitly migrated. Keep a durable work ledger. Do not dispatch the same accepted external action to both implementations. A job that already completed should not be rerun simply because a new worker cannot find its output. If some prototype work was never recorded durably, quantify the uncertainty and provide a recovery/support process rather than claim that nothing was lost.

10. Feature flags and staged exposure#

Use release flags to control a specific capability or route independently of deploying code. Distinguish release flags, experiment assignment and operational kill switches from authorization rules. An enabled flag does not grant the user permission. Server-side controls must enforce the real resource boundary regardless of flag state.

For a stable canary assignment, choose a key matching the consistency requirement. If users share work inside an account, account-level or tenant-level assignment may avoid a confusing mixture of old and new semantics. If each task is independent, logical task-level assignment may suffice. Hash a canonical authorized identity with a versioned rollout salt into a fixed bucket range. Increasing the threshold preserves membership of the earlier cohort under the same key and salt. Actual request traffic share may differ substantially from the fraction of identities, particularly for high-volume tenants. Measure real exposure.

Keep flags typed, centrally governed, auditable, time-bounded where appropriate and fail-safe under configuration failures. Define cache freshness and propagation time for emergency switches. A stale worker must not commit effects after ownership or authorization has been revoked. Persist assignment and release identity on durable jobs when their behavior must remain consistent.

Feature-flag cleanup is part of migration completion. An obsolete branch can accidentally restore insecure behavior or retain old dependencies. Remove it only after the recovery window and approved retirement criteria, not immediately after reaching a nominal 100% traffic weight.

11. Offline replay, shadow, blue-green and canary serve different purposes#

TechniqueCandidate affects users?Use in whole-product migration
Offline replayNoValidate contracts, source transformations, quality and historical edge cases
Shadow executionNo authoritative response or effectRehearse candidate against eligible realistic inputs and detect dependency/semantic differences
Blue-green infrastructureOnly after controlled routingKeep compatible stable and candidate deployments available for a reversible route change
CanaryYes, within approved eligible cohortObserve real user outcomes and operational health
Progressive rolloutYes, increasing exposureExpand only after stage-specific evidence and ownership checks

The existing model rollout and shadow lessons explain their infrastructure and statistical mechanics in depth. For migration, the critical issue is whether both application generations can coexist against the *current authoritative state*. Shadow output must not create jobs, charge credits, send notifications, mutate shared memory or pollute authoritative feedback. Prevent these effects using separate identities, controlled egress and sinks, not just by discarding responses. Copy only approved input data and bound shadow resource use to protect the stable path.

A shadow result can expose schema incompatibility or changed retrieval evidence. It cannot demonstrate user response to an answer that was never shown, nor prove every migrated record is correct. Use data reconciliation, integration tests and separate controlled exposure.

A blue-green routing switch can be fast if both fleets are healthy, compatible and provisioned. It is not an instant data rollback after irreversible schema changes or new target writes. Canary stages should therefore explicitly record which owner is allowed to commit and which client/job versions are supported at each stage.

Loading diagram…

This coexistence pattern assumes the candidate can safely use the shared authoritative contract during the observation stage. If not, use an adapter, a read-only rehearsal, or a separate explicit write handoff. A shared database with unrestricted dual writers is not what is intended.

12. Worked exposure plan and acceptance gates#

Suppose a prototype serves 50,000 eligible tasks/day. An initial candidate exposure of 2% of requests would yield approximately 1,000 candidate requests/day if traffic assignment realized that fraction. An account-level bucket of 2% need not produce exactly 1,000 requests. Track observed assignment, accepted tasks, successful tasks, missing labels, and each critical cohort.

An illustrative progression might be no exposure, internal permitted cohort, 2%, 10%, 25%, 50% and full eligible traffic. Advance only when every blocking gate for that stage is met, not merely because a scheduled hour has elapsed.

GateExample criterion, defined before exposure
ContractSupported clients and job types pass compatibility fixtures
DataRequired key/revision/ownership/deletion reconciliation complete at intended boundary
SecurityNo known mandatory violation; independent control review complete
QualityPrespecified representative audit meets task success and critical-slice criteria
ReliabilityValid completion and error objectives met over approved sample/time coverage
LatencyEnd-to-end deadline and tail latency meet the task contract
CapacityStable path, target, dependencies and recovery fleet retain tested headroom
Jobs and effectsNo unexplained accepted work or duplicate business effects
RecoveryRestore/routing and state-reconciliation drills pass; accountable owner available

For a simple illustrative count gate, suppose a candidate receives 1,000 eligible requests with 12 technical failures, an observed failure rate of 1.2%. If the gate requires no more than 0.5% for that test window, it fails regardless of answer fluency. A result of zero failures in only 20 requests would not justify a 0.5% population guarantee. Use the sampling and confidence requirements established in ASD-002. Stop immediately for severe mandatory incidents even if the planned sample size has not been reached. Missing evidence means HOLD, not PASS.

Do not conflate a migration canary with a randomized efficacy trial. Operationally selected early customers may differ from other users. To estimate causal business benefit, design an appropriate controlled experiment with assignment, outcome, dependence and stop rules. For migration readiness, evaluate both continuity and user-facing outcomes, including users who abandon or require support.

A move from 10% to 25% is a new exposure decision. Verify that the candidate actually has the required warm capacity and that stable recovery capacity is still available. A steady 50% rollout does not imply each downstream dependency sees half its old load; shadow, dual reads, retries, cache warming and backfill can increase demand.

13. Tested example: version-safe replay and guarded exposure#

The standard-library Python example below demonstrates two small pieces of the migration contract: applying monotonic document revisions into a staging representation, then checking a frozen snapshot and verified change position before readiness; and selecting a stable exposure cohort with a kill switch. It uses a single in-memory SQLite connection. The source snapshot and applied position are supplied by the caller; it does not implement change-data capture, transactionally consistent snapshot creation, a verified contiguous watermark, authorization or actual traffic routing. The two functions are deliberately independent; a production release controller must enforce readiness and other gates before enabling candidate exposure.

PYTHON
from dataclasses import dataclass from hashlib import sha256, md5 import sqlite3 @dataclass(frozen=True) class Revision: tenant: str doc: str version: int body: str | None # None is a deletion tombstone def apply(db, event): if type(event.version) is not int or event.version < 1: raise ValueError('invalid version') with db: row = db.execute('SELECT version, body FROM target WHERE tenant=? AND doc=?', (event.tenant, event.doc)).fetchone() if row and event.version == row[0] and event.body != row[1]: raise ValueError('conflicting revision') if row and event.version <= row[0]: return False db.execute('INSERT INTO target VALUES (?,?,?,?) ' 'ON CONFLICT(tenant,doc) DO UPDATE SET version=excluded.version, ' 'body=excluded.body', (event.tenant, event.doc, event.version, event.body)) return True def ready(db, source, source_position, applied_position): # Caller supplies a frozen source snapshot and a verified contiguous watermark. if applied_position != source_position: return False expected = sorted((e.tenant, e.doc, e.version, e.body) for e in source) actual = db.execute('SELECT tenant,doc,version,body FROM target ' 'ORDER BY tenant,doc').fetchall() return expected == actual def route(account, basis_points, enabled): if type(basis_points) is not int or not 0 <= basis_points <= 10000: raise ValueError('invalid exposure') if not enabled: return 'stable' digest = sha256(('asd008-rollout:' + account).encode()).digest() bucket = int.from_bytes(digest[:8], 'big') % 10000 return 'candidate' if bucket < basis_points else 'stable' def main(): db = sqlite3.connect(':memory:') db.execute('CREATE TABLE target(tenant TEXT, doc TEXT, version INTEGER, ' 'body TEXT, PRIMARY KEY(tenant,doc))') old = Revision('a', 'x', 1, 'old') new = Revision('a', 'x', 2, 'new') deleted = Revision('a', 'x', 3, None) other = Revision('b', 'x', 1, 'private') assert apply(db, new) assert not apply(db, old) assert not apply(db, new) try: apply(db, Revision('a', 'x', 2, 'conflict')) except ValueError: pass else: raise AssertionError('conflict accepted') assert apply(db, deleted) assert not apply(db, new) assert apply(db, other) assert ready(db, [deleted, other], 12, 12) assert not ready(db, [deleted, other], 12, 11) assert not ready(db, [new, other], 12, 12) assert not ready(db, [deleted], 12, 12) assert route('account1', 0, True) == 'stable' assert route('account1', 10000, True) == 'candidate' assert route('account1', 10000, False) == 'stable' assert all(route(str(i), 1000, True) != 'candidate' or route(str(i), 5000, True) == 'candidate' for i in range(1000)) db.close() print('15 checks passed') if __name__ == '__main__': main()

Observed execution on Python 3.13.5:

15 checks passed

Fourteen direct assertions and one exception check test acceptance of a newer revision, rejection of an older or repeated revision, conflict detection for equal versions, tombstone handling, tenant-scoped key identity, complete reconciliation, refusal when positions or records differ, zero/full exposure, disabling the route and nesting the 10% cohort within the 50% cohort across 1,000 illustrative identities. The hashlib md5 import is unused; the routing helper uses SHA-256.

The example stores document identity and body (None represents a tombstone) in the target. It assumes trusted, normalized event fields, valid tenant/document identifiers and a complete source list with one row per key. The identical numeric version with a different payload raises an error. If a newer event has already replaced an older one, the code ignores older revisions; it does not retain a full event history or detect every historical conflicting payload. A real pipeline needs producer identity, schema validation, appropriately durable storage, transaction-aware offsets, replay retention, and a consistent source/target read boundary. For parallel writers, the preliminary SELECT and subsequent write are not a sufficient concurrency protocol; use an atomic conditional update or appropriate isolation with conflict checks. The target primary key scopes the data; it does not authenticate a tenant or enforce access. The toy is not a production-ready data or security migration.

The full reconciliation reads all rows and sorts the source, with O(N log N) sort work and O(N) memory for N records; the target query uses database-dependent ordering and storage access. At scale use partitioned, canonical key/version/payload digests with consistent snapshots, exact mismatch drill-down and independent validation of permissions and relationships. Do not assume matching aggregate hashes establish all invariants; canonicalization, completeness and trusted scope are necessary. Reconcile tombstones or deletion/version ledgers without retaining prohibited contents.

The routing helper uses deterministic buckets, not a security mechanism or statistically guaranteed equal request allocation. The enabled switch returns the stable route in this fixture, but a real emergency fallback is permitted only if the stable release remains secure, compatible and has adequate capacity. If not, use an approved restricted mode or hold affected work. No real network, concurrent database, production cutover, checkpoint, authorization or rollback was tested.

14. Observability: measure continuity rather than infrastructure activity#

Add telemetry before migration so baseline and candidate are comparable. Instrument the logical task across API, retrieval, model, worker, data store and artifact delivery. Include route assignment, actual application and model release, policy/contract version, source revision, job ID, retry attempt and outcome category using appropriately governed identifiers. Distinguish observed candidate traffic from configured flag percentage.

SignalMigration question
Valid completed tasks / offered tasksAre supported workflows still successful?
p50/p95/p99 and deadline missesDid the change hurt interactive experience?
Job queue age and terminal accountingAre accepted jobs stranded or duplicated?
Source position, applied progress and mismatch countsIs the target data actually coherent?
Permission and deletion validationHas the migration changed data exposure?
Artifact resolution and legacy contract errorsAre old clients and links still working?
Candidate versus stable quality by scopeIs the new path useful and safe?
Warm capacity, dependency pressure and retry amplificationIs rollout or backfill degrading the stable product?
Recovery routing, state and receipt reconciliationDid recovery restore the actual product contract?

Monitor user feedback and support requests with appropriate privacy controls. Delayed outcomes require label maturity tracking; a recent canary may look perfect simply because failures have not been adjudicated. Observe important low-volume clients and scheduled jobs rather than rely entirely on aggregate daily request metrics.

Use structured traces and runbooks, but avoid dumping raw documents, credentials or prompts into logs. Store approved evidence references and minimize sensitive telemetry. An incident dashboard must have clear action ownership and an independent view of the stable path.

15. Security hardening and governance during coexistence#

A live migration temporarily expands the attack surface: two deployments, replication credentials, backfill workers, compatibility routes, shadow sinks, exported backups and administrative flags. Review trust boundaries for the *transition state*, not just the final topology.

Establish workload identity, resource-level authorization, scoped service credentials, secure secret rotation, artifact integrity, protected backups, controlled egress, dependency patching and approved data retention/deletion. Check access on old and new routes, indexes, caches, artifact links and exports. A new index must not expose a document removed from a user's membership during catch-up. Replay must not restore revoked access or deleted content. A copied historical grant may establish past authorization but cannot grant current access.

Ensure model and tool execution never directly changes protected state without the independently authorized enforcement boundary (ASD-006). Shadow work cannot reach production mutation endpoints. Validate migration administrators' permissions, protect flag changes and record approvals. Restrict debug endpoints and remove development tokens from deployed artifacts. Verify fail-closed behavior when trusted authority is unavailable.

If a privacy or integrity incident occurs, halt the affected exposure, preserve authorized evidence, revoke unsafe capabilities and reconcile actual affected records. Do not automatically restore the insecure prototype. Follow the applicable incident and notification process with qualified owners. Risk frameworks and a passing test suite do not establish legal compliance.

16. Rollback is a set of recovery actions, not a single button#

Separate the mechanisms:

Recovery dimensionPossible actionWhat it does not automatically repair
Feature/trafficDisable exposure and route to compatible stable fleetNew target writes, already delivered results
Application/modelRestore approved prior compatible bundleIncompatible schema/index migration
Read dataSwitch to verified equivalent source/projectionAny new authoritative mutations
Write ownershipFenced reverse transfer with all new writes reconciled, if supportedExternal irreversible actions
Job executionStop admission, drain, safely resume/reconcile jobsDuplicate side effects already committed
User outcomesNotify, correct, revoke or compensate where allowedDisclosures or irreversible effects already made

Before target write ownership is transferred, aborting may be as simple as keeping the source authoritative and discarding or rebuilding staging. After the target commits new mutations, reverting routing to a source that lacks those mutations can lose data and duplicate effects. Either keep a tested reverse-compatible replication/ownership procedure, preserve a shared authoritative store across release generations, or plan an explicit forward repair. Never restore an old backup over current live data as an improvised rollback.

Loading diagram…

Use an accountable incident commander or release owner. Freeze risky changes, record candidate/stable identities and affected scope, and protect users before lengthy root-cause analysis. Verify actual traffic, task-level health, permissions, job state and reconciliation after recovery. A deployment tool saying rollback succeeded is only infrastructure evidence.

Example: a candidate report worker generates an artifact successfully but loses the acknowledgment after recording completion. A naive rollback may requeue the same job, charge twice or publish a conflicting artifact. Resolve the canonical job and charge receipts first. Only retry work that is safely retryable under the defined idempotency contract. Use explicit corrective revisions for invalid published artifacts, and authorized compensation for effects that support it.

17. Disaster recovery and business continuity#

Rollback restores a known compatible product release or ownership arrangement after a change. Disaster recovery addresses loss of infrastructure, state or dependencies. Define the recovery time objective (RTO: target time to restore the agreed service) and recovery point objective (RPO: tolerated data loss measured relative to the incident), per critical data and task class. These are objectives, not claims about actual recovery.

For the fictional workspace, assume business owners propose a 60-minute service RTO and a five-minute document-metadata RPO for a regional disaster. Accepted business commitments such as charge receipts may require a stricter recovery point or synchronous/durable external reconciliation; do not apply one global RPO without checking obligations. Backups every five minutes do not prove a five-minute RPO if they are inconsistent, not completed, unavailable or missing relevant logs.

A hypothetical tested recovery breakdown might allocate 5 minutes to detection and declaration, 20 to restore consistent data, 15 to restore/warm compatible runtimes and rebuild or mount essential derived state, and 10 to validate access, job receipts and critical workflows. The serial sum is 50 minutes, leaving 10 minutes of budget under the illustrative 60-minute objective. Actual work may overlap or take longer; a drill must observe elapsed recovery and data state.

Maintain backup and restore plans for canonical records, artifacts, keys and necessary configuration under governed access. Retain reproducible model/index artifacts or a tested regeneration procedure. Track source offsets, job ownership, release manifests and deletion state so restored copies cannot resurrect removed access or replay obsolete effects. Protect backups against correlated failure; test restoration in an isolated environment and evaluate regional data obligations. Define failback separately from initial failover.

During coexistence, verify both the current owner and the intended recovery owner can restore the appropriate state and enforce current policy. Recovery documentation should identify who declares a disaster, controls routing and write authority, validates integrity, communicates to affected users and authorizes normal service. A replica that has never been restored is an assumption, not demonstrated recovery capacity.

18. Operational ownership and migration economics#

Production readiness requires people and processes, not simply infrastructure. Assign a domain owner for permissions and business invariants, service owner for availability and capacity, model owner for quality and compatible releases, data owner for migration/reconciliation, security owner for control review, and accountable release/incident owner for exposure and recovery. Small teams can share roles, but responsibility must be explicit.

Before expansion, confirm on-call coverage, runbooks, escalation contacts, alert routing, deployment and restore permissions, support handling, known limitations, approved budgets, dependency agreements and ownership of outstanding jobs. Make a record of which risks have been accepted by qualified owners, and expire temporary exceptions.

Budget parallel infrastructure and hidden migration work. For an illustrative overlap of a $1,500/day stable fleet and $1,200/day candidate fleet for seven days, the total fleet cost during overlap is $18,900, with $8,400 incremental candidate fleet cost versus stable alone. Add shadow computation, backfill, additional storage, engineering, evaluation, on-call and support. If preserving the old fleet for a longer observation period protects a material risk, include that cost rather than prematurely delete recovery capacity.

A cost reduction from migration is not real until it reflects actual attributable expenses and successful task outcomes. A candidate may consume fewer GPUs while requiring substantially more human review or more expensive retrieval. Measure cost per useful task and task quality together. Conversely, keeping every temporary dual-run component forever creates ongoing cost and complexity; set exit criteria at the outset.

19. A second scenario: live predictive dashboard#

A small forecasting dashboard stores daily predictions in files and lets managers download reports. Some scheduled spreadsheets still read the original file schema. The target uses versioned forecast artifacts, durable scheduled jobs and monitored prediction delivery.

Preserve forecast target, horizon, unit, generation time and consumer schema while modernizing storage and scheduling. Capture the old dataset and approved history, identify consumers that run monthly, and generate candidate forecasts into isolated staging. Compare time-aligned forecasts with the appropriate actual outcomes and consumer contract; do not demand identical predictions if the approved model intentionally changes behavior.

Publish a complete versioned manifest at the next approved logical cutoff rather than partially overwrite old files. Keep old links or adapters for supported consumers, pin the forecast version used by each scheduled job, and check that no report was lost. If a candidate misses the publication deadline, use the prior *valid* forecast only if the freshness contract allows it and disclose its age. Do not relabel stale predictions as current.

After a new forecast is consumed, rollback may require issuing a corrected artifact revision and notifying downstream users rather than deleting the old record. The forecast has no authority to place orders; actual replenishment decisions remain in the approved business workflow. This differs from the document assistant's interactive request canary, illustrating that migration units may be logical runs, accounts, artifact versions or capabilities rather than HTTP traffic alone.

20. Readiness, cutover and retirement evidence#

Use separate sign-offs for initial candidate readiness, data ownership transition, traffic expansion and retirement. A compact migration record can include:

FieldEvidence
ScopeSupported users, tasks, data and explicit exclusions
Stable and target identitiesImmutable release/contract manifests and owners
BaselineObserved user, quality, service and data-integrity measures
State boundarySource snapshot/capture positions, target reconciliation and authority
CompatibilitySupported clients, old/new jobs, references and rollback fixtures
RolloutActual cohort assignment/exposure, gate results, sample coverage and approval
RecoveryCompatible rollback, recovery drill, receipts and unresolved incident handling
SecurityReviewed transition/final controls, retention and data-use restrictions
ExitOutstanding jobs complete/accounted for; consumers migrated; recovery window and retention fulfilled

Retirement is a distinct milestone. Verify supported clients and scheduled workloads no longer need the old route, old jobs are reconciled, backups and audit obligations are satisfied, rollback no longer depends on the removed resources, and obsolete credentials, flags and data copies are removed according to approved policy. Do not delete the only copy of historical user artifacts or silently change their links.

Maintain a post-migration observation period based on the actual feedback horizon. A monthly consumer and delayed model-quality labels may require longer evidence than a fast API health check. Record unresolved limitations explicitly rather than declare absolute zero disruption.

21. Interview-ready summary#

I would first inventory the live prototype's users, contracts, identity, authoritative data, accepted jobs and AI dependencies, then baseline user-visible outcomes and define what continuity means. I would contain urgent security and integrity issues, introduce durable state and compatible interfaces, and choose a target architecture that solves measured weaknesses without requiring unnecessary services or a simultaneous rewrite.

I would migrate data using a consistent snapshot and change capture, preserve canonical IDs and tombstones, reconcile through a verified boundary and maintain one write authority. I would test old and new clients, in-flight work and recovery compatibility. I would deploy the candidate without exposure, run authorized side-effect-isolated rehearsals and move stable user or task cohorts progressively only after quality, data, security, reliability and capacity gates pass.

If a regression occurs, I would halt expansion, choose a safe compatible recovery path, reconcile committed effects and verify the actual user task and state. I would define and drill disaster recovery separately, retain recovery capacity and artifacts until the agreed exit criteria, and assign operational ownership. The goal is not merely to launch a new architecture; it is to honor the product's existing commitments while making its reliability, security and change process demonstrable.

References and research transparency#

The authorized offline research exception was applied. The references below identify established architecture patterns, primary research, official standards and technical documentation. Current link availability and contents and the current Supabase changelog were not live-verified. Five meaningful Mermaid diagrams use standard triple-backtick fences and were reviewed structurally; no Mermaid parser or live frontend rendering was tested. The exact Python example was executed locally on Python 3.13.5 with 15 checks passing. No real migration, network rollout, security assessment, concurrent database test, production load test or disaster-recovery drill was performed. All numerical and operational scenarios are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython