AI System DesignData and Feature InfrastructureModule 02 — Data and feature infrastructure
Designing a Shared Data Ingestion Platform for Multiple AI Applications
Question 32 of 47 · Updated
On this page
- 1. Requirements: share transport and evidence, not all semantics
- 2. Reference architecture
- 3. Separate native source contracts from the canonical envelope
- 4. Source-specific adapter responsibilities
- 5. Batch, streams and CDC: define the capture frontier
- 6. Validation, normalization and schema evolution
- 7. Durable accounting, idempotency and checkpointing
- 8. Quarantine is an accounting state, not a hidden deletion
- 9. Independent application projections and reproducible publication
- 10. Worked retail ingestion scenario
- 11. Tested implementation: versioned capture ledger and independent replay
- 12. Replay and lineage: separate recovery from reinterpretation
- 13. Backpressure, capacity planning and cost
- 14. Tenant isolation, purpose and deletion governance
- 15. Operational evidence and incident response
- 16. Production validation and acceptance
- 17. Interview-ready answer
- References and research transparency
Capture source data once under explicit source-specific contracts, preserve its identity and lineage, normalize it into governed domain datasets, and let each AI application independently build and release its own projections. Share the expensive, reliability-sensitive work of extraction, durable landing, validation, checkpointing, governance and replay. Do not force every source into one universal business schema or every AI workload into one index. Acknowledging durable capture, accepting a normalized record and publishing a complete application input are three different commitments.
How would you build a shared data ingestion platform for multiple AI applications with different source contracts?
ASD-009 | Module 02 — Data and feature infrastructure | Progressive learning order 19. This begins the third module in learning order after architecture fundamentals and architecture contracts. ASD-083 defined service-to-service domain facts and compatible event contracts; here the platform ingests heterogeneous operational sources, including those that do not emit domain events, and produces reusable governed data products. Existing MLOps data-contract, ingestion quality, schema-evolution and multi-dataset scheduling lessons explain individual validation and producer-consumer agreements. The RAG document ingestion and duplicate-vector lessons address retrieval preparation and index safety. They are prerequisites; this lesson focuses on a common capture substrate, adapter obligations, separate capture and publication frontiers, reusable canonical datasets, tenant/purpose governance, and independently reproducible application projections. Feature stores serve and materialize features; ingestion establishes the underlying source evidence. ASD-010 will cover inconsistent feature snapshots, and ASD-011 will address large historical backfills coexisting with live state. All scenarios and sizing figures are hypothetical. The exact Python fixture was executed locally, not on a real source or distributed ingestion service.
1. Requirements: share transport and evidence, not all semantics#
Consider an enterprise retail platform supporting four AI products: inventory forecasting, fraud detection, a policy-document assistant, and a supplier-risk dashboard. Its input sources are an order database, warehouse inventory updates, supplier APIs and uploaded documents. Without a shared substrate, each team builds its own connectors, retries, storage, permission checks and historical replays. The operational database receives redundant scans, connector bugs multiply, and downstream teams disagree about which revision a model saw.
The shared platform must preserve the meaning of each input and the independent correctness requirements of its consumers.
| Source | Native capture | Required contract details |
|---|---|---|
| Order database | Consistent snapshot plus CDC | Primary key, transaction boundary, source position, delete/update semantics |
| Warehouse devices | Partitioned event stream | Device identity, event time, sequence/reset behavior, payload schema |
| Supplier API | Incremental polling and periodic reconciliation | Page/cursor stability, quotas, modified-time meaning, deletion visibility |
| Document upload | Object plus manifest | Immutable object version, digest, content type, access and deletion policy |
| Consumer | Reusable input | Consumer-specific projection and readiness |
|---|---|---|
| Inventory forecast | Orders, stock revisions and calendar facts | Point-in-time aggregates, labels and versioned training manifests |
| Fraud detection | Authorized transaction and entity updates | Low-latency risk features with strict freshness and completeness |
| Policy assistant | Governed document versions and access metadata | Parsing, chunks, embeddings, retrieval and citation validation |
| Supplier-risk view | Supplier facts, inspection and delivery history | Reconciled supplier statistics and evidence status |
Define source onboarding, capture latency, recovery and retention, record accounting, acceptable missingness, dataset ownership and permitted downstream purposes. A source may be timely enough for daily forecasting but inappropriate for real-time fraud scoring. Shared capture should not imply shared freshness requirements or shared processing permission. A design that marks all applications ready because a connector finished reading a page is incorrect.
Start with a small number of high-value source families and a strong contract template. Avoid designing a universal connector before discovering the source's actual guarantees. Some legacy sources may not support consistent incremental snapshots or reliable deletes; expose that limitation in the contract and prohibit consumers that require a stronger guarantee.
2. Reference architecture#
The diagram is a logical decomposition, not a requirement for separate deployments or a particular broker. The source owners remain authoritative for operational facts; the platform owns capture and canonicalization contracts, raw and normalized persistence, and supported replay behavior. Application owners own feature definitions, chunking, model inputs, publication gates and outcomes. A central governance owner defines purpose restrictions, retention and access, enforced throughout. The ingestion platform should not decide which model to train merely because new data arrived.
A control plane registers sources, credentials references, contract versions, adapter releases, schedules, allowed purposes, ownership, quality policy and current source/partition leases. A data plane performs reads, landing, decoding, normalization and distribution. Source-specific privileges are scoped to least necessary access; an adapter for supplier A must not inherit the database administrator credentials of a different source.
A durable raw landing area might be an object store with manifests, an append-only database ledger, or a retained event log. Choose based on record sizes, replay horizons, throughput, durability and deletion requirements. A lakehouse table format can provide versioned dataset snapshots and commit metadata, but its existence alone does not guarantee complete source capture. A broker offset is transport position, not dataset publication status. Design the boundary explicitly.
3. Separate native source contracts from the canonical envelope#
A source contract includes identity, structure, meaning, mutation semantics, capture mechanism, completeness and ordering guarantees, expected volume, freshness/availability, permission, retention and incident ownership. Schema validation is necessary but insufficient: a producer switching quantity from pieces to cartons may break every consumer while the integer field remains valid.
Define a common envelope for provenance and routing, with domain-specific typed payloads. The following is illustrative JSON, not an official standard schema.
JSON{ "envelope_version": 1, "tenant": "retail-a", "source": "warehouse-12", "source_epoch": "approved-connection-7", "partition": "stock-0", "source_position": "native-position-1024", "source_contract": "inventory-stock/v2", "entity_type": "inventory_balance", "entity_id": "sku-417", "source_revision": 31, "operation": "upsert", "event_time": "2026-01-15T10:00:00Z", "captured_at": "2026-01-15T10:00:04Z", "raw_ref": "raw-artifact-1024", "normalizer_release": "inventory-normalizer/r8", "canonical_contract": "inventory-balance/v1", "payload": {"available_units": 42, "unit": "piece"} }
Native position need not be a number or globally ordered; store its exact representation and the adapter's checkpoint semantics. Scope includes source incarnation/epoch and native partition or cursor domain. The source position identifies a captured occurrence, entity identity identifies what changed, and source revision describes the logical version of that entity. Content digest detects certain payload mismatches but does not identify distinct legitimate transactions with identical bodies. Use stable namespaced identities and explicitly define a business-event identity where deduplicating distinct deliveries of one operation is necessary.
Retain source event/effective time separately from ingestion time, source availability time where known, normalization time and publication time. Downstream training must know what was genuinely available at the intended prediction cutoff, not merely the time a fact was retrospectively reported. Handle ambiguous or timezone-less timestamps according to a reviewed source contract rather than silently guessing.
A common envelope does not make all data semantically uniform. Use a family of canonical domain contracts such as orders, inventory balances, supplier records and document versions. Preserve original typed details, precision, units, missing-value meanings, correction and delete semantics. Do not flatten a scanned PDF, a money amount and a device reading into arbitrary text simply because all products use AI. Large binaries should be referenced through governed immutable artifacts and checksums. A reference is not permission to fetch an object.
4. Source-specific adapter responsibilities#
A connector must implement the actual native source semantics and document its failure model. A generic adapter interface might expose contract discovery, bounded read, resume from native position, durable acknowledgment where supported, health state and reconciliation. Do not pretend a universal offset abstraction is enough for every source.
| Adapter | Cursor and correctness concerns | Mitigation |
|---|---|---|
| CDC | Transaction commit order, snapshot consistency, log retention, before/after images | Use documented snapshot/log coordination, durable native position and transaction metadata |
| REST/API | Pagination changes, overlapping modified timestamps, rate limits, hidden deletes | Stable cursor if offered, overlap windows with dedup, periodic full reconciliation |
| File batch | Late files, overwritten filenames, partial uploads, missing partitions | Object version/digest, expected manifest, atomic or verified completion |
| Event stream | Redelivery, ordering within partition, consumer rebalance, late events | Per-partition checkpoint/fence, durable capture, event-time policy |
| Device uploads | Clock skew, device resets, intermittent connectivity | Trusted device identity/epoch, bounded offline buffer and explicit missingness |
For API polling, a timestamp alone may skip rows with identical timestamps or records updated during pagination. Use a stable cursor or a documented total ordering such as (modified time, entity ID), where the source supports it, plus an overlap window and reconciliation. If the API cannot reveal deletion events, periodic complete inventory comparison may help; if neither is possible, explicitly report that deletions cannot be reconstructed reliably. Never infer deletion from a single incomplete page.
For scheduled files, do not equate file existence with a complete partition. An expected manifest can list logical partition, object version, byte length, record count, digest and schema. Verify the actual stored version and completeness before publication. An overwritten filename is not an immutable source identity. A source correction should create a new lineage-bearing version rather than silently change an earlier snapshot.
Adapter credentials must be scoped, rotated and monitored. A connector's retry cannot exceed the upstream rate limit or consume so much operational database I/O that it harms customers. Use read replicas or documented export interfaces where appropriate; replica lag and consistency guarantees must be explicit. Some snapshot operations require long-lived transactions and can impose retention/storage costs on the source. Include the source owner in capacity and recovery design.
5. Batch, streams and CDC: define the capture frontier#
Batch ingestion works well for bounded exports and daily datasets. Streaming is useful for continuously updated facts with latency requirements. CDC captures database changes from supported logs or equivalent source facilities. It is not identical to polling rows by updated_at, and a CDC row change is not necessarily a domain event. A transaction may change several rows, and a storage-level update may not mean the business event a model needs. Domain interpretation belongs to governed transformations and the source owner.
An initial snapshot followed by CDC must cover the transition without gaps. A database-specific connector may establish a consistent snapshot tied to a log position, buffer or retain subsequent committed changes, then apply them after the snapshot. The exact mechanism depends on the source and connector. Do not take an arbitrary full-table scan, record the current log position at the end, and assume concurrent changes were captured.
This conceptual sequence assumes the source supports the declared coordinated snapshot procedure and log retention covers the capture delay. PostgreSQL logical decoding, for example, requires attention to replication slots and retained WAL. A crashed or slow connector can increase source retention pressure; monitor lag and disk capacity and use approved recovery/rebootstrap procedures. Different databases use different position and transaction semantics. A generic integer increment is not a portable CDC offset.
Keep transaction boundaries where required by the downstream domain. For a multi-row transfer, exposing a partially applied transaction can violate an inventory invariant. A consumer requiring atomic source transaction visibility must stage all relevant changes and promote them together. A consumer performing approximate analytics may have a different explicitly approved completeness contract.
Record two kinds of progress: durable native capture (all required records through a source-defined cursor durably accounted for) and normalized/published readiness. A stream processor's event-time watermark expresses its progress assumption about late data; it is not the same as a source offset or an absolute proof that no earlier events can arrive. Preserve late and corrected facts under the appropriate consumer policy.
6. Validation, normalization and schema evolution#
Separate decoding, record validation, domain adaptation, cross-record consistency, and publication validation.
- Decode safely with size/depth limits, declared encoding and content type. Preserve original bytes or trustworthy immutable artifact reference before transformations when retention allows.
- Validate schema and identity, types, permitted values, finite numeric quantities and required timestamps.
- Apply reviewed source-specific mapping: explicit unit conversions, canonical IDs, null semantics, enumeration mapping and source revision.
- Validate cross-record constraints and source completeness against relevant reference snapshots and expected manifests.
- Validate the canonical dataset for intended permitted uses; applications separately enforce feature, training or retrieval quality gates.
A rule suite must have a version and owner. Not every validation failure has the same disposition. An optional field missing in one record may be acceptable for a text-search projection but critical for a training label. A wrong unit in an inventory movement can invalidate an entire partition. Do not replace missing or invalid values with zero merely to satisfy a numeric schema.
Use a schema registry or equivalent approved contract catalog. Distinguish the raw source schema, envelope schema and canonical domain schema. Version the adapter and normalizer as well. Compatibility checks depend on serialization format and actual consumers: adding a nullable field may be compatible with a tolerant reader, while adding a new closed enumeration value may break old code. A type-preserving change in business meaning is breaking even if the schema registry accepts it.
Example: inventory source v1 uses sku and units; v2 uses product_id and quantity with exactly the same approved meaning (available pieces). An adapter can map both to entity and quantity under the same canonical contract. If v2 instead reports on-hand inventory including reservations, it cannot be mapped to available quantity without an approved definition and adequate information. Introduce a distinct canonical attribute or version; never mask semantic change by renaming fields.
For a compatible source transition, deploy readers that support both versions, test actual historical fixtures and downstream expectations, then enable the new source writer. For a breaking canonical change, publish parallel approved versions or migrate consumers through a defined compatibility window, with clear ownership, rollback and replay support. Do not overwrite previous normalized artifacts with today's normalizer and call them the same version.
7. Durable accounting, idempotency and checkpointing#
If raw bytes and a relational checkpoint live in separate systems, atomicity requires a designed protocol: write an immutable object under an idempotent key, verify its version/digest, then commit a manifest and checkpoint referring to that object. Or store the data and cursor in one appropriate transactional boundary. A crash before manifest commit leaves a potential orphan to reconcile; a crash after commitment but before acknowledgment causes safe re-read. Do not advance a checkpoint to a position whose durable data is missing. A retention policy must not remove an artifact still referenced by a recoverable checkpoint.
For each source partition, distinguish the latest seen position, captured contiguous frontier and consumer application progress. Some native position systems have gaps by design (compaction, transaction markers, log sequence addresses). "Contiguous" means complete according to the documented adapter contract, not necessarily every integer offset. Store source epoch so reused offsets after reset cannot silently collide. Concurrent connector workers need fencing or a transactionally enforced ownership claim; a stale worker must not overwrite a newer checkpoint.
Retries are normal. Use a stable native occurrence key plus payload integrity check. Re-reading an exact occurrence should not create a second committed capture; a different payload claiming the same immutable identity is a source-integrity incident. A second occurrence with a different source position may be a legitimate correction or a duplicate business operation: apply the explicit domain identity semantics, not blanket hash deduplication. Two customers can have identical payloads and must remain separate.
For complete-state records, a later authoritative entity revision can supersede an older revision, with tombstones retained so stale upserts cannot resurrect deletions. For delta events, skipping earlier deltas can corrupt state: require ordered application, gap repair or an approved full-state recovery. Detect conflicting content at the same source revision. If the upstream does not supply a reliable revision, use an approved snapshot/cursor order and conflict rules rather than assume arrival order reflects truth.
8. Quarantine is an accounting state, not a hidden deletion#
Quarantine stores a durable reference to invalid or unsupported records, the relevant source identity and position, contract/normalizer revision, reason, incident owner and remediation history. Restrict access because invalid records may contain private or unexpected sensitive content. Keep safe reason codes in general telemetry; never dump raw malformed data into logs. Treat executable-looking strings, document content and retrieved data as untrusted.
A platform may continue durable capture after isolating a poison record, preventing a connector from losing the entire upstream retention window. That does not imply canonical completeness. If a required record is quarantined, a strict application must block promotion until repaired or explicitly approved as outside its input scope. Another application using unrelated datasets may continue. A legitimately partial projection should publish coverage and exclusions under its own contract; it must not say complete.
Transient storage or network errors need bounded retries, backoff and durable recovery rather than permanent data-quality quarantine. Incompatible schema changes may require pausing normalization while raw capture continues. If capture itself cannot safely preserve a record, do not acknowledge it as durable. Repair workflows should record a versioned correction, approved decoder upgrade or explicit exclusion, retaining the original evidence and auditing the downstream impact. Never silently edit raw history to force the pipeline green.
9. Independent application projections and reproducible publication#
A canonical data product needs an explicit owner and meaning. Each consumer should pin a versioned dependency manifest, not read arbitrary mutable latest tables. A training manifest may contain exact source partition ranges, canonical table snapshot IDs, feature transformation releases, temporal cutoffs, validation results and authorized purpose. A serving feature projection may consume incremental changes under a freshness/ordering contract. A retrieval projection builds chunks and embeddings only for authorized document versions. These stages have independent release pointers, rollback and quality evidence. A slow vector rebuild must not stall capture of inventory data or the fraud feature pipeline.
Publish staged output only when the relevant consumer's requirements pass. An atomic table snapshot or generation-pointer switch can hide half-written results when supported by the storage and reader contract. Include canonical and consumer transformation identity, source coverage, unresolved gaps, quality evidence, generation and expected predecessor. Stale workers must not activate an old generation after a newer one wins. Do not let a downstream projection publish itself as a fully validated canonical source.
The MLOps multi-dataset scheduling lesson addresses aligning source snapshots for a training run; ASD-010 addresses conflicting predictions from independently updated feature snapshots. In this lesson the ingestion platform provides those consumers with the identity, completeness and availability evidence they need, rather than attempting to reconcile every downstream model result.
10. Worked retail ingestion scenario#
Suppose warehouse W reports full-state inventory for item X through one partition. Capture offsets in this fictional adapter are contiguous, whereas entity revisions can arrive out of order:
| Capture position | Input | Durable disposition | Latest inventory projection |
|---|---|---|---|
| 1 | v1: sku X, revision 1, units 5 | Accepted | X=5 |
| 2 | v2: product_id X, revision 2, quantity 8 | Accepted | X=8 |
| 3 | Delete revision 3 | Accepted | X absent, tombstone retained |
| 4 | Late full-state revision 1 | Accepted as historical evidence | X remains absent |
| 5 | Unsupported source schema | Quarantined | Strict new publication blocked |
If position 3 arrives before 2 in this specific adapter, position 3 cannot advance the contiguous frontier; the missing range is recovered first. If a duplicate arrives with identical position and payload, it is a repeat, not new state. A different body for position 1 is an integrity collision. For this complete-state contract the old revision is harmless after the tombstone. With an increment/decrement event contract, skipping movement events may be unsafe.
Consider a separate supplier file with an expected 50,000 rows. It is delivered once to shared capture, but a validation suite finds 250 invalid supplier addresses and five missing mandatory supplier identifiers. A forecast using only authorized order amounts might not depend on supplier addresses. A supplier-risk application requiring validated identities cannot approve the missing-identity rows or claim complete coverage. The source and data product owners must agree whether a subset can be released, and whether duplicate or missing keys compromise aggregate interpretation. No platform-wide one-size-fits-all 99% quality threshold solves this.
11. Tested implementation: versioned capture ledger and independent replay#
This Python/SQLite fixture models two compatible source versions, a scoped capture ledger with original logical payload and digest, contiguous synthetic checkpoints, quarantine and a strict independent latest-state projection. The ledger and checkpoint commit together. Replay reads the captured normalized records and returns a fresh in-memory view only if no quarantine or current equal-revision conflict is encountered. Deletions remain in state as tombstones until projection output is produced.
PYTHONimport hashlib import json import sqlite3 def encode(value): return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) def normalize(raw): # Two approved full-state contracts for the same inventory entity. version = raw.get('schema') if type(version) is not int or version not in (1, 2): raise ValueError('unsupported schema') entity = raw.get('sku') if version == 1 else raw.get('product_id') revision = raw.get('revision') op = raw.get('op') if (not isinstance(entity, str) or not entity or type(revision) is not int or revision < 1 or op not in ('upsert', 'delete')): raise ValueError('invalid identity or operation') quantity = raw.get('units') if version == 1 else raw.get('quantity') if op == 'upsert' and (type(quantity) is not int or quantity < 0): raise ValueError('invalid quantity') return entity, revision, op, quantity if op == 'upsert' else None def ingest(db, tenant, source, offset, raw): # Trusted scope; fixture adapter supplies contiguous synthetic offsets. if type(offset) is not int or offset < 1: raise ValueError('invalid offset') payload = encode(raw) digest = hashlib.sha256(payload.encode()).hexdigest() db.execute('BEGIN IMMEDIATE') try: previous = db.execute('SELECT digest FROM ledger WHERE tenant=? AND source=? AND pos=?', (tenant, source, offset)).fetchone() if previous: if previous[0] != digest: raise ValueError('position collision') db.commit() return 'DUPLICATE' cursor = db.execute('SELECT pos FROM checkpoints WHERE tenant=? AND source=?', (tenant, source)).fetchone() if offset != (cursor[0] if cursor else 0) + 1: db.rollback() return 'GAP' try: entity, revision, op, qty = normalize(raw) except ValueError as exc: status, reason, canonical = 'QUARANTINED', str(exc), None else: status, reason = 'ACCEPTED', None canonical = encode({'entity': entity, 'revision': revision, 'op': op, 'quantity': qty}) db.execute('INSERT INTO ledger VALUES (?,?,?,?,?,?,?,?)', (tenant, source, offset, digest, payload, status, reason, canonical)) db.execute('INSERT INTO checkpoints VALUES (?,?,?) ON CONFLICT(tenant,source) ' 'DO UPDATE SET pos=excluded.pos', (tenant, source, offset)) db.commit() return status except BaseException: db.rollback() raise def project(db, tenant, source): # Rebuild a fresh in-memory view; do not promote incomplete history. state = {} for status, body in db.execute('SELECT status,canonical FROM ledger ' 'WHERE tenant=? AND source=? ORDER BY pos', (tenant, source)): if status != 'ACCEPTED': return 'BLOCKED', None record = json.loads(body) key = record['entity'] old = state.get(key) if old and old['revision'] == record['revision'] and old != record: return 'CONFLICT', None if old is None or old['revision'] < record['revision']: state[key] = record return 'READY', {k: v['quantity'] for k, v in state.items() if v['op'] != 'delete'} db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE ledger(tenant TEXT,source TEXT,pos INTEGER,digest TEXT, raw TEXT,status TEXT,reason TEXT,canonical TEXT,PRIMARY KEY(tenant,source,pos)); CREATE TABLE checkpoints(tenant TEXT,source TEXT,pos INTEGER,PRIMARY KEY(tenant,source));''') a = {'schema': 1, 'sku': 'x', 'revision': 1, 'op': 'upsert', 'units': 5} b = {'schema': 2, 'product_id': 'x', 'revision': 2, 'op': 'upsert', 'quantity': 8} d = {'schema': 2, 'product_id': 'x', 'revision': 3, 'op': 'delete'} assert ingest(db, 'a', 'stock', 1, a) == 'ACCEPTED' assert ingest(db, 'a', 'stock', 1, a) == 'DUPLICATE' assert ingest(db, 'a', 'stock', 3, d) == 'GAP' assert ingest(db, 'a', 'stock', 2, b) == 'ACCEPTED' assert project(db, 'a', 'stock') == ('READY', {'x': 8}) assert ingest(db, 'a', 'stock', 3, d) == 'ACCEPTED' assert ingest(db, 'a', 'stock', 4, a) == 'ACCEPTED' assert project(db, 'a', 'stock') == ('READY', {}) assert ingest(db, 'b', 'stock', 1, a) == 'ACCEPTED' assert project(db, 'b', 'stock') == ('READY', {'x': 5}) assert ingest(db, 'b', 'stock', 2, dict(a, units=True)) == 'QUARANTINED' assert project(db, 'b', 'stock') == ('BLOCKED', None) assert ingest(db, 'b', 'stock', 3, dict(b, schema=3)) == 'QUARANTINED' assert db.execute("SELECT pos FROM checkpoints WHERE tenant='b'").fetchone() == (3,) assert ingest(db, 'c', 'stock', 1, a) == 'ACCEPTED' assert ingest(db, 'c', 'stock', 2, dict(a, units=9)) == 'ACCEPTED' assert project(db, 'c', 'stock') == ('CONFLICT', None) try: ingest(db, 'a', 'stock', 1, b) except ValueError: pass else: raise AssertionError('collision accepted') db.execute("CREATE TRIGGER fail_cursor BEFORE UPDATE ON checkpoints BEGIN SELECT RAISE(ABORT,'fault'); END") try: ingest(db, 'a', 'stock', 5, b) except sqlite3.IntegrityError: pass else: raise AssertionError('fault not injected') assert db.execute("SELECT count(*) FROM ledger WHERE tenant='a' AND pos=5").fetchone() == (0,) assert db.execute("SELECT pos FROM checkpoints WHERE tenant='a'").fetchone() == (4,) db.execute('DROP TRIGGER fail_cursor') assert ingest(db, 'a', 'stock', 5, b) == 'ACCEPTED' assert project(db, 'a', 'stock') == ('READY', {}) assert project(db, 'a', 'stock') == project(db, 'a', 'stock') print('24 checks passed')
Actual local execution on Python 3.13.5:
24 checks passedTwenty-two assertions plus two expected-exception checks exercise version normalization, exact duplicate replay, a missing capture position, latest-state projection, delete and stale update, separate tenant state, invalid Boolean quantity, unsupported schema quarantine, capture progress through quarantined records, blocking strict publication, conflicting equal revision, immutable position collision and a simulated checkpoint-update failure. An injected SQLite trigger aborts the checkpoint update after the ledger insertion; both writes roll back, the old checkpoint survives, and retry succeeds. The final rebuild still respects the tombstone despite late old data. Code fingerprint is MD5 80b64a5f3bb8cd5331261811a401fcb7 excluding the terminal newline.
This is a narrow pedagogical fixture, not a production connector. It expects a predecoded dictionary with JSON-compatible values, trusted tenant/source and synthetic contiguous integer positions. It stores serialized logical JSON, not the original wire bytes, and does not implement cross-language canonicalization, raw object manifests, schema registry, source epochs, multi-partition transactions, actual CDC or credential/authorization checks. Its strict projection assumes no relevant quarantines are resolvable within the captured range; a production correction/replay workflow needs versioned dispositions and explicit coverage manifests. The projection detects conflicting equal *current selected* revisions, not every possible conflict in historical revisions already superseded; a real source ledger must enforce the stronger invariant if required. The adapter does not deduplicate business events with distinct positions; that depends on the source contract. The example does not implement dataset release pointers or external projections and the last equality assertion exercises deterministic replay on unchanged input, not recovery across a process crash.
BEGIN IMMEDIATE provides a local write transaction for this in-memory SQLite connection. The test proves selected sequential invariants and an injected transactional rollback, not distributed exactly-once semantics, real concurrent writers, durable crash recovery or real broker behavior. With n retained records, projection scans O(n) records and retains O(u) entities, including tombstones, for u distinct entity keys. The ledger has indexed point lookups. Actual storage and throughput depend on serialization, index costs, partition contention and infrastructure; no production performance was measured.
12. Replay and lineage: separate recovery from reinterpretation#
Replay has several purposes: retry a missed capture, rebuild a damaged canonical generation, reconstruct an application projection, repair a decoder error, or reproduce a historical model input. The identity and permitted effects differ.
For same-generation recovery, reuse stable operation identities and the exact adapter/normalizer contract where possible. For corrected interpretation, create a new canonical generation with a new normalizer revision and links to original raw occurrences and correction evidence. For an application rebuild, use an isolated projection namespace and pinned canonical snapshot, then validate and promote only if current source and consumer contracts allow. Do not send a historical replay into a live notification or payment effect path. Historical AI inference may not be reproducible bit-for-bit; preserve authorized historical result artifacts separately when exact output matters.
The lineage graph should link source identity/version and native positions, raw artifacts, capture run/adapter release, schema and validation rule versions, canonical snapshot/partition, consumer transformation and result/model training manifest. OpenLineage supplies a useful vocabulary for jobs, runs and datasets; W3C PROV provides general provenance concepts. Neither automatically proves correct capture or permissions. Verify record counts, hashes and source coverage under the specific source contract.
Use a consistent snapshot plus retained incremental range for a rebuild. Retention must cover recovery objectives and the largest expected replay window, or a fresh source snapshot and repair procedure must be available. Record whether deletions and retention constraints make historical reconstruction incomplete. ASD-011 will examine backfill admission, live/historical isolation and safe activation in more depth; this lesson establishes the shared substrate it requires.
13. Backpressure, capacity planning and cost#
Bound each stage independently. Source adapters respect upstream quota and source health. The raw buffer absorbs a bounded transient mismatch; normalization and projection consumers have independent queues, worker pools and progress. A downstream embedding bottleneck must not force duplicate source capture or stop unrelated canonical feeds. Pause or slow capture where the native source supports it; if an upstream cannot be throttled, provision durable landing and explicit overload handling. Never discard required data silently when a queue fills.
Use per-source and tenant quotas, weighted fairness, bounded concurrency and prioritized recovery. Prioritize required live data according to agreed deadlines, not simply largest tenant volume. Reserve capacity for deletes and access invalidations. For finite source retention, monitor time to retention exhaustion; scaling workers after a source log has been truncated cannot recover missing data without rebootstrap or other evidence. Retry budgets and jitter prevent dependency outages from becoming retry storms.
Worked sizing, in decimal units, for an invented business:
| Input | Assumed daily volume | Average captured bytes | Raw volume/day |
|---|---|---|---|
| Order and stock CDC | 8 million records | 0.8 KB | 6.4 GB |
| Device stream | 12 million records | 0.5 KB | 6.0 GB |
| Supplier API | 1 million records | 1.2 KB | 1.2 GB |
| Uploaded files | 20,000 objects | 250 KB | 5.0 GB |
| Total | 21.02 million occurrences | Mixed | 18.6 GB |
Thirty-day raw retention is about 558 GB before compression, metadata, indexes, replicas and lifecycle overhead. Three complete raw copies would use approximately 1,674 GB under those simple assumptions. Canonical datasets and application projections add separate storage. Compression may reduce size; large documents can need extra derived artifacts. The approximate average occurrence rate is 21,020,000 / 86,400 = 243.3/s; do not size from that average alone. A few large files may dominate bytes and processing time despite low occurrence rate.
Assume one homogeneous stream has a sustained arrival rate of 400 records/s and is paused for 15 minutes. It accumulates 360,000 records. If recovery service capacity is 650 records/s while arrivals continue at 400/s, net drain is 250/s and ideal catch-up time is 1,440 seconds = 24 minutes. If capacity is at most 400/s, no backlog drain occurs under those assumptions. Real workloads have variable record sizes, partitions, retries and dependency quotas; separately check bytes/s, CPU, memory, I/O and source retention. If raw retention remaining is only ten minutes, this recovery strategy may already be infeasible.
For a shared supplier API limited to 100 requests/min, four uncoordinated products polling at 40 requests/min each would offer 160 requests/min. A single approved capture adapter at 40 requests/min can provide reusable data for compatible purposes without duplicating upstream calls. Downstream projections still incur work and may need additional source scopes or latency. Sharing is worthwhile only where data contracts and permissions genuinely overlap. Capture once does not mean authorize every possible reuse.
14. Tenant isolation, purpose and deletion governance#
Source registration binds credentials, tenant and permitted datasets using a trusted control plane. The input payload cannot choose its own tenant or unrestricted destination. Use scoped credentials, encryption, access controls and isolation across raw landing, catalogs, canonical datasets, checkpoints, quarantine, queues, logs, caches and consumer exports. An opaque artifact reference is not a bearer credential. Dedicated capture infrastructure may be appropriate for regulated or noisy tenants; a common codebase and compatible contract can still be shared.
Data classification and permitted purpose must survive normalization and derivation. If a source is licensed only for internal analytics, do not make it available to a third-party inference service or training pipeline by default. Enforce consumer subscriptions/access at the dataset boundary and resource reads, including replay. Avoid copying secrets, unnecessary raw personal data or unauthorized source text to model prompts or general telemetry. Validate and sandbox parsers and untrusted document processing according to risk; source records can carry malicious content.
Deletion and revocation must propagate through authorized lineage to raw/normalized data and dependent projections under the applicable obligations. Retaining tombstones and minimal necessary evidence is different from retaining deleted sensitive payloads indefinitely. Define retention, legal hold, correction, deletion propagation, backup recovery and replay limitations with accountable governance owners. A rebuild must not restore revoked access or resurrect a deleted object from an old snapshot. If complete historical replay is incompatible with required deletion, document that limitation instead of claiming permanent immutability.
15. Operational evidence and incident response#
| Metric | Meaning |
|---|---|
| Source age, native lag and remaining retention headroom | Risk of delayed or irrecoverable capture |
| Capture coverage and gap age per partition | Whether the captured range is complete |
| Raw durable bytes, record counts and digest failures | Landing integrity |
| Duplicate occurrence and identity collision rate | Retry pressure or source inconsistency |
| Normalization failures by contract and rule release | Adapter/semantic issues |
| Quarantine count, oldest unresolved and impacted datasets | Missing evidence, not just failed jobs |
| Canonical published frontier versus capture frontier | Delay caused by normalization or quality |
| Per-consumer generation age and coverage | Actual downstream readiness |
| Replay/rebuild duration, cost and reconciliation results | Recovery effectiveness |
| Access denials, deletion propagation and tenant scope violations | Governance and isolation |
Define each denominator. Capture attempts, distinct native occurrences, canonical entities and application rows are different units. A 99.9% successful capture rate is not proof that every required training partition or document generation is valid. Check expected-vs-actual counts and snapshot manifests, source integrity and downstream readiness. Alert the responsible source, platform or consumer owner based on the violated boundary.
For a schema incident, stop affected canonical promotion, preserve authorized raw capture if safe, identify exact schema/adapter and affected positions, obtain source-owner confirmation, validate the approved mapping with historical and new examples, rebuild impacted canonical generations, rerun quality gates and promote the approved revision. Notify affected AI teams with exact dataset and availability status. A fixed decoder does not retroactively prove that already-issued predictions were correct. Reconcile and correct downstream outputs where appropriate.
16. Production validation and acceptance#
Test connectors against actual source guarantees, not only happy-path fixtures. Include snapshot/live handoff, multiple changes in one transaction, source restart/epoch reset, duplicate and conflicting IDs, overwritten files, incomplete manifests, API cursor expiration, identical modified timestamps, rate limiting and hidden deletes. Validate source-specific field meanings, units, nulls, schema evolution and source revision conflicts. Exercise missing mandatory records and quarantined records separately from optional exclusions.
Test durability boundaries: crash after raw write before manifest, after manifest before acknowledgment, after normalization before publication, competing checkpoint owners, stale projection activation, and recovery when retention is exhausted. Verify durable cursor and data coverage against the native source. Test replay under pinned contracts and changed normalizers, with independent projection generations and correct deletion behavior. Inject backpressure and tenant skew without harming the upstream source or unrelated consumers. Use actual concurrent storage/broker tests and controlled failure injection before production approval.
For application acceptance, verify point-in-time training inputs and no future leakage, serving feature freshness, authorized document retrieval and reproducible manifests. Enforce independent security tests for cross-tenant access, purpose restrictions, restricted quarantine, malicious inputs, credential rotation, expired permissions and deletion propagation. Monitor upstream and downstream outcomes through an approved pilot; the local fixture does not validate any of these deployed properties.
17. Interview-ready answer#
I would first inventory source contracts and consumer requirements, then implement a governed shared capture layer with source-specific adapters for consistent snapshots, CDC, streams, APIs and files. I would persist immutable source identities and authorized original artifacts with native checkpoints, normalize through versioned domain-specific mappings, and separate durable capture from canonical completeness and application readiness. I would validate both schema and meaning, isolate bad records with lineage, preserve ordering and correction semantics, and make retry safe using scoped occurrence identity, atomic durable accounting and source-aware checkpoint fencing.
I would distribute approved canonical data products to independently owned training, serving, retrieval and analytics projections, each with its own temporal, quality and authorization contract and release manifest. I would support bounded replay and recovery, preserve provenance, isolate tenants and purposes, and propagate revocations/deletions. I would size buffers and processing stages independently, protect upstream sources, monitor lag and completeness rather than only successful tasks, and test real source cutover, retries, concurrency, publication and recovery. This produces reusable ingestion infrastructure without forcing every AI application into the same data representation or making a feature store or vector index the source of truth.
The core interview distinction: share capture and governed evidence; keep downstream interpretations, freshness and release decisions explicit and independently owned.
References and research transparency#
Authorized offline research exception applied. References identify established primary research, technical specifications and official documentation. Current URL availability, live contents and the Supabase changelog were not verified. Four standard triple-backtick Mermaid diagrams were reviewed structurally; parser execution and frontend rendering were not tested. The Python fixture was actually executed locally on Python 3.13.5 with 24 checks passing, including injected rollback. No actual CDC connector, broker, cloud object store, feature store, distributed concurrency, security assessment, load benchmark or production integration was exercised. Numerical scenarios and JSON examples are illustrative.
- Apache Kafka — Documentation
- Debezium — Architecture
- PostgreSQL — Logical Decoding Concepts
- Apache Flink — Timely Stream Processing
- Akidau et al. — The Dataflow Model
- Apache Avro — Specification
- JSON Schema — Draft 2020-12
- Open Data Contract Standard
- OpenLineage — Specification
- Apache Iceberg — Specification
- W3C — PROV Data Model
- NIST SP 800-207 — Zero Trust Architecture
- SQLite — Transaction Documentation
- Google SRE — Addressing Cascading Failures
References
- 1.Apache Kafka — Documentationkafka.apache.org
- 2.Debezium — Architecturedebezium.io
- 3.PostgreSQL — Logical Decoding Conceptspostgresql.org
- 4.Apache Flink — Timely Stream Processingnightlies.apache.org
- 5.
- 6.Apache Avro — Specificationavro.apache.org
- 7.JSON Schema — Draft 2020-12json-schema.org
- 8.Open Data Contract Standardgithub.com
- 9.OpenLineage — Specificationopenlineage.io
- 10.Apache Iceberg — Specificationiceberg.apache.org
- 11.W3C — PROV Data Modelw3.org
- 12.
- 13.SQLite — Transaction Documentationsqlite.org
- 14.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython