AI System DesignData and Feature InfrastructureModule 02 — Data and feature infrastructure

Safely Backfilling Historical Data Without Corrupting Live AI State

Question 34 of 47 · Updated

On this page

Run a historical backfill as an isolated, versioned rebuild, never as an uncontrolled replay into live mutable state. Pin the historical source and transformation contract, process bounded event-time ranges into a new generation, retain live changes from a known boundary, catch the candidate up to a verified source frontier, and validate it before a fenced publication. Protect production capacity and suppress historical business side effects. Rollback must restore a compatible, sufficiently caught-up generation, not simply point at a stale copy.

How would you backfill years of historical data without corrupting live AI system state?

ASD-011 | Module 02 — Data and feature infrastructure | Learning order 21. The existing MLOps lesson on backfills in ML data and training pipelines covers explicit historical run dates, Airflow scheduling, immutable input snapshots, idempotent partition outputs, bounded concurrency and separate model promotion. This lesson goes beyond rerunning historical jobs: it designs coexistence between a multi-year rebuild and an actively mutating serving system, with source boundary proofs, catch-up and cutover protocols, stale-writer fencing, retention constraints, derived state and external-effect isolation. ASD-009 covers reusable source capture; ASD-010 reconciles predictions whose evidence snapshots differ; ASD-008 migrates an entire user-facing prototype. Here the central invariant is that replay of old data must not regress or corrupt current derived AI state. The scenarios and capacity numbers are illustrative, not measured production results. A narrow SQLite fixture was executed locally.

1. Define the purpose, affected state and non-negotiable invariants#

Suppose a retail AI platform discovers that its demand feature pipeline incorrectly handled order cancellations for the last three years. It serves live inventory and demand predictions continuously. The team must rebuild historical daily features, correct training data and potentially update serving state, while live orders and cancellations keep arriving.

Do not start by invoking a scheduler for three years of dates. Decide what the backfill is intended to produce and which artifacts may become current.

Backfill objectiveResultProduction implication
Fill missing historical partitionsNew versions of missing datesNormally no change to current serving state
Reproduce original computationHistorical as-known evidence under pinned old logicAudit only, not a corrected truth claim
Correct a transformationNew historical dataset generationReview impact on dependent features and models
Rebuild current state from historyCandidate serving generation caught up to live frontierExplicit validation and fenced cutover
Recompute historical predictionsNew retrospective analysis artifactsMust not duplicate real business actions
Retrain models using corrected dataNew candidate model and evaluationIndependent training and production release approval

The same replay can produce multiple outputs, but each has its own publication rules. Rebuilding training examples does not authorize replacing the current production model. Corrected hindsight features are not automatically as-known training data. Recomputing an old risk prediction must not reissue an old fraud hold or customer notification.

Define invariants before choosing tooling:

  • The live path remains within agreed latency, freshness, availability and correctness limits.
  • Historical computation cannot overwrite current state through ordinary historical writes.
  • Every expected input range is durably accounted for, including gaps, quarantines and corrections.
  • Publication uses a verified, compatible and sufficiently complete candidate generation.
  • A stale build, worker or approval cannot replace a newer active generation.
  • Deletions, access revocations and mandatory controls survive replay and rollback.
  • Historical effects are disabled by default at both credentials and effect-sink boundaries.
  • Original prediction and action receipts remain truthful and are never rewritten as if corrected inputs were available earlier.

Agree with source, serving, model, privacy, product and on-call owners on what constitutes complete coverage and what may be intentionally excluded. If the available historical data cannot support the desired correctness contract, narrow the objective or hold publication. More compute cannot recover missing facts.

2. Architecture: isolate the candidate from the active serving generation#

Loading diagram…

Separate the control plane from replay execution. The backfill control plane registers the run, expected partitions, immutable input manifest, transformation release, resource budget, owner, expected predecessor generation and intended output purposes. It manages task leases, checkpoints, validation evidence, approvals and cancellation. Workers operate in a candidate namespace, with credentials that cannot mutate active production materializations or trigger protected actions.

Use an immutable generation ID as part of storage keys, index namespaces, dataset paths, cache keys and result references. A candidate is invisible to production readers until the appropriate release pointer changes. This may be implemented with separate tables, partitions, immutable objects and manifests, index collections or dedicated stores, depending on isolation and reader capabilities. Two logical namespaces in the same overloaded database are not necessarily sufficient resource isolation.

Keep the source log or equivalent durable change capture independent of the backfill. The normal live processor continues to consume it. The candidate initially processes historical evidence and subsequently consumes the retained tail (or incrementally incorporates changes under an explicitly compatible merge contract). Use independent consumer positions. Never reset the live consumer group to a historical offset just to initiate a backfill.

The architecture does not imply globally atomic publication across independent databases, feature stores and vector indexes. A single manifest pointer can give readers a consistent bundle only if every dependent artifact is immutable, resolvable and compatible, and readers actually pin that manifest. Otherwise introduce a coordinated release protocol or separate independently valid publication scopes.

3. Choose a reproducible source cut and bound the historical window#

A backfill manifest identifies at least:

FieldMeaning
Run identity and purposeDistinguish missing-partition repair, historical replay and corrected rebuild
Target candidate generationPrevent accidental active writes
Logical event-time intervalExplicit half-open range [start,end)
Input snapshot and source incarnationImmutable source state, not mutable latest
Native partition position vectorExact source frontier covered by snapshot
Knowledge/availability policyOriginal as-known versus later corrected facts
Transform and feature definitionVersioned code, parameters, schema and reference data
Required dependency windowsLookback, carry-in state and impacted future windows
Partition coverage and quality rulesExpected ranges, permitted exclusions and validation requirements
Resource and effect policiesThrottle, priority, cost cap, no historical external effects
Release contextExpected predecessor, compatibility and approval scope

For a transactional source, establish the snapshot and live-log boundary through the supported consistent snapshot or CDC mechanism. A snapshot that begins at noon and a log cursor recorded at 14:00 do not prove all intervening changes were captured. Obtain a snapshot tied to an exact source frontier and retain changes after that frontier. For multiple independent sources, a compatible cut is a vector of positions and domain constraints, not a magic global timestamp. If the source cannot supply a consistent cut, explicitly stage, reconcile and repair the gap before treating a candidate as eligible.

Event-time partitions and capture positions answer different questions. A source event dated three years ago might be corrected today. The correction belongs to the current capture tail even though its business-time impact is historical. A historical job reading only the original date partitions will miss that correction unless the pinned source already includes it or the tail accounts for it.

Do not conflate event time, processing time, source availability and publication time. The historical feature cutoff must respect the intended analysis mode. A retrospectively corrected training dataset may differ from the original as-served information set. ASD-010 covers this distinction in detail; here preserve it as a backfill input and validation requirement.

Why partition windows need dependencies#

Consider daily demand aggregates with a 30-day rolling mean. Rebuilding March 1 through March 31 requires the correct input from at least the preceding 29 days, assuming the defined window includes the current day. A correction on March 1 can affect rolling features through March 30. If a feature includes cumulative state or an unbounded session history, an arbitrary month split may be invalid without a proven carry-in checkpoint. Separate output ownership (which partitions a task writes) from input overlap (which evidence it must read).

Partition by an appropriate event-time interval and stable entity/tenant shard; estimate skew before choosing fixed sizes. A single massive tenant or date may need subpartitions. For stateful sequential algorithms, partition parallelism must respect state dependencies. Independently recomputing overlapping windows and blindly adding the resulting aggregates double-counts evidence.

4. Coordinate the snapshot and live tail without a missing interval#

Loading diagram…

This conceptual sequence assumes the cutover controller actually establishes an enforceable handoff frontier. For a continuously changing source there is no durable "both are caught up" flag detached from a specific source position. Select one of the following strategies with a proven consistency contract.

Bounded publication barrier. Keep capturing source changes durably, but briefly fence materialization/pointer advancement at a known frontier. Bring both generations to the same covered cut, validate the exact immutable manifests and atomically switch the pointer. Resume candidate consumption from the next native position. Source transactions can continue into the buffer if the source and product tolerate the resulting bounded serving lag. If a pause would violate a freshness SLA, choose a different strategy.

Continuous versioned snapshots. Both paths independently publish immutable snapshots. Candidate release references a verified source frontier at least as eligible as the active release under the declared partial-order/coverage policy. A compare-and-swap publication transaction checks the active predecessor and the candidate's exact manifest; a concurrently advanced active frontier causes retry/revalidation. Readers pin one complete bundle. Avoid starvation if the active generation advances faster than the candidate can establish a comparable cut.

Per-partition handoff. Where decisions and state are independent by partition, migrate one partition at a time with scoped ownership and fencing. Do not allow cross-partition aggregates, joins or business invariants to observe an incompatible mixture; publish a consistent composite manifest where required.

The phrase "catch up" means all required changes through the frontier have been durably applied or otherwise accounted for under the approved policy, not just that the largest seen timestamp is recent. Native positions may be opaque, sparse and partition-specific. A stream event-time watermark is not proof of completeness of all source partitions or later corrections.

If source retention will expire before the candidate can replay, arrange additional authorized durable landing or a new coordinated snapshot. Do not assume a source can keep a log forever; a lagging logical replication consumer can impose real storage pressure upstream. Monitor time until retention loss from the beginning, not after the historical phase finishes.

5. Idempotency, checkpoints and ownership fencing#

A backfill run should be restartable at explicit durable boundaries. A task key might contain (run ID, generation, tenant, output partition, input manifest, transform version). For every attempt record the exact source range, output manifest, worker lease epoch, validation outcome and completion receipt. Attempts are not the logical partition identity.

When a worker reads a bounded batch and writes an output, make publication of the output and its checkpoint atomic within the supported local boundary. If data and metadata live in separate systems, write under an immutable attempt key, verify the artifact, then conditionally commit the manifest and checkpoint together. A crash after the artifact write but before manifest publication leaves an orphan, not a completed partition. A crash after commit but before acknowledgment should recover the existing receipt rather than append duplicate rows.

A unique input occurrence identity prevents duplicate application of the same record. A digest or full immutable payload comparison can detect an identity collision. However, two distinct legitimate source events may have equal content. Do not deduplicate all records on payload hash. For additive events such as purchases or refunds, record the actual event identity and apply the delta exactly once within the state transaction or an equivalent verified protocol. For full-state updates, compare authoritative entity revisions and retain deletions; skipping an older delta is not the same as ignoring an old full-state update.

Fence stale task owners with an authoritative generation/lease epoch check at the manifest or state sink. A scheduler's claim alone does not protect against a paused worker whose lease expired. A worker may finish computing after cancellation or after another attempt committed. Its artifact can remain as an orphan or authorized diagnostic, but it must not overwrite the committed partition manifest. Workers should not own the production release pointer.

A promotion epoch is distinct from an input cursor and a worker lease. It identifies the ordered history of active-generation changes. A rollback increments the epoch; it must never reuse the older epoch, or stale promotion attempts may become valid again.

6. Preserve late corrections and tombstones#

Replaying historical events must not resurrect deleted items or restore revoked access. Maintain the source mutation semantics throughout the reconstruction. For a full-state entity, an authoritative revision 9 tombstone defeats a late revision 4 upsert. For delta or event-sourced state, replay in the required order, handle retractions and corrections explicitly, and avoid combining incompatible base state and delta windows.

OccurrenceEntity revisionMeaningResult under full-state semantics
Historical snapshot4Product existsCandidate contains product
Captured live correction5Product values changedReplace revision 4
Live delete6Product deletedRetain deletion marker
Delayed old import3Older product representationIgnore for latest state
Conflicting equal revision6Different meaning at same revisionQuarantine/hold, investigate
Approved recreation7New valid state under source contractRestore only if permitted

Revision order is meaningful only within a defined entity/source incarnation. A new source reset can reuse revision numbers. Compare source epoch and authoritative lineage, not integers from different sources. Some delete obligations are stronger than normal entity revision handling: a historical object subject to erasure may not be re-read, re-embedded or retained even temporarily unless permitted. Apply current access and deletion policy before processing historical content and again at publication and retrieval.

For derived aggregates, maintain sufficient event identity and correction lineage to reverse or recompute affected contributions. Example: an order of $100 was included in a daily revenue feature, and later its cancellation is established. Depending on the domain contract, the correction may subtract the order contribution or rebuild the affected window from corrected facts. It must not subtract twice on retry. If the original snapshot already incorporates the cancellation, replaying it again could be incorrect. Establish a clear base-plus-tail boundary.

For feature windows, late corrections may affect downstream days beyond the original input date. For vector indexes, deletions require removing the affected document chunks and enforcing current access even during rebuilding. Rebuilds may create new embeddings while old-generation vectors remain physically present; only authorized active-generation retrieval is permitted. A candidate should not become current if deletion propagation is unverified.

7. Side-effect suppression: historical processing is not a new business event#

A replay that runs the original application handler may accidentally send customer emails, create reviews, charge accounts or trigger autonomous agent tools. Model predictions and feature transformations can be recomputed; historical decisions and their effects must not be repeated implicitly.

Design an explicit replay execution context with a separate allowed capability set. Use isolated queues and destinations, read-only source credentials and output credentials restricted to the candidate namespace. Exclude production effect clients from the historical worker, and independently deny historical execution credentials at the authoritative effect service. A request field such as replay=true is not a sufficient security control if a generated payload or bug can omit it.

An illustrative permission matrix:

OperationLive workflowBackfill worker
Read currently authorized historical sourceWithin contractWithin approved replay purpose
Write active feature generationScoped current writerDenied
Write candidate feature generationDenied unless explicitly assignedScoped build worker
Recompute historical model scoreApproved analysis onlyCandidate/audit output
Send real order notificationAuthorized live effect pathDenied
Submit release pointer updateSeparate release authorityDenied

If the purpose is to remedy a past error, create a separate remediation workflow with current authorization, exact affected entities, independent review, idempotent operation identity and explicit actual effect receipts. The backfill may generate a remediation proposal, but should not automatically execute it. External effects already committed cannot be rolled back by changing a dataset pointer.

8. Worked capacity plan: three years of data while live traffic continues#

Consider a fictional workload with 1,095 daily partitions, each averaging 5 million logical records. Total historical records are 5.475 billion. At 600 bytes per record (decimal units), source payload is approximately 3.285 TB before compression, indices, metadata, replicas and intermediate outputs. Output sizes and shuffle costs must be measured independently.

Assume one reserved backfill worker sustains 4,000 records/s on a representative workload, and 20 workers scale ideally to 80,000/s. The historical processing floor is:

5,475,000,000 / 80,000 = 68,437.5 seconds
                      = 19.01 hours

This is a lower bound under the stated throughput assumptions, not an operational ETA. Skew, object reads, aggregation windows, retry, source quotas, validation and staging can dominate.

Suppose live input is 2,000 events/s and the candidate defers tail application until the historical rebuild completes. The ideal tail backlog accumulated over 68,437.5 seconds is about 136.875 million events. If the catch-up path can sustain 12,000 events/s while 2,000/s continue arriving, net drain is 10,000/s. Ideal catch-up takes 13,687.5 seconds (3.80 hours). Historical build plus catch-up is thus about 22.81 hours before cutover validation and scheduling. At 600 bytes per tail event, the initially accumulated backlog alone is about 82.125 GB of payload, excluding replicas and log overhead.

For a retention commitment, include the historical build, catch-up, expected failures, source rate variation and recovery margin. A 12-hour retained tail is insufficient for the assumed sequential plan unless another durable landing retains the entire needed range. If catch-up throughput falls to the arrival rate, it will not converge. The backlog derivative is arrival rate minus service rate; capacity must exceed arrivals over the relevant sustained interval.

Now assume live inference uses the same database and GPU cluster as the backfill. Reserve live capacity first. Historical recomputation does not receive an entitlement to idle-looking capacity that is actually needed for live peaks, failover or burst absorption. Rate limit source scans, writes, network and compute separately. Set a backlog budget, cost limit and automatic pause on live SLO burn. If throughput drops to 40,000/s, historical compute floor becomes roughly 38.02 hours and tail retention assumptions must be recalculated; extending the run without re-evaluating retention can cause data loss.

For rolling-window features, partition work can require overlapping reads: processing a daily 30-day window naively scans up to 30 days of evidence per output day. Prefer correct incremental/windowed algorithms, checkpoints or preaggregations where they preserve semantics. Benchmark representative high-cardinality and skewed partitions instead of extrapolating from a single small date.

9. Resource isolation, adaptive throttling and interruption#

Set explicit resource ownership: separate live and backfill worker pools, queue priorities, source connections, storage throughput quotas and inference/embedding rate limits. Where hard isolation is unavailable, enforce admission and resource controls and verify contention under actual peak conditions. A scheduler concurrency limit is useful but does not bound per-task memory, database I/O or downstream fan-out.

Use backpressure from both source and production state. Track live latency, error budget burn, feature freshness, queue age, source replica lag, log retention, database locks, disk headroom and candidate progress. A governor can gradually increase replay rate within allowed headroom and reduce/pause it on sustained production degradation. Employ hysteresis and minimum dwell times to avoid rapid oscillation. Pause should stop new historical admissions and allow or cancel in-flight work under a documented safe checkpoint contract.

Prioritize critical live changes, including tombstones and access revocations. Avoid a recovery plan that starves deletes behind billions of old events. Preserve source ordering and consistency if using priority paths; arbitrary reordering of delta mutations can break correctness. Separate safety invalidation signals may block use promptly while canonical application catches up.

Keep costs attributable to the run. Establish a budget including historical reads, staging, duplicate storage during coexistence, tail retention, extra model/embedding compute, validation and rollback retention. For the fictional three-year example, 20 workers for 19.01 hours are about 380.2 worker-hours before catch-up. At a hypothetical $2/worker-hour, that historical worker component is about $760.4, not the total bill. Recompute estimates as actual throughput and retry rates become known. Do not turn an illustrative capacity model into a vendor price claim.

Cancellation and restart must not leave an apparently ready candidate. Retain completed immutable partition artifacts only if their manifest and source/transform contract still match the resumed run. A changed transformation version or input snapshot creates a new generation or formally approved reuse mapping. Clean abandoned candidates and orphan objects only after checking leases, active pointers, retention and references. Cleanup must not remove the recovery baseline.

10. Reconcile and validate before promotion#

Loading diagram…

A completed scheduler run does not equal a valid dataset. Require explicit release gates at the exact manifest:

GateEvidence and failure meaning
CoverageEvery expected partition/range and required dependency is accounted for
Source identityConsistent snapshot and tail, no gaps or unresolved occurrence collisions
Semantic correctnessUnits, definitions, key uniqueness, valid state transitions, corrections
CurrentnessRequired capture frontier reached and source corrections/deletions honored
Output integrityVerified immutable manifests, counts, hashes, constraints and referential integrity
Application compatibilityFeature contract, model preprocessing, index/query pairing and schema
QualityRepresentative paired evaluation, critical slices, intended correction differences
SecurityCurrent access, deletion and purpose requirements satisfied
OperationsProduction headroom, read/cutover behavior, recovery path and ownership
ApprovalExact manifest, validation release and expected predecessor signed off

Compare active and candidate at the same source cut wherever possible. Equal row counts are necessary in some datasets but insufficient: equal counts can hide swapped keys or incorrect values. Compare key sets, source positions, per-partition checksums, record-level diffs for critical entities, distribution and domain invariants. Use appropriate tolerance for numeric transforms, and compare source revisions and missingness separately. If a correction intentionally changes outputs, exact equality with the old generation is the wrong gate. Maintain an approved change specification and independent reference calculation. Investigate unexplained differences rather than simply count changed rows.

For training artifacts, validate point-in-time semantics, label windows, split leakage and data/model version lineage. For current inference features, validate actual online input parity under the expected model release. If an updated feature definition needs a new model, promote the compatible model/feature bundle or leave the live model on its old feature contract. A successful feature backfill is not automatic model release permission.

A validation result is bound to an immutable manifest and source frontier. If the candidate continues to mutate after validation, the original validation is not automatically evidence for the new state. Freeze the validated generation snapshot or define incremental validation for every additional tail segment and bind the resulting evidence to the final release cut. Recheck any material mutable policy and current resource eligibility at use.

11. Practical implementation: isolated state and fenced generation promotion#

The standard-library SQLite fixture below models a simplified single source partition with contiguous synthetic positions and full-state entity revisions. Live and candidate generations consume their own normalized event sequences. A None value represents a tombstone. The two generations may deliberately have different transformed values for the same source position because a backfill can correct a transform. In a real system, the source occurrence identity must be independently verified as the same, with each derived value linked to its transformation release.

The fixture isolates state by generation, commits event accounting, state and cursor together, refuses gaps and conflicting replay, checks an expected publication epoch and requires both cursors to reach the specified cut. An injected external validator result is represented by a Boolean, not by a real validation process. It demonstrates rollback to an older *implementation generation* only after that generation has caught up.

PYTHON
import sqlite3 def apply(db, generation, pos, key, revision, value): db.execute('BEGIN IMMEDIATE') try: cursor = db.execute('SELECT cursor FROM generations WHERE id=?', (generation,)).fetchone()[0] old = db.execute('SELECT entity,rev,value FROM events WHERE gen=? AND pos=?', (generation, pos)).fetchone() if old is not None: db.rollback() return 'DUPLICATE' if old == (key, revision, value) else 'CONFLICT' if pos != cursor + 1: db.rollback() return 'GAP' prior = db.execute('SELECT rev,value FROM state WHERE gen=? AND entity=?', (generation, key)).fetchone() if prior and prior[0] == revision and prior[1] != value: db.rollback() return 'CONFLICT' db.execute('INSERT INTO events VALUES(?,?,?,?,?)', (generation, pos, key, revision, value)) if prior is None or revision > prior[0]: db.execute('INSERT INTO state VALUES(?,?,?,?) ON CONFLICT(gen,entity) ' 'DO UPDATE SET rev=excluded.rev,value=excluded.value', (generation, key, revision, value)) db.execute('UPDATE generations SET cursor=? WHERE id=?', (pos, generation)) db.commit() return 'APPLIED' except BaseException: db.rollback() raise def promote(db, expected_epoch, candidate, expected_cursor, validated): db.execute('BEGIN IMMEDIATE') try: active, epoch = db.execute('SELECT gen,epoch FROM pointer').fetchone() cursors = dict(db.execute('SELECT id,cursor FROM generations')) if (not validated or epoch != expected_epoch or candidate == active or cursors.get(active) != expected_cursor or cursors.get(candidate) != expected_cursor): db.rollback() return False db.execute('UPDATE pointer SET gen=?,epoch=epoch+1', (candidate,)) db.commit() return True except BaseException: db.rollback() raise def active_view(db): return dict(db.execute('SELECT entity,value FROM state WHERE gen=(SELECT gen FROM pointer) ' 'AND value IS NOT NULL')) db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE generations(id TEXT PRIMARY KEY,cursor INTEGER); INSERT INTO generations VALUES('live',0),('build',0); CREATE TABLE pointer(gen TEXT,epoch INTEGER); INSERT INTO pointer VALUES('live',1); CREATE TABLE events(gen TEXT,pos INTEGER,entity TEXT,rev INTEGER,value INTEGER,PRIMARY KEY(gen,pos)); CREATE TABLE state(gen TEXT,entity TEXT,rev INTEGER,value INTEGER,PRIMARY KEY(gen,entity));''') assert apply(db,'live',1,'x',1,5) == 'APPLIED' assert apply(db,'build',1,'x',1,6) == 'APPLIED' assert active_view(db) == {'x':5} assert not promote(db,1,'build',1,False) assert apply(db,'live',2,'x',2,None) == 'APPLIED' assert not promote(db,1,'build',1,True) assert apply(db,'build',3,'x',1,6) == 'GAP' assert apply(db,'build',2,'x',2,None) == 'APPLIED' assert apply(db,'build',2,'x',2,None) == 'DUPLICATE' assert apply(db,'build',2,'x',2,9) == 'CONFLICT' assert apply(db,'build',3,'x',1,6) == 'APPLIED' assert apply(db,'live',3,'x',1,5) == 'APPLIED' assert active_view(db) == {} assert apply(db,'build',4,'y',1,8) == 'APPLIED' assert apply(db,'live',4,'y',1,7) == 'APPLIED' assert not promote(db,0,'build',4,True) assert promote(db,1,'build',4,True) assert active_view(db) == {'y':8} assert not promote(db,1,'live',4,True) assert apply(db,'build',5,'y',2,9) == 'APPLIED' assert not promote(db,2,'live',5,True) assert apply(db,'live',5,'y',2,9) == 'APPLIED' assert promote(db,2,'live',5,True) assert active_view(db) == {'y':9} assert db.execute('SELECT epoch FROM pointer').fetchone() == (3,) print('25 checks passed')

Actual local execution with Python 3.13.5:

25 checks passed

All 25 assertions passed. They cover distinct live and candidate values, candidate invisibility before publication, rejection without validation, a live cursor advancing ahead of the candidate, gap refusal, duplicate occurrence handling, conflicting same-position replay, tombstone preservation against older revisions, stale epoch rejection, successful promotion, rejection of a stale promotion attempt, refusal to roll back to a lagging generation, catch-up and successful rollback at a new epoch. The local code MD5 excluding its terminal newline is 547ad439f12ea2fd188ee39e1887ce50.

The example deliberately operates on trusted, normalized single-scope fixture inputs in one in-memory SQLite connection. It does not validate types, scope, authority, source incarnation, source membership, transformation semantics or authenticity of the supplied Boolean. Cursor equality alone is not proof of source coverage equivalence: production must bind an independently verified source manifest, validation digest and exact candidate version to the publication operation. The simple apply function accepts writes to either generation, including the active one, from its trusted test caller; production must restrict generation-specific writer identity and lease epoch at the sink, and coordinate writer advancement with the publication barrier. Generation pointer updates are transactional in this local database, not a proof of atomic publication across different systems. The fixture does not use an actual snapshot/CDC handoff, resource throttler, model, broker, outbox, external effects, concurrent connections or crash recovery. It retains tombstones as state and detects conflicts with the currently selected equal revision; historical conflicts superseded by higher revisions may require separate stronger ledger checks. It checks selected sequential invariants only. In a real implementation a validation approval cannot be a caller-controlled Boolean, and a previous generation may be incompatible even when caught up.

Each event uses a fixed number of indexed database accesses; the promotion function reads all generation cursors (O(g) for g generations) for simplicity; a production implementation would read the relevant scoped pair with correct locking and validation. Reading the active view is O(u) in live entities, not a request-time feature lookup design. No production performance was measured.

12. Promotion protocols and reader consistency#

A safe release pointer might contain the scope, generation ID, release epoch, source frontier vector, approved manifest digest, validation digest, model/feature contract version and expected predecessor. The control plane should atomically compare the current epoch and predecessor against the validated release request and update the pointer to exactly the approved manifest. For strict cutover, also enforce the authoritative frontier/ownership conditions under the same consistency boundary or a proven coordinated protocol.

Readers must resolve a generation once for a logical request or job, then use compatible pinned artifacts throughout. A request that reads inventory features from G1 and normalization parameters from G2 because it consulted mutable latest twice may produce an invalid result. Namespace caches by generation and relevant input identity; expire or bypass old entries under the current eligibility policy. Historical jobs may remain pinned to older authorized snapshots if their purpose and permission allow, but current decisions need their own currentness checks.

For asynchronous processors, route live updates after the agreed cut to the correct generation and verify continuity. If both generations receive live changes during a rollback window, each retains independent progress and applies its own compatible transformation. A stale worker must not commit a new active pointer or mutate another generation. Do not use dual writes to unrelated stores as proof of atomicity; failures can leave one side ahead. Reconcile the durable log and each generation's checkpoints.

Canarying a new feature generation can reduce exposure, provided cohort assignment respects the product's consistency boundary. A user may need a stable feature/model combination across a session or related workflow. If cross-entity decisions require one coherent state, per-user partial cutover may be unsafe. Validate source completeness, actual user outcomes, latency and feature compatibility, and gate expansion. Shadow scoring can reveal behavioral changes without granting effects, but cannot substitute for control enforcement or mature outcome evidence.

13. Rollback and recovery: old does not mean safe#

Rollback is not merely changing the pointer to the original generation. If G1 stopped receiving events at cutover Fstar and G2 is now at Fstar+100,000 changes, restoring G1 blindly loses current evidence, may resurrect deleted entities and can violate feature freshness. Preserve a compatible recovery generation with continued tail application or a tested bounded catch-up plan. Retaining an old snapshot is useful for audit, but insufficient for a live rollback.

Loading diagram…

A production incident runbook should:

  1. Stop unsafe activation or expansion and prevent new affected current use where required.
  2. Identify the exact active manifest, source frontier, failure class, and affected model/feature/index dependencies.
  3. Choose a currently authorized, compatible recovery generation. Verify current deletions, corrections and source coverage. Catch it up before switch where possible.
  4. If safe rollback cannot meet the required consistency envelope, enter the approved degraded or unavailable mode rather than silently serve stale data.
  5. Perform a conditional switch under a new release epoch, with an enforceable write and read handoff. Verify receipt and actual traffic.
  6. Reconcile predictions and any business effects produced during the bad generation. Correct them through a separate authorized workflow; changing the pointer does not undo them.
  7. Repair the candidate as a new version, document the incident and revalidate before attempting promotion again.

If the old model or transformation is revoked because of an independent security or quality issue, it may not be eligible even if its state is current. Rollback does not override current policy. Retire recovery generations only after the approved recovery window, dependency and retention checks, and evidence of an alternative recovery path.

14. Second scenario: rebuilding a document retrieval index#

A knowledge assistant must re-embed four years of documents after a chunking defect. The existing collection remains live. Build a new index namespace from an immutable authorized document manifest, pin parser/chunker/embedding versions, and consume changes and access/deletion updates from a retained source boundary. Maintain exact document/version and chunk identity. A live delete wins over historical re-embedding; current resource authorization is enforced at retrieval even if old vectors remain during cleanup.

Validate document coverage, chunk-to-source references, retrieval quality, embedding dimension and space compatibility, ACL semantics, query encoder compatibility, latency and resource cost. A matching embedding dimension is not proof that vectors from two embedding models are comparable. Switch the query encoder/index pair through one compatible generation reference. Preserve current source invalidations across rollback. Do not send notifications for every historical document during reindexing.

Unlike ASD-009, the ingestion source and raw capture contract are already assumed to exist; unlike a generic RAG ingestion lesson, the key design is rebuilding one active derived state while updates continue and preventing incompatible readers or stale workers from restoring old state.

15. Monitoring and production test plan#

SignalWhat it detects
Expected vs completed partition rangesCoverage and holes, not merely job success
Candidate and live source frontier vectorsCatch-up convergence and comparability
Oldest unprocessed change and retention headroomRisk of irrecoverable missing tail
Live latency, error budget burn and feature freshnessProduction impact
Source scan load, replica lag, locks and disk pressureUpstream disruption
Duplicate occurrence, identity collision and revision conflictRetry/correctness issues
Deletion and permission invalidation lagRisk of resurrected or exposed data
Candidate validation failures and unexplained diffsSemantic/quality regressions
Promotion epoch conflicts and rejected stale writesConcurrent ownership issues
Unapproved effect attemptsReplay isolation violation
Actual model outcome quality and contract mismatchUser-visible impact
Backfill cost, progress and restart overheadBudget and recovery planning

Distinguish capture backlog from event-time lag and candidate publication age. A healthy historical throughput rate can coexist with an unreachable cutover frontier. Alert before retained history becomes unrecoverable. Include specific owners and stop conditions. Avoid broad high-cardinality labels with raw tenant/entity IDs or private feature values; use restricted diagnostics and aggregate metrics.

Production tests must cover the real source and sink contracts:

  • Snapshot/live boundary under concurrent inserts, updates, deletes and multi-record transactions; native partition resets and cursor expiry.
  • Missing ranges, duplicate deliveries, collision at equal identity, out-of-order full-state revisions and ordered delta semantics.
  • Stateful window dependencies and point-in-time leakage, including correction effects outside nominal output dates.
  • Crash after output write before manifest; after checkpoint before acknowledgement; expired worker lease and concurrent retry.
  • Rebuild under actual live peak, skew, quota pressure, storage failure and recovery; governor pause and restart.
  • Permission revocation and deletion during historical processing and during rollback; replay credential denial at business effect sinks.
  • Candidate changes after validation, active predecessor advancement, stale activation, reader pinning, cache versioning and multi-store publication.
  • Rollback with a lagging prior generation and no viable fallback; verify safe hold, source continuity and real downstream outcome reconciliation.

The local fixture is not sufficient evidence for any of the deployed-system properties above. Run isolated integration and concurrency tests with the real storage, source, broker, reader and effect boundaries; conduct bounded failure rehearsals with approved data and owners.

16. Interview-ready answer#

I would first distinguish repairing historical partitions, reproducing the original information set and rebuilding current serving state. I would pin the source snapshot, native frontier vector, code and feature contract, expected historical partitions, lookback dependencies and allowed purposes. I would create an isolated generation with scoped credentials and independent checkpoint ownership, protect live capacity and prohibit historical business effects at the executor and sink.

While live capture and serving continue, I would rebuild the candidate from the pinned evidence, apply the retained tail under correct source mutation semantics, preserve tombstones and handle late corrections. I would make every partition restartable and every state/position commitment idempotent, with stale-worker fencing. I would establish a compatible cutover frontier, compare exact source coverage and independently validate intended output changes, current permissions, feature/model compatibility and production behavior.

I would atomically activate only the approved immutable release manifest against the expected predecessor and epoch, ensure readers pin a consistent generation and coordinate ongoing tail ownership. I would keep a compatible recovery generation caught up or provide an explicit safe degraded mode. A rollback would use a new epoch and current evidence, not a stale snapshot, and would separately reconcile past decisions and effects. I would monitor source retention, live SLOs, backlog convergence, data integrity, deletion propagation and cost.

The fundamental invariant is that replay can build an alternative history or derived state, but it cannot silently change what production is allowed to treat as current.

References and research transparency#

Authorized offline research exception applied. The references identify established primary research, official technical documentation and reliability guidance. Live contents, link availability and the current Supabase changelog were not verified. Four standard triple-backtick Mermaid diagrams were structurally reviewed; parser execution and frontend rendering were not tested. The Python 3.13.5 fixture was genuinely executed locally and passed 25 assertions; the code hash is recorded above. No actual multi-year dataset, real CDC, broker, feature store, vector store, distributed concurrency, security assessment, load benchmark or production cutover was exercised. All numerical workload and cost values are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython