AI System DesignAI System Design FundamentalsModule 11 — Architecture contracts and integration
Composing Independently Owned AI Services with Versioned Event Contracts
Question 24 of 47 · Updated
On this page
- 1. Start with the capability and its ownership contract
- 2. Architecture: independently owned state and explicit facts
- 3. Define an event envelope before designing topic names
- 4. Domain schema versus model provenance
- 5. Version the event contract, not every deployment
- 6. Independent deployment through reader-first transitions
- 7. Choreography versus orchestration
- 8. Causality and fan-in: join by meaning, not arrival time
- 9. Reliable publication: transactional outbox
- 10. Ordering, idempotency and logical revisions
- 11. Replay and model reproducibility
- 12. Dead-letter handling and compatibility incidents
- 13. Tested example: versioned document-event consumer with atomic inbox and outbox
- 14. Worked throughput and retention scenario
- 15. Security and data governance across independently owned capabilities
- 16. Observability and operational ownership
- 17. Production acceptance and independent release checklist
- 18. Interview-ready answer
- References and research transparency
Compose AI capabilities by publishing versioned facts about domain state, not by allowing services to depend on each other's internal model formats, tables or execution timing. Give each event a clear owner, immutable identity, subject, schema and semantic contract, causal context and relevant model/data provenance. Consumers validate supported versions and current scope, apply effects idempotently within their own transaction boundary, and emit their own committed facts. Explicitly coordinate workflows whose completion has a product-level meaning. This allows the document, retrieval, inference, evaluation and publication teams to evolve independently without mistaking loosely coupled messages for guaranteed business completion.
Original curriculum question: How would you compose independently owned AI capabilities using versioned inter-service event contracts?
ASD-083 | Module 11 — Architecture contracts and integration | Progressive learning order 11. ASD-004 selected synchronous, job, batch and streaming execution contracts; ASD-007 selected deployment boundaries; ASD-082 addressed reversible catalog edits within an authoritative owner. This lesson defines the inter-owner composition protocol: the meaning, identity, evolution and ownership of events; causality and provenance; independently deployable consumers; and the distinction between a workflow's progress and a transport's delivery. ASD-018 concerns distributed business compensation and uncertain external effects, not the initial event contract. The published RAG ingestion duplicate-vector and poison-message articles and the FDE dead-letter lesson address operational recovery for particular consumers. They are prerequisites, not duplicated here. The pending Python and SQL lessons cover generic messaging, outbox and schema evolution mechanics; this lesson uses those patterns to compose heterogeneous AI outputs with explicit semantic compatibility and domain authority.
All workload, latency, event counts and retention estimates below are fictional. The Python/SQLite fixture was executed locally; there was no live broker, model service, schema registry or distributed integration test.
1. Start with the capability and its ownership contract#
Imagine an enterprise research workspace. The document team owns canonical documents, revisions and access policy. A parsing service produces an immutable extracted-text artifact for an approved document revision. An embedding service produces a compatible vector generation. A retrieval team maintains a searchable projection. A report-generation team creates an answer or report, and an evaluation service assesses artifacts. Each team can deploy and operate its own capability.
A fragile architecture would let all services update one shared document status field, consume a common undocumented vector representation, and assume messages arrive in the same order as model execution. A more reliable architecture defines the facts that each owner can assert.
| Owner | Published fact | Consumer may infer | Consumer must not infer |
|---|---|---|---|
| Document service | DocumentRevisionCommitted | A specified canonical revision committed | All downstream representations are current |
| Extraction service | ExtractionArtifactReady | A specified extracted artifact exists under its stated contract | The document is authorized for every future reader |
| Embedding service | EmbeddingGenerationReady | A versioned manifest exists for a specified input/model | It is active in retrieval |
| Retrieval service | IndexRevisionActivated | A particular index generation became visible | Every query is authorized or returns correct results |
| Report service | ReportArtifactCommitted | A report artifact and its metadata committed | Claims are correct merely because generation finished |
| Evaluation service | EvaluationCompleted | A stated rubric evaluated a stated artifact | The product release is automatically approved |
A producer owns the truth and meaning of its event. A consumer owns its reaction, its own state and its failure policy. A central transport team owns broker operations, not business semantics. A schema registry team may own compatibility infrastructure, but domain owners approve the target meanings and supported use cases.
Distinguish a domain event (a fact that already happened), a command (a request for a particular owner to do something), a notification (a signal to inspect authoritative state), and a query (a request for information). A message called GenerateReport is a command, not proof that a report exists. An event called ReportCommitted must be backed by actual commitment. An event broker is not inherently an event-sourced database. Event sourcing uses an authoritative event history to reconstruct state; many systems instead publish integration events from ordinary transactional tables.
2. Architecture: independently owned state and explicit facts#
The shared log in this conceptual diagram represents governed channels, not one unrestricted topic. Each subscription filters the event types it is authorized to consume. The document owner writes its own database, the extraction owner writes its own artifact manifest, and retrieval owns its own activation. No event grants access to another owner's private tables. The coordinator tracks product-level completion from durable receipts/events, rather than inferring that every service succeeded because a message was published.
AI work may be synchronous inside a consumer, queued to GPU workers, or performed in batches. The integration contract does not require one execution mode. Inference services may have many replicas; deployment topology is separate from logical ownership. The event contract also separates model inference from authorized effects (ASD-006). A predicted classification is a fact about an issued prediction, not a fact about the underlying real-world class or approval of an action.
3. Define an event envelope before designing topic names#
CloudEvents provides a standard envelope for interoperable event metadata. Its required attributes include specversion, id, source and type; attributes such as subject, time, datacontenttype and dataschema are optional. Applications can define extension attributes subject to its rules. CloudEvents describes event representation, not delivery semantics, authenticity or business compatibility.
A structured JSON example, illustrative rather than a complete production contract:
JSON{ "specversion": "1.0", "id": "01-example-event-74", "source": "/services/documents", "type": "com.example.documents.revision.committed.v1", "subject": "documents/doc-17", "time": "2026-01-15T10:00:00Z", "datacontenttype": "application/json", "dataschema": "https://schemas.example.com/document-revision/1.0.0", "tenantid": "tenant-a", "correlationid": "task-820", "causationid": "cmd-41", "data": { "document_id": "doc-17", "revision": 12, "content_ref": "artifact-opaque-12", "content_digest": "sha256:illustrative", "policy_revision": "policy-9" } }
The example schema URL and digest are placeholders, not real resolvable artifacts. The tenant identifier and source are untrusted until the authenticated publishing identity, scope and payload are verified. The event ID is unique within the producer's source namespace; CloudEvents defines uniqueness by source plus id. A broker delivery ID, retry attempt number, offset and partition are transport metadata and not substitutes for logical event identity. A retransmission of the same event keeps its identity and original logical payload. If two messages claim the same source/id but differ materially, quarantine or investigate an integrity error; do not silently pick the later arrival.
| Metadata | Semantic purpose |
|---|---|
| source + id | Stable immutable event identity |
| type | Named fact and major semantic family |
| schema reference | Exact structural contract or registry identifier |
| subject | Canonical domain entity, not an arbitrary routing string |
| tenant/scope | Authorization and data isolation boundary |
| entity revision | Monotonic version within the defined owner/entity |
| occurrence time | Time of the domain fact, not necessarily processing time |
| correlation ID | Logical workflow or business task grouping |
| causation reference | Immediate triggering command or event identity |
| trace context | Observability context, not business identity |
| producer release | Build/config provenance, when needed |
Use full source/id for causation references where producer IDs are not globally unique. A correlation ID may be shared by hundreds of events; it cannot be used as a deduplication key. A tracing span can be sampled or lost; it cannot be the authoritative workflow receipt. A batch fan-in may have multiple causal predecessors, represented by a dependency manifest rather than forcing every event into a single-parent tree.
4. Domain schema versus model provenance#
A reusable envelope is not a universal AI payload. Domain events should have specific names and typed result contracts. For example, an embedding-generation event could contain:
JSON{ "document_id": "doc-17", "source_revision": 12, "extraction_artifact_ref": "extract-12", "generation_id": "embed-gen-31", "embedding_contract": "retrieval-embedding/v2", "model_release": "embed-r7", "preprocessor_release": "chunker-r4", "dimension": 768, "normalization": "l2", "distance_semantics": "cosine", "expected_chunk_count": 14, "manifest_ref": "manifest-31", "generated_at": "2026-01-15T10:00:12Z" }
The manifest should reference immutable chunk identities, checksums and authorized source lineage. Vector values generally belong in an appropriately governed artifact/index store, not duplicated into every event. The consumer checks the supported embedding contract, generation completeness, dimension and actual normalization/metric assumptions before activating. A 768-dimensional vector from a different embedding space is not interchangeable merely because its shape matches. For prediction artifacts, use ASD-081's target, uncertainty and validity contract; a prediction emitted an hour ago might be historical evidence but not eligible for a live decision.
Include only provenance needed for the consumer: model and preprocessing/prompt release, input/source revision, applicable feature or retrieval version, policy and evaluation references, output digest and time. Keep sensitive prompts and private source content in protected stores with scoped references. A manifest ID is not a bearer credential. Recheck current access before fetching and consuming the artifact. A generation event does not automatically grant permission to expose the underlying document.
5. Version the event contract, not every deployment#
There are independent version axes: transport/envelope version, payload schema version, event semantic version, service build, model artifact version and source entity revision. Do not use one overloaded version integer for all six.
A patch-level application deployment may not change the event at all. A model release can change while satisfying a stable domain contract if evidence and compatibility gates pass. Conversely, changing a score's meaning from probability of a defect in 24 hours to a raw ranking score is breaking even if both remain JSON numbers. Semantic compatibility is a domain obligation in addition to structural compatibility.
| Change | Structural issue | Domain issue |
|---|---|---|
| Add optional evidence reference | May be compatible if readers tolerate it | Define absence without inventing evidence |
| Add required field without a valid default | Old writers cannot supply it | May require staged transition |
| Rename content_ref | Existing readers may fail | Preserve equivalent semantics via adapter or new version |
| Add a class to a closed enumeration | Strict old readers may fail | New class needs explicit consumer behavior |
| Change unit from seconds to milliseconds | Same numeric type | Breaking without explicit conversion/version |
| Change calibrated probability to rank | Same numeric type | Breaking target meaning |
| Change embedding model with same dimension | Schema unchanged | May be incompatible with active index |
Use a major event type change when consumers cannot safely interpret the same semantic contract. A schema registry may assign separate immutable schema IDs to compatible minor revisions. Semantic Versioning can be adopted as an application convention, but its numbers do not automatically prove compatibility. Do not assume every ecosystem's rules are identical.
A registry often checks backward compatibility (new consumer reads old writer data), forward compatibility (old consumer reads new writer data), full compatibility (both), and transitive variants against the relevant historical schemas. Exact definitions and checks depend on the format/registry and configured subject policy. For example Avro reader defaults, Protobuf reserved field numbers and JSON Schema additionalProperties rules have different behavior. A schema-registry check is useful but cannot verify claim truth, authorization, calibration, units or model-output equivalence.
6. Independent deployment through reader-first transitions#
Suppose the document contract v1 contains text_ref, and the desired v2 contains content_ref with the same logical artifact semantics. Renaming is breaking for an old consumer that requires text_ref. Possible approaches include:
- Add content_ref as an optional field while retaining text_ref and define both meanings; deploy readers able to handle both and verify consistency.
- Keep v1 and introduce a separate v2 event type/schema, with consumers subscribing to one designated representation or deliberately deduplicating equivalent logical operations.
- Use a controlled adapter/upcaster to translate an old event into the internal normalized representation, retaining original provenance. If the new meaning cannot be inferred from old data, return unsupported rather than invent a value.
Do not casually republish the same source/id with a changed envelope/payload. If publishing two versioned representations, use distinct event identities with a stable shared domain operation/revision reference and an explicit deduplication/selection strategy. Otherwise a dual subscriber can apply the same work twice. If a consumer reads v2 with a fallback v1 adapter, test the full retained replay horizon, not just yesterday's events.
A compatibility matrix must cover producer version, consumer version, schema format, semantic target, allowed model/feature/embedding bundles and retained messages. The producer team publishes a contract and golden examples. Consumers publish their actual expectations and tests (consumer-driven contract tests where useful). Contract changes require domain ownership and a deprecation policy with a known support window. Independent deployment means the supported combinations work, not that a producer can change semantics unilaterally.
Schema registration should be controlled, immutable and available to producers and consumers under reviewed policy. Cache trusted schemas by exact identity to avoid adding a registry dependency to every event when appropriate; never let a message point the consumer at an arbitrary external schema URL to fetch. Reject or quarantine unknown versions rather than silently parse with the nearest schema. AsyncAPI can document channels, operations, messages and bindings; it does not execute or verify a workflow automatically.
7. Choreography versus orchestration#
In choreography, owners subscribe to relevant domain facts and emit new facts without one component commanding every step. This is useful for independent derived projections, analytics, and notifications with bounded consequences. It avoids a single central decision point but can obscure dependencies and completion. Cyclic subscriptions may trigger event storms, and no one may know whether the user's whole task finished.
In orchestration, a durable workflow owner tracks the required steps, issues scoped commands, consumes receipts and decides what the product can claim. Each capability remains independently owned; the coordinator does not write its private state. This is preferable for a report that requires a specific document snapshot, compatible retrieval index, generation artifact and mandatory evaluation before publication. A missing evaluation event is not proof of failure or success; the workflow can remain pending, time out according to policy, or reconcile authoritative status.
Hybrid composition is often simplest: document revisions trigger extraction and indexing through choreography; report jobs have an explicit orchestrator that waits for an approved source/index boundary and drives their own task lifecycle. Events are durable facts; commands are scoped requests. A coordinator must not invoke an external state-changing tool just because a generated event suggests it. Require authorized effects and appropriate reconciliation.
8. Causality and fan-in: join by meaning, not arrival time#
A report task is created for documents A revision 12 and B revision 8. Extraction, embedding and indexing have different completion times. If B revision 9 arrives while A revision 12 is being indexed, a naive "take latest event" join may combine evidence from a snapshot different from the requested one.
Persist the task's required dependency manifest: canonical subjects/revisions, compatible artifact contracts, allowed model and policy releases, freshness/validity rules, and the exact result or condition expected from each owner. Track a receipt per dependency; duplicates do not advance a completion counter twice. For a snapshot-pinned report, only a result for the requested source revision is eligible unless the product explicitly re-plans and records the change. For a latest-state view, require a bounded freshness contract and update according to authoritative current revisions. These are distinct products.
The diagram does not imply exactly-once command delivery. The coordinator persists its own decision state and stable command IDs; owners deduplicate appropriate commands and report outcomes. A late event after cancellation may still describe a true committed artifact, but the cancelled workflow must not automatically resume. Use lifecycle fencing and current authority when consuming results for protected effects.
9. Reliable publication: transactional outbox#
Writing business data to a database and then publishing an event separately creates a dual-write gap. If the database commit succeeds and the publish fails, consumers may never hear the fact. Publishing before the database commit risks announcing a change that later rolls back.
When state and an outbox table share an appropriate local transaction, persist the state change and event publication intent atomically. A relay reads committed outbox rows, publishes with stable event identity, and records delivery progress. Change-data capture may implement an equivalent relay if its snapshot, log retention and delivery semantics are understood. A producer confirms the local commit independently of the eventual subscriber's processing.
The relay can crash after the broker acknowledges but before recording progress; redelivery is expected. The consumer may crash after its local commit but before acknowledging, so the same input can be received again. Inbox deduplication and durable local effects must be atomic where possible. The consumer can emit a new event through its own outbox in the same transaction. Do not claim the broker, producer database and all consumers participate in a global exactly-once transaction. If a consumer invokes an external service, use appropriate operation identity, receipts and reconciliation; ASD-018 covers those business semantics.
For long GPU tasks, the input consumer should atomically record desired work and dispatch intent, then acknowledge after that commitment if the contract permits. Actual inference happens outside the database transaction; it has its own durable job identity and artifact commit/activation fencing. Do not hold a database transaction during an LLM call.
10. Ordering, idempotency and logical revisions#
Ordering is scoped. A partitioned log may order records within one partition under documented conditions; it does not provide total ordering across entities. Publishing with the entity key can preserve the intended partition boundary, but retries, parallel processing and downstream writes can complete in another order. Consumers must define which ordering they actually need.
For a latest-state projection, a monotonic entity revision prevents late state from overwriting newer state. If a complete snapshot at revision 12 arrives before 11, the projection may accept 12 and ignore 11 if the contract explicitly permits coalescing complete state. For delta events (increment quantity, add variant, subtract quota), skipping revision 11 may lose an essential effect. Require contiguous application, a gap buffer, reconciliation or a full snapshot repair. Never generalize a latest-wins strategy to every event type.
There are two distinct identities: the immutable event ID and the domain effect key. Two separate valid event IDs might represent the same committed revision or operation. Deduplicate event deliveries by source/id; prevent redundant effects with a revision check, operation receipt or domain uniqueness constraint. A repeated event ID with changed content is an integrity incident, not a normal duplicate. A same-revision conflict between two payloads should not be silently resolved by arrival order. Define source ownership and revision uniqueness within tenant/aggregate.
AI computation can finish late. Suppose desired source revision 12 changes to 13 while a worker generates vectors for 12. The completion event for 12 is still a valid historical fact about that generation, but it must not activate 12 as the latest index if the contract requires 13. Use conditional activation against the desired version and approved model/index compatibility. A job lease alone does not fence old writes unless the actual resource checks ownership or version.
11. Replay and model reproducibility#
Replay can rebuild a projection from retained facts, repair a consumer bug, recover from a checkpoint or feed an isolated analysis. It does not automatically mean rerunning AI inference. Preserve the distinction between reapplying recorded facts and generating new artifacts.
For historical evaluation, reproduce the originally issued prediction/artifact and recorded model, data, prompt, feature and policy versions where authorized. Even pinned model artifacts may not guarantee bit-identical output across nondeterministic inference/hardware; prefer replay of immutable recorded outputs if the aim is to reconstruct past state. If using today's model to reprocess old inputs, record a new generation ID and lineage; do not rewrite historical events or present the new output as the original. Retention and deletion obligations may prevent complete reconstruction; communicate the limitation.
A replay must specify range/offsets or snapshot boundary, consumer release and schema adapters, target namespace, permitted source data and whether live side effects are allowed. Rebuilding into a fresh projection requires a separate consumer/projection namespace for deduplication; a shared old inbox may cause every event to be skipped. For replay into the same live effect namespace, keep original operation keys so previously committed effects are not repeated. Avoid replaying events into payment, notification or privileged mutation handlers without explicit approval and safe reconciliation.
A checkpoint includes the relevant partition positions and associated durable consumer state. Retention must exceed expected outage/backfill needs or provide a consistent snapshot recovery mechanism. A highest observed offset is not proof all preceding required records were handled. When a DLQ creates a gap, a contiguous projection may need to stop that entity or partition, repair or rebuild rather than advance silently.
12. Dead-letter handling and compatibility incidents#
The existing FDE and RAG lessons cover poison-message classification and dead-letter operations extensively. Here the cross-owner contract is the central concern. An unsupported schema is often a release coordination failure rather than a transient bad event. Route affected messages to controlled quarantine or pause the incompatible consumer according to ordering requirements. Notify both producer and consumer owners with schema ID, event identity, release and safe validation reason. Do not repeatedly retry a permanent mismatch or discard the event without a business disposition.
Transient database/network failures receive bounded retries, backoff and admission limits. A widespread dependency outage should usually trigger backpressure or circuit breaking rather than fill the DLQ immediately. For a permanent invalid event, preserve sufficient authorized evidence and durably record quarantine before acknowledging according to the actual broker guarantees. DLQ movement may reorder messages; document what consumers can do across gaps.
Repair a schema adapter, producer bug or scope problem and selectively redrive approved events with original identities. If the fact itself was wrong, the producer should emit a new corrective event with a new ID and predecessor reference, not mutate the previously published fact in place. Verify actual domain/projection state after replay. A cleared DLQ is not proof of correctness.
13. Tested example: versioned document-event consumer with atomic inbox and outbox#
This standard-library Python example implements an intentionally narrow latest-state consumer. Its own durable desired-work projection accepts two versions of a document event (v1 text_ref and v2 content_ref). The fixture models a full-state reference, not a delta stream; it may skip stale revisions. It atomically records an inbox, the latest desired revision and a follow-up outbox intent in a single local SQLite transaction. The outbox rows are intent records, not already delivered events.
PYTHONimport json import sqlite3 from dataclasses import dataclass, replace, asdict from hashlib import sha256 @dataclass(frozen=True) class Event: source: str event_id: str tenant: str subject: str revision: int version: int data: dict def normalize(e): if e.source != 'document-service' or not all( type(x) is str and x for x in (e.event_id, e.tenant, e.subject)): raise ValueError('invalid source or identity') if type(e.revision) is not int or e.revision < 1: raise ValueError('invalid revision') if type(e.version) is not int or e.version not in (1, 2): raise ValueError('unsupported schema') if e.version == 1: ref = e.data['text_ref'] else: ref = e.data['content_ref'] if type(ref) is not str or not ref: raise ValueError('invalid reference') return ref def consume(db, e): ref = normalize(e) body = json.dumps(asdict(e), sort_keys=True, separators=(',', ':'), allow_nan=False) digest = sha256(body.encode()).hexdigest() db.execute('BEGIN IMMEDIATE') try: seen = db.execute('SELECT digest FROM inbox WHERE source=? AND event_id=?', (e.source, e.event_id)).fetchone() if seen: if seen[0] != digest: raise ValueError('event identity collision') db.commit() return 'DUPLICATE' row = db.execute('SELECT revision, ref FROM desired WHERE tenant=? AND subject=?', (e.tenant, e.subject)).fetchone() if row and row[0] == e.revision and row[1] != ref: raise ValueError('conflicting source revision') outcome = 'STALE' if row and row[0] >= e.revision else 'APPLIED' if outcome == 'APPLIED': db.execute('INSERT INTO desired VALUES (?,?,?,?) ' 'ON CONFLICT(tenant,subject) DO UPDATE SET ' 'revision=excluded.revision, ref=excluded.ref', (e.tenant, e.subject, e.revision, ref)) db.execute('INSERT INTO outbox VALUES (?,?,?,?,?)', (e.source, e.event_id, e.tenant, e.subject, e.revision)) db.execute('INSERT INTO inbox VALUES (?,?,?)', (e.source, e.event_id, digest)) db.commit() return outcome except BaseException: db.rollback() raise def main(): db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE inbox(source TEXT,event_id TEXT,digest TEXT, PRIMARY KEY(source,event_id)); CREATE TABLE desired(tenant TEXT,subject TEXT,revision INTEGER,ref TEXT, PRIMARY KEY(tenant,subject)); CREATE TABLE outbox(source TEXT,event_id TEXT,tenant TEXT,subject TEXT,revision INTEGER, PRIMARY KEY(source,event_id));''') a = Event('document-service','e1','a','doc',1,1,{'text_ref':'ref1'}) b = replace(a,event_id='e2',revision=2,version=2,data={'content_ref':'ref2'}) assert consume(db,a) == 'APPLIED' assert consume(db,b) == 'APPLIED' assert consume(db,b) == 'DUPLICATE' assert consume(db,replace(a,event_id='late')) == 'STALE' assert consume(db,replace(b,event_id='same')) == 'STALE' assert consume(db,replace(b,event_id='other',tenant='b')) == 'APPLIED' for bad in (replace(b,version=3), replace(b,source='unknown'), replace(b,data={'content_ref':'collision'}), replace(b,event_id='conflict',data={'content_ref':'wrong'})): try: consume(db,bad) except ValueError: pass else: raise AssertionError('invalid event accepted') assert db.execute('SELECT tenant,revision,ref FROM desired ORDER BY tenant').fetchall() == [('a',2,'ref2'),('b',2,'ref2')] assert db.execute('SELECT count(*) FROM inbox').fetchone()[0] == 5 assert db.execute('SELECT count(*) FROM outbox').fetchone()[0] == 3 db.execute("CREATE TRIGGER fail_outbox BEFORE INSERT ON outbox BEGIN SELECT RAISE(ABORT,'injected'); END") c = replace(b,event_id='e3',revision=3,data={'content_ref':'ref3'}) try: consume(db,c) except sqlite3.IntegrityError: pass else: raise AssertionError('fault not injected') assert db.execute("SELECT revision FROM desired WHERE tenant='a'").fetchone()[0] == 2 assert db.execute("SELECT count(*) FROM inbox WHERE event_id='e3'").fetchone()[0] == 0 db.execute('DROP TRIGGER fail_outbox') assert consume(db,c) == 'APPLIED' assert consume(db,c) == 'DUPLICATE' assert db.execute('SELECT count(*) FROM outbox').fetchone()[0] == 4 print('19 checks passed') if __name__ == '__main__': main()
Observed execution on Python 3.13.5:
19 checks passedThe 19 checks comprise fourteen direct assertions and five exception checks. They exercise both schema versions, duplicate input, stale delivery, equal revision with equal reference, tenant-scoped projection identity, unknown source, unsupported version, reused event identity with conflicting payload, same-revision conflicting content, expected state and inbox/outbox counts. An injected SQLite trigger aborts the outbox insertion after the desired-state update: the test confirms the desired revision remains unchanged and no inbox entry survives. Removing the trigger allows retry to succeed, and a subsequent repeat has no additional effect.
The code assumes normalized, trusted inputs and globally unique event IDs per source. Its source string allowlist is not authentication; a real broker and resource service must authenticate producer identities and enforce tenant/subject scope independently. It does not validate a full CloudEvents envelope, JSON Schema, payload size or every Python input type; missing payload keys raise KeyError, which an actual consumer must classify at the boundary. A deterministic Python JSON serialization is used for this fixture's digest, not a cross-language canonicalization standard. The toy stores the last revision and detects current equal-revision conflicts; it does not retain all historical versions or detect conflicts in an already superseded revision. Production owners should preserve sufficient history and specify canonical payload identity.
BEGIN IMMEDIATE acquires SQLite's write transaction before reads. The local transactional test is real, but this is one in-memory connection, not a durable broker, multiple worker processes, real CDC, PostgreSQL isolation test or a crash-after-commit exercise. The outbox key stores the originating event identity; a real outgoing event needs its own producer source/id, type and immutable payload, with causation pointing to the original event. No relay or actual GPU task is implemented. A production consumer needs appropriate isolation/constraints, durable storage, leases or fencing for long work, schema validation, approval and deletion controls, checkpoint and broker-acknowledgment integration.
Expected per-event work includes serialization/hash cost linear in payload size and a fixed number of indexed database operations. Actual lock contention and throughput depend on storage, indexes, transaction mode and workload. The implementation does not establish production performance or exactly-once external effects.
14. Worked throughput and retention scenario#
Suppose a research workspace receives 100,000 canonical document-revision events per day. Assume each eligible revision creates one extraction-ready event, one embedding-ready event and one index-activation event, with no abstention or failure for this first model. There are 400,000 logical events/day across the four owners. If the average envelope and reference payload is 1.5 KB decimal, raw retained event payload is 600 MB/day or 18 GB over 30 days. Three separately stored replicas imply 54 GB raw before broker metadata, compression, indexes, snapshots, checkpoints and storage overhead.
If each event has an average of 2.5 subscriber deliveries, the logical delivery workload is one million/day. A 10% additional delivery-attempt rate yields 1.1 million attempts/day, about 12.73 attempts/s averaged over a full day. At an illustrative peak factor of eight, approximately 102 delivery attempts/s are offered. Delivery attempts are not necessarily inference attempts; an idempotent consumer may recognize a duplicate without expensive work. Measure branch-specific fan-out, replay, model failures and stale generation separately. Do not size a GPU from event-broker throughput alone (ASD-003 covers capacity).
If a consumer is paused for 30 minutes at 80 relevant events/s, it accumulates 144,000 events assuming no loss or processing. On recovery, at 120/s sustainable consumption with 80/s continued arrival, ideal net drain is 40/s, giving one hour to catch up. This is a fluid approximation. Some events may expire, require historical treatment or contain outdated desired revisions. If the domain permits, coalesce full-state work to current desired revisions, while retaining appropriate event disposition and not skipping required deltas. Never interpret recovery lag as proof of invalid model quality. Measure event age at use, not only arrival-to-processing time.
15. Security and data governance across independently owned capabilities#
A valid event envelope does not authorize a service to perform arbitrary work. Authenticate workload identities at publication and consumption, enforce producer ownership of event types, and restrict subscriptions by purpose and tenant/resource rules. Use encrypted transport and storage where required, controlled schema registry access, bounded payloads and safe deserialization. Do not evaluate generated code or tool arguments embedded in event payloads as privileged instructions.
Broker topic permissions alone may be too coarse for multi-tenant object access. Partitioning by tenant is not a complete authorization system. Recheck current resource access when retrieving artifacts and when committing protected effects. A historical event may refer to a document that has since been deleted or whose access was revoked. A replay must not restore old grants or expose removed content. Use authorized references, deletion/tombstone handling, limited retention and controlled artifact access. An immutable log is not an exemption from deletion obligations; design for data minimization and qualified governance.
For cross-trust-boundary events, consider integrity protection, producer verification and scoped credentials with a replay model appropriate to the threat. A hash supplied by an untrusted sender does not authenticate the message. A correlation ID is not a secret, capability or authorization token. Propagated trace metadata can itself be untrusted; avoid recording sensitive data in trace baggage. Keep debug/DLQ channels restricted and auditable. A model-produced fact about a prediction must not be accepted as a business fact about an approved purchase, permission or real-world outcome.
16. Observability and operational ownership#
Monitor product-level outcomes as well as transport activity. Trace a logical task across asynchronous boundaries using correlation and causation references; use standardized trace context for observability where appropriate, including span links for fan-in and batch processing. Keep business task identity durable independent of trace sampling.
| Metric | What it diagnoses |
|---|---|
| Outbox oldest unpublished age and count | Producer publication gap |
| Consumer lag by partition and event time | Freshness and recovery pressure |
| Schema/semantic rejection by producer and consumer release | Compatibility incidents |
| Duplicate and conflicting identity counts | Retry load or integrity issue |
| Desired revision versus active artifact/index revision | Stale AI results |
| Dependency manifest completion and timeout age | Product workflow status |
| Dead-letter age, reasons and reconciliation | Unresolved work, not just transport errors |
| Actual inference attempts and committed artifact counts | Wasted compute and deduplication efficacy |
| Authorization denials and scope mismatches | Trust-boundary problems |
| Task-level valid completion and cost | Consumer-visible success |
Define measurement denominators: one event may create many deliveries, one delivery may produce no effect, one job may create multiple artifact versions. Distinguish a published event, broker-acknowledged delivery, local committed reaction, active derived result and completed product task. Alert the appropriate owner on contract failure, missing required dependency or freshness SLO violation. Define cross-team incident escalation and reconciliation procedures. A consumer may remain independently deployable but cannot be independently unaccountable.
17. Production acceptance and independent release checklist#
Before enabling the integration, specify event ownership, schema/type, semantic target, entity/operation identity, ordering requirements, maximum accepted age, supported versions and retention. Record which side effects are permitted on initial delivery, duplicate and replay.
Test old writers with new readers and new writers with every supported old reader; include retained historical messages and unknown enum/field behavior. Use golden fixtures for units, event meaning, model provenance, prediction validity, embedding compatibility and authorized artifact references. Check malformed and oversized payloads, duplicate source/id with changed contents, distinct event IDs for the same logical effect, out-of-order complete snapshots and gaps in delta streams. Test same-revision conflicting inputs, deletion and revocation, and stale worker activation.
Inject failures before and after each local commit, publication, broker acknowledgment and consumer acknowledgment. Rehearse relay replay and consumer rebuilding into a new projection, verify retention and contiguous checkpoints, simulate unsupported schema quarantine and redrive, and validate workflow fan-in with missing/late/duplicated results. Ensure shadow runs and replay cannot inadvertently execute protected effects. The local fixture above tests only a subset of these conditions; real deployment needs broker-specific and end-to-end workload evidence.
For a new model release, verify the contract's semantic and statistical quality independently of schema conformance. For a new embedding generation, validate the intended retrieval space and prevent incompatible generations becoming active together. For contract retirement, verify all supported consumers, replay horizons and rollback arrangements. Do not declare compatibility simply because two payloads deserialize successfully.
18. Interview-ready answer#
I would start by defining bounded capabilities and authoritative owners, then identify the committed domain facts that other services need to consume. I would use a standardized event envelope with immutable source/id, event type, exact schema, subject/revision, tenant scope, correlation and causation, plus domain-specific AI artifact and model provenance. I would distinguish commands from facts, and keep generated predictions separate from business authority.
I would version schemas and semantics independently of builds and models, maintain a compatibility registry and golden contract fixtures, and use reader-first evolution or explicitly coordinated major versions. I would compose independent projections by choreography and use a durable orchestrator when a user task has required dependencies and completion semantics.
I would publish through a local transactional outbox, make consumers idempotent through a transactional inbox and domain revision/operation checks, and acknowledge only after the required durable reaction. I would specify ordering per entity and distinguish complete-state coalescing from contiguous delta processing. Replay would preserve historical provenance and avoid unauthorized or duplicated effects. I would use bounded retries, controlled dead-letter recovery, resource-level authorization and event/task telemetry. Finally I would test the compatible release matrix, replay, late AI results, fault boundaries and actual product outcomes. Independent deployment is achievable when ownership and meaning are stable and testable, not merely because teams communicate through a broker.
References and research transparency#
The authorized offline research exception was applied. References identify established specifications, documentation and architectural guidance. Current link availability, contents and the Supabase changelog were not live-verified. Four meaningful Mermaid diagrams use standard triple-backtick fences and were structurally reviewed; parser execution and live frontend rendering were not verified. The exact Python example was executed locally on Python 3.13.5 with 19 checks passing, including an injected local transactional failure. No real broker, schema registry, CDC pipeline, multi-process concurrency, AI model, authentication system or production workload was exercised. The JSON envelopes are illustrative and were not schema-validated. All numerical scenarios are hypothetical.
- CNCF CloudEvents — Specification v1.0.2
- AsyncAPI — Specification 3.0.0
- Apache Avro — Specification
- Protocol Buffers — Updating a message type
- JSON Schema — Draft 2020-12
- Apache Kafka — Documentation
- Confluent — Schema evolution and compatibility
- Chris Richardson — Transactional outbox pattern
- PostgreSQL — Transaction isolation
- SQLite — Transaction documentation
- W3C — Trace Context
- W3C — PROV-DM: The PROV Data Model
- NIST SP 800-207 — Zero Trust Architecture
- Google SRE — Addressing Cascading Failures
References
- 1.CNCF CloudEvents — Specification v1.0.2github.com
- 2.AsyncAPI — Specification 3.0.0asyncapi.com
- 3.Apache Avro — Specificationavro.apache.org
- 4.Protocol Buffers — Updating a message typeprotobuf.dev
- 5.JSON Schema — Draft 2020-12json-schema.org
- 6.Apache Kafka — Documentationkafka.apache.org
- 7.Confluent — Schema evolution and compatibilitydocs.confluent.io
- 8.Chris Richardson — Transactional outbox patternmicroservices.io
- 9.PostgreSQL — Transaction isolationpostgresql.org
- 10.SQLite — Transaction documentationsqlite.org
- 11.W3C — Trace Contextw3.org
- 12.
- 13.
- 14.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython