AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals
Choosing Synchronous, Asynchronous, Batch, and Streaming AI Execution Architectures
Question 17 of 47 · Updated
On this page
- 1. Separate the architectural axes before choosing a mode
- 2. Derive the choice from the actual user task
- 3. Synchronous request-response: bounded coupling
- 4. Asynchronous job processing: durable intent
- 5. Scheduled or triggered batch: one bounded publication
- 6. Event-stream processing: continuous change rather than a job per event
- 7. Token and progress streaming: delivery, not the execution mode
- 8. Delivery semantics, ordering and the actual commitment boundary
- 9. Backpressure and cancellation across the product
- 10. One practical hybrid product: research and reporting workspace
- 11. Moving between modes without losing intent
- 12. Tested implementation: idempotent submission and terminal-state commitment
- 13. Cost and latency trade-offs by consumer promise
- 14. Reliability, security and versioned result contracts
- 15. Validation and production release
- 16. Decision checklist and interview-ready answer
- References and research transparency
Select an execution architecture from the consumer's required response contract, the shape of the input, the required freshness of the result, and the failure and consistency semantics. Use synchronous request-response when the caller needs a bounded result now; asynchronous jobs when a specific submitted task must survive the caller's connection; scheduled or triggered batch processing for bounded collections of records; and event-stream processing for continuing changes that must be processed with low delay. Stream generated tokens or progress to a client when incremental delivery improves the experience. These choices are composable rather than mutually exclusive.
Original curriculum question: How would you choose between synchronous, asynchronous, batch and streaming AI architectures for different workloads?
Module 01 — Architecture fundamentals | ASD-004. ASD-001 selects the architecture family, ASD-002 defines measurable acceptance criteria, and ASD-003 sizes resources. This article specifies how work is accepted, observed, completed, resumed and delivered across a whole AI product. The MLOps lessons on online versus batch inference, asynchronous prediction APIs, streaming inference and day-2 operational differences are prerequisites; their model-serving and stream-engine details are not the focus here. The distinctive learning objective is selecting and combining *consumer-visible execution contracts*, including durable jobs with optional streaming subscriptions, transitions between modes, versioned result publication and workflow completion semantics. Framework-specific sync/async agent SDKs, implementation of bulk inference job platforms (ASD-019), cross-service deadline propagation (ASD-060) and resumable human-approval orchestration (ASD-046) belong in later or specialist lessons.
All scenarios, service times, workloads and prices are synthetic teaching assumptions, not vendor quotations or observed production measurements.
1. Separate the architectural axes before choosing a mode#
The words synchronous, asynchronous, batch and streaming are often used as if they describe four incompatible technologies. They actually describe different properties.
Caller coupling: In a synchronous API, the caller waits for a response to the request. In an asynchronous job API, acceptance and completion are separate events. This is independent of whether the server implementation uses threads, nonblocking I/O, an event loop or a queue internally. An async Python endpoint may still expose a synchronous request-response contract.
Input boundedness: A batch consumes a defined finite collection, such as a committed snapshot or a closed time window. An event stream is logically unbounded: new events may continue to arrive indefinitely. A scheduled job can launch because a new dataset was committed rather than only because a clock fired.
Delivery granularity: A result may be delivered as a single response, a sequence of partial updates, or a durable artifact. Token streaming is incremental transport of model output to a consumer; it is not synonymous with continuous event processing. A streaming HTTP response can still be coupled to the lifetime of a request.
Durability: Work may disappear with a failed process or survive a connection loss and restart. A queue alone does not establish end-to-end durability; acceptance, worker state, result persistence, and external effects all need explicit semantics.
Freshness: Online work can use current inputs but is not inherently fresh if its sources are stale. A batch result can be appropriate even when it is hours old if the consumer permits that age. Stream processing can be running but produce stale results due to lag or source delay.
| Architecture | What the consumer expects | Typical input | Completion contract |
|---|---|---|---|
| Synchronous | Final response now, within a deadline | One logical request | Response or explicit error |
| Asynchronous job | Acknowledgment now, result later | One bounded submitted job | Durable terminal status and result |
| Batch | Complete dataset or artifact by a deadline | Finite snapshot or partition set | Versioned committed output |
| Event stream | Continuous updates with bounded freshness | Unbounded events | Per-event or windowed outputs, with correction policy |
| Token/progress stream | Incremental display during work | Usually one task or a subscription | Provisional chunks and final completion signal |
A single product can use all five. A synchronous endpoint can microbatch model calls internally. A durable asynchronous job can send progress using server-sent events. A stream processor can use bounded microbatches for inference. A scheduled batch can populate an online serving store.
2. Derive the choice from the actual user task#
Start with the consumer's deadline and ability to continue without a result. Ask:
- Does the next user action require a final result immediately?
- Can work continue after a client disconnect or device restart?
- Is the input finite, or does it continue to arrive indefinitely?
- Does the consumer need a complete snapshot or incremental updates?
- Is the result allowed to be provisional, and can it be corrected?
- Are actions read-only, reversible or externally consequential?
- What result age, cancellation behavior, failure recovery and cost are acceptable?
Then establish the user-visible promise independently of the implementation. For an order lookup, a client may need a response in 300 ms and can show an explicit unavailable state otherwise. For a long report, a client may prefer a durable job ID in 200 ms with a result within 15 minutes. For a nightly compliance report, consumers may require one verified complete snapshot at a specific cutoff. For live equipment alerts, a low event-to-alert delay and explicit late-event semantics matter more than an individual HTTP response.
The following decision diagram is a guide, not a rigid taxonomy. Several branches can apply to one workflow.
Choose the simplest implementation that satisfies the contract. Do not introduce an always-running broker for a small scheduled calculation, or force a twenty-minute document job into a long-lived request merely because the HTTP framework permits it.
3. Synchronous request-response: bounded coupling#
The caller sends an operation and waits for the final response or a defined failure. A synchronous design is appropriate for interactive tasks whose useful result can be returned within the required deadline. Examples are exact order lookup, checkout ETA, a compact prediction and a short eligibility explanation based on verified facts.
A typical path is authenticated gateway, validation, current feature or evidence retrieval, inference, result validation and response. The server may internally run independent reads concurrently. That does not change the external contract.
Use an absolute deadline or a consistently propagated remaining time budget. Retries consume part of the original time budget rather than receive unlimited new deadlines. Bound request size, concurrency and work per user. If a dependency is down, use an explicitly permitted baseline or return an honest unavailable result; do not invent a prediction.
A response timeout does not establish whether a state-changing action occurred. A client may have lost the response after the server committed the operation. For any operation with side effects, use appropriate idempotency, status lookup and reconciliation rather than blind retry. Even a read-only inference call may incur duplicate billable model work when retried.
Distinguish transport completion from semantic success. HTTP 200 does not mean a generated claim is true. The consumer's acceptance contract must check the result's content, validity, provenance and freshness as appropriate.
A synchronous service should measure offered requests, successful valid responses, deadline misses, rejection rate and tail latency. Avoid treating only successful completed requests as the denominator. The resource sizing method is already covered in ASD-003; the choice here is whether the result belongs in the live interaction at all.
4. Asynchronous job processing: durable intent#
An asynchronous job is a specific submitted unit of work with an identity and lifecycle independent of the caller's current connection. Examples include processing a large PDF collection, producing a research artifact or running an approved evaluation suite.
A typical API contract:
POST /reports
authenticated principal and tenant
Idempotency-Key: client-generated logical submission ID
validated request body
-> 202 Accepted, job identifier, status URL
GET /reports/{job_id}
-> queued | running | succeeded | failed | cancelled | expired
-> progress information when available
-> result reference when authorized and complete
POST /reports/{job_id}/cancel
-> accepted cancellation request or current terminal statusHTTP 202 means the request has been accepted for processing, not that processing completed successfully. The application must define its own durable acceptance guarantee. A production API should return its durable-acceptance acknowledgment only once the job record and necessary dispatch information have been persisted consistently. Returning a job ID before a volatile enqueue succeeds creates a lost-job failure.
For a small deployment, a transactional job table with workers claiming jobs may suffice. For a distributed deployment, store the job and a transactional outbox record in the same database transaction, then relay the outbox to a queue. Duplicate relay deliveries remain possible; a consumer must tolerate them. Treat the queue as a dispatch mechanism and the durable job record as the source of truth for client-visible status.
The sequence is conceptual: the database does not autonomously send queue messages; a relay process performs the indicated step. If the worker crashes after committing but before acknowledging, delivery can repeat. The durable job state and stable operation identity must prevent an unintended second publication. If an external action occurred outside the transaction, reconciliation is still needed.
Use a lease or ownership epoch to avoid a stalled worker committing after its replacement starts. Worker heartbeats and expiry alone do not prevent stale writes; enforce a fencing token or version check at the committing resource. Pin the job's input snapshot, model/prompt versions, allowed tools and policy context, then recheck current authority for sensitive operations.
Cancellation is a separate intent. A queued job can often be cancelled directly; a running job may require cooperative cleanup and a cancellation-requested state. A committed external action is not undone merely because the client cancels. Define whether cancellation can win before a result is published, what happens after the commitment point, and which compensations are authorized.
The product can report accepted-job latency, queue age, time to terminal state, successful-job fraction, expiry, cancellation responsiveness and artifact delivery correctness. Do not measure only queue-consumption throughput.
5. Scheduled or triggered batch: one bounded publication#
Batch is defined by the bounded work set and consumer contract, not by whether execution uses GPUs, parallel jobs or a queue. A batch might run at a daily cutoff, after a source snapshot commits or after an operator requests a controlled backfill.
A consumer often needs a complete coherent dataset rather than independently successful records. Define the logical interval, expected IDs or partitions, source snapshot, pinned model and feature versions, output schema, permitted missing-record policy, validation checks and publication deadline.
A batch run can persist staged partitions separately and then atomically publish a manifest identifying the verified complete generation. The consumer reads the manifest, not whichever file happens to be newest. If a required partition fails, retry that partition or mark the entire run incomplete according to the explicit contract. Partial results can be useful only if the product explicitly labels and permits them; never silently present an incomplete dataset as complete.
A repeated logical run should use stable run and partition identities. If the business needs a corrected snapshot, publish a new revision with lineage instead of silently replacing a previously consumed version. Backfills must not accidentally overwrite newer effective state in an online application.
Example: a merchant needs 240,000 approved catalog descriptions scored by the beginning of a merchandising review. At a hypothetical aggregate 200 records/s, pure processing takes 1,200 seconds (20 minutes); add ingestion, validation, publication and retry allowance. The decisive contract is a complete verified snapshot by the review deadline. An individual customer's connection is irrelevant. Per-record latency may be secondary, but per-record data correctness and completeness remain essential.
The MLOps batch curriculum covers implementation, scheduling and deployment in depth. Here the central decision is whether consumers need one consistent finite collection and how its publication boundary differs from independent submitted jobs.
6. Event-stream processing: continuous change rather than a job per event#
An event stream represents an ongoing sequence of domain changes, such as order transitions, sensor readings or document update events. Consumers may need a new prediction or updated feature whenever relevant state changes. Unlike a long job, there is no global final success state for the entire stream.
An event should carry a stable event ID, authorized entity or partition key, event time, schema version, source identity and appropriate ordering/version information. Do not assume an event's timestamp is trustworthy without checking the source's clock and contract.
Event time describes when the underlying event occurred; processing time describes when the system handles it. Out-of-order arrivals are ordinary. For instance, a document revision 12 may reach one worker before delayed revision 11. If the business contract is latest-version visibility, a conditional update must prevent revision 11 from overwriting revision 12. For historical windowed analytics, the older event may still need inclusion in the appropriate event-time window. These are distinct consistency rules.
A watermark estimates event-time progress, not proof that no earlier event will arrive. Choose the permitted lateness and correction strategy based on consumer needs. A low-latency alert can be provisional and later revised; a final accounting snapshot may require a longer completeness window.
The checkpoint arrow denotes recovery, not a second normal event input. State restoration must be coherent with source offsets and sink semantics. A pinned model version and point-in-time feature dependencies may be required for meaningful replay. When a model version changes, establish an explicit processing epoch or version-aware update contract.
Event streaming is justified when value decays quickly after changes or when maintaining incremental state avoids repeated full scans. It introduces always-on infrastructure, retention, state migration, ordering, lag and recovery requirements. A small hourly report may not need this complexity. Detailed window operators, partition scaling and streaming-model deployment are covered in the existing MLOps lessons and upcoming ASD-021; do not replicate an entire stream-engine tutorial here.
7. Token and progress streaming: delivery, not the execution mode#
A language-model response can be emitted incrementally. A long-running job can send status updates without emitting generated text. Both are streaming from the client's point of view, but neither implies that the input is an unbounded event stream.
Server-sent events (SSE) provide a server-to-client event stream over HTTP; a client may submit a separate authenticated request to start work. The EventSource interface supports reconnection and event IDs under its protocol semantics, but the application must actually retain replayable events if it promises resume. Native browser EventSource is not a general POST-with-body client. Other HTTP streaming interfaces can accept POST requests, but application framing and reconnection behavior must be designed explicitly.
WebSocket provides bidirectional communication, useful when an interactive application must receive interruption messages while sending outputs, or when audio flows both ways. A socket is not a durable job store. Reconnecting does not automatically restore missed state or establish message deduplication.
Consider the following message envelope, which is illustrative application data rather than a complete protocol specification:
JSON{ "job_id": "report-123", "sequence": 42, "type": "progress", "phase": "validating_sources", "provisional": true }
A completion event should identify the committed result and its version. A token fragment should never be interpreted as a successfully validated final response. Clients can disconnect after seeing a partial answer. Decide whether work should be cancelled on disconnect or remain durable and reconnectable; neither behavior is universally correct.
If incremental text can contain unsupported claims or sensitive content, validate or buffer appropriate units before display. A final validator cannot retract information already exposed to the user. Some tasks should stream only non-sensitive progress and deliver the verified artifact atomically. This is particularly important when outputs carry high consequences or require independent approval.
Measure time to first meaningful update, inter-update gaps, completion latency, disconnects, reconnects, replay correctness and cost of abandoned generation. Avoid optimizing first-token latency at the expense of final useful completion.
8. Delivery semantics, ordering and the actual commitment boundary#
A queue or event broker may advertise a particular delivery guarantee within a specific boundary. Translate it into the business effect you need:
| Semantics | Implication | Design requirement |
|---|---|---|
| At most once | Work may be lost under failure, but no retry delivery within the stated mechanism | Only where loss is explicitly acceptable or independently repaired |
| At least once | Retry or replay may deliver duplicates | Stable event identity and idempotent or deduplicated effects |
| Exactly-once processing/state within supported boundary | Compatible source, state and sink coordination can make replay logically consistent | Verify the specific framework/configuration and participating systems |
| Exactly-once external business effect | External side effect occurs once per logical intent | End-to-end coordination, destination idempotency or reconciliation |
A database transaction can atomically record a job's success and its result reference when they share the same database boundary. It does not automatically include an external payment service, model provider or email endpoint. A transactional outbox atomically records *intent*, not delivery to every external destination.
For example, a report worker writes an artifact under an immutable generation ID, then commits a database pointer to that artifact. A repeated write may incur duplicate compute or storage, but an appropriately fenced conditional database update can prevent multiple terminal publications for one logical job. If a worker crashes between object upload and database commitment, unreferenced objects may remain; cleanup must be safe and version-aware.
Ordering is similarly scoped. Per-partition ordering in a log does not imply a total order across all entities. Retrying a failed message or routing work through parallel consumers may change processing completion order. A client-facing stream with sequence numbers must define gaps, duplicates and replay. Use entity-level version checks when business state must move forward monotonically, and reserve global coordination for the few invariants that truly require it.
9. Backpressure and cancellation across the product#
Backpressure means downstream processing cannot accept work as quickly as upstream produces it. The response depends on the execution contract.
For synchronous requests, use bounded concurrency, admission control and deadlines. For asynchronous jobs, use per-tenant quotas, maximum queue age, scheduled priorities and admission estimates; do not promise impossible deadlines. For batch, limit concurrent partitions and avoid saturating source or sink throughput. For streams, control consumer concurrency, monitor retained backlog and slow producers where supported. Dropping events is allowed only under an explicit business policy, not as an invisible optimization.
For illustration, imagine an asynchronous report pool with four workers. Each finishes an average of one job per minute under the assumed mix, so aggregate capacity is four jobs/minute. A burst of eight arrivals/minute for five minutes creates approximately 20 queued jobs from an empty backlog if all are admitted and service rates are constant. With later arrival rate two/minute, net drain is two/minute and backlog takes about ten additional minutes to clear. The latest queued job may violate its promised deadline. The fluid calculation is an approximation and ignores service-time variability, worker failures and retry overhead. ASD-003 supplies the general sizing method; here the implication is choosing admission and user-visible queue promises appropriately.
Cancellation semantics vary:
- A disconnected synchronous read may be aborted if no useful work remains; propagate cancellation to dependencies that support it.
- A durable job should usually continue after accidental disconnect unless the user or contract explicitly cancels it.
- A cancelled running job must stop at safe boundaries, fence stale commits and report the actual outcome.
- Cancelling a progress subscription does not necessarily cancel its underlying job.
- A batch cancellation requires a defined output visibility rule for staged results.
- A stream shutdown is a controlled processing lifecycle event, not a cancellation of every domain event in the retained log.
Cancellation is not compensation. It cannot erase a committed action or undo disclosure. Require authorized compensation and reconciliation where supported; otherwise accurately report the action's actual status.
10. One practical hybrid product: research and reporting workspace#
Imagine an enterprise research workspace with four requirements:
| User or system task | Illustrative requirement | Architecture |
|---|---|---|
| Look up an authorized document or current report status | Answer within 300 ms | Synchronous API |
| Ask a short grounded question | Useful final answer within 5 s; optional safe partial text | Synchronous or bounded streaming response |
| Generate a large cited report | Durable acknowledgment within 200 ms; validated artifact within 15 min | Asynchronous job plus progress subscription |
| Refresh search index after document changes | Changes reflected within 60 s for eligible events | Event stream and incremental indexing |
| Produce the weekly department report | Complete consistent snapshot by Monday cutoff | Scheduled batch |
All deadlines are illustrative design requirements, not measured results.
The diagram deliberately separates progress from the artifact. The job is authoritative even if the connection disappears. The short-answer path does not wait behind large report jobs. A report can cite a pinned source snapshot while the index continues updating; do not mix revisions without explicit policy. Current access authorization still applies when a saved artifact is opened.
The hybrid needs shared contracts, not merely a collection of queues. Define logical task IDs, immutable artifact versions, data/policy provenance, compatible schemas, and ownership for all modes. A report accepted yesterday cannot automatically use revoked credentials today. A stream index refresh cannot expose a newly restricted document to either synchronous or async consumers.
11. Moving between modes without losing intent#
A product often begins synchronously and adds durable execution when task lengths vary. Do not quietly change a request-response API into an unreliable background task when it is near timeout. Negotiate the contract before work begins or establish an explicit, durable handoff.
A client could send a request with a preference for a fast answer and a permitted asynchronous alternative. The server validates the task, decides whether the bounded fast path is feasible, then either returns the result or creates a durable job and returns its status reference. The same logical task key should identify both paths where the product promises one intent. If work already started, establish a commitment point and transfer ownership before another worker resumes it. An aborted synchronous attempt must not concurrently publish a competing result.
Likewise, transitioning from batch to event-driven updates requires an initial committed snapshot and a defined source-position boundary. Start from a consistent cutover position, replay subsequent events, verify the consumer-visible result, then promote the new mode. If the snapshot and stream offsets do not align, records may be missed or applied twice. If events have been compacted or expired, a fresh full snapshot may be required.
Moving an event-driven system back to batch for cost reasons may be reasonable when the freshness requirement changes, but must be an explicit consumer contract revision. A nightly rebuild cannot silently replace a previously promised one-minute freshness SLO. A synchronous lookup may still serve batch-generated artifacts as long as their as-of times and expiry are clearly enforced.
12. Tested implementation: idempotent submission and terminal-state commitment#
The following standard-library Python example demonstrates a narrow contract shared by an asynchronous job API, a polling UI and an optional progress subscription. It implements tenant-scoped logical submission keys and conditional terminal-state writes using SQLite on one local connection. It has no broker, network, real model call, external effect, lease, persistent job recovery or concurrent workers. It is an executable specification of the sequential state transitions, not a production job service.
PYTHONimport sqlite3 def submit(db, tenant, key, payload): with db: db.execute('INSERT INTO jobs VALUES (?, ?, ?, ?, NULL)', (tenant, key, payload, 'QUEUED')) if not db.execute( 'SELECT 1 FROM jobs WHERE tenant=? AND k=?', (tenant, key)).fetchone() else None row = db.execute('SELECT payload, state FROM jobs WHERE tenant=? AND k=?', (tenant, key)).fetchone() if row[0] != payload: raise ValueError('idempotency conflict') return row[1] def finish(db, tenant, key, result): with db: return db.execute("UPDATE jobs SET state='SUCCEEDED', result=? " "WHERE tenant=? AND k=? AND state='QUEUED'", (result, tenant, key)).rowcount == 1 def cancel(db, tenant, key): with db: return db.execute("UPDATE jobs SET state='CANCELLED' " "WHERE tenant=? AND k=? AND state='QUEUED'", (tenant, key)).rowcount == 1 def main(): db = sqlite3.connect(':memory:') db.execute('CREATE TABLE jobs (tenant TEXT, k TEXT, payload TEXT, ' 'state TEXT, result TEXT, PRIMARY KEY(tenant,k))') assert submit(db, 'a', '1', 'report') == 'QUEUED' assert submit(db, 'a', '1', 'report') == 'QUEUED' assert db.execute('SELECT count(*) FROM jobs').fetchone()[0] == 1 try: submit(db, 'a', '1', 'other') except ValueError: pass else: raise AssertionError('conflicting payload accepted') assert submit(db, 'b', '1', 'other') == 'QUEUED' assert finish(db, 'a', '1', 'first') assert not finish(db, 'a', '1', 'second') assert not cancel(db, 'a', '1') assert submit(db, 'a', '1', 'report') == 'SUCCEEDED' assert cancel(db, 'b', '1') assert not finish(db, 'b', '1', 'late') assert submit(db, 'b', '1', 'other') == 'CANCELLED' assert db.execute("SELECT result FROM jobs WHERE tenant='a'").fetchone()[0] == 'first' assert not finish(db, 'c', '1', 'wrong tenant') db.close() print('14 checks passed') if __name__ == '__main__': main()
Observed execution with Python 3.13.5:
14 checks passedThirteen direct assertions and one exception check establish that a repeated same-payload submission preserves one job, a reused key with different payload is rejected, different tenant keys remain independent, a successful result cannot be overwritten or cancelled by a subsequent call, cancellation prevents later terminal success, and an unrelated tenant cannot finish another tenant's job.
The example compares the exact payload string; a real API defines a canonical request fingerprint, operation type and idempotency-key retention window. The tenant argument must come from authenticated server-side context, not an untrusted client-provided tenant name. The primary key is a database invariant, but the preliminary SELECT followed by INSERT in this toy implementation is not a concurrency-safe submit protocol across multiple connections. A production implementation needs a conflict-safe insert or equivalent atomic pattern and conflict handling, together with tested transaction isolation. In-memory SQLite loses its contents when the connection closes. Use durable storage, leases, outbox dispatch, real authorization, result integrity, cleanup and fault-injection tests in production.
The conditional UPDATE ensures only a job in QUEUED can be marked successful or cancelled in this simplified sequential state machine. RUNNING, CANCEL_REQUESTED and worker ownership are deliberately omitted. A real worker must commit only from the authorized running state with a valid lease/version, and reconcile external side effects that cannot participate in the database transaction.
13. Cost and latency trade-offs by consumer promise#
Do not compare architectures only by their per-inference price. They serve different promises and therefore have different cost drivers.
| Mode | Major resource costs | Main latency commitment |
|---|---|---|
| Synchronous | Warm replicas, burst headroom, dependencies | Per-request completion |
| Durable jobs | Queue, job/result store, workers, retries, artifact delivery | Acceptance plus queue-to-terminal deadline |
| Batch | Windowed compute, snapshot IO, validation, temporary outputs | Complete publication by deadline |
| Event stream | Continuous broker/processor, state and checkpoint storage | Event-to-visible-result freshness |
| Token/progress subscription | Open connections, buffers, replay history, abandoned work | First meaningful update and final completion |
For a fictional report workload of 120 jobs/day requiring one worker-minute each, the ideal compute work is two worker-hours/day. Four workers running continuously would reserve 96 worker-hours/day. A job-triggered or shared pool might use much less paid idle time, but startup, concurrency, burst deadlines, retries and minimum capacity determine feasibility. At an invented $1 per worker-hour, the two-hour ideal compute lower bound is $2/day versus $96/day for four continuously billed workers, before other costs. These are not actual prices, measured savings or equivalent performance guarantees.
An event-stream solution might avoid reprocessing a large mostly unchanged snapshot, but it pays for continuous infrastructure and recovery state. A batch can be cheaper for low-freshness use cases, yet repeatedly recomputing expensive unchanged results can cost more than incremental updates. Model caching or batching may help in any mode when freshness, authorization and quality permit.
Compare cost per completed correct task, per complete snapshot or per timely event result as appropriate. Include failures, duplicated compute, human review and consumer-side reconciliation. Do not label a faster acknowledgment as lower task-completion latency.
14. Reliability, security and versioned result contracts#
Every execution mode must define the identity and authority of its work, the result's validity interval, and the outcome when dependencies fail.
For asynchronous work, persist the submitting principal, allowed purpose and task context securely. Recheck current access at execution and result retrieval, and before consequential effects. The user might lose access while a report is in the queue. Prevent replay from resurrecting revoked authorization. Do not place secrets or unrestricted personal data in broker payloads, progress events or logs. Prefer references with access checks and short-lived credentials.
For batch and stream outputs, include source snapshot or event position, model version, schema version, evaluation or policy version, generation time and effective data time. Consumers should reject incompatible schemas or expired results. For interactive outputs, carry sufficient provenance to explain freshness and trace failures.
Common incidents and correct response:
| Failure | Expected handling |
|---|---|
| Client times out after acceptance | Resolve using logical key and durable status; do not blindly create duplicate work |
| Worker crashes after result commit | Retry delivery safely; preserve committed terminal result |
| Worker loses lease | Fence its subsequent writes |
| Batch partition fails | Keep incomplete generation staged; retry or report incomplete |
| Late event arrives | Apply version/late-data policy; do not overwrite newer state blindly |
| Event source unavailable | Expose freshness loss, stop unsupported updates and recover from a coherent position |
| Client disconnects mid-generation | Apply declared cancellation or durable continuation behavior |
| Authorization revoked mid-job | Stop unauthorized access and suppress protected output |
| Partial output already displayed | Report incomplete result; do not imply final validation or pretend disclosure can be undone |
A checkpoint is not simply a saved offset. For stateful event processing it must restore corresponding state and source position; for a batch it may be a verified partition receipt tied to the snapshot and model version; for a long job it can be an intermediate artifact and durable phase record. Checkpoint only at a boundary where replay has defined semantics. Training optimizer checkpoints are a separate concern.
15. Validation and production release#
Carry the measurement contracts from ASD-002 into mode-specific tests. Test happy paths and failure boundaries, not only inference accuracy.
For a synchronous API, replay representative traffic and measure deadline success including error responses, timeouts and validation. For async jobs, inject duplicate submissions, broker redelivery, worker crashes before and after terminal commit, stale lease writes, cancellation races and unauthorized status requests. For batch, inject missing partitions and late inputs; confirm consumers cannot see a falsely complete manifest. For stream processing, replay out-of-order and duplicate events, restore checkpoints, test incompatible state schemas and verify corrections. For token/progress transport, disconnect and reconnect at several sequence boundaries, test slow receivers and measure cancellation propagation.
For hybrid integration, verify the same logical task cannot produce competing committed results when changing execution mode. Verify batch and stream cutovers without event gaps, correct as-of versions in generated reports, consistent authorization across result paths, and isolated background load under peak interactive traffic.
Define owner and stop rules for each failure mode. An apparently healthy worker, successful socket connection or completed batch process does not demonstrate useful consumer-visible outcomes. Observe the relevant task-level SLO and evidence of committed result correctness.
16. Decision checklist and interview-ready answer#
In an interview, I would begin by identifying the consumer's deadline, whether it needs a final result in the current interaction, whether the work must survive disconnection, whether input is bounded, and whether results must be delivered as complete snapshots or incremental updates.
I would use synchronous request-response for bounded interactive work, durable asynchronous jobs for long-running user-submitted tasks, batch for complete bounded collections with publication deadlines, and event-stream processing when continuing changes require low freshness lag. Token or progress streaming is an orthogonal delivery choice. I would combine modes for a product with different tasks rather than choose one globally.
I would specify stable task and event identities, acceptance versus completion, authorization, result versions, retry and idempotency contracts, ordering, cancellation and checkpoint boundaries. I would use bounded queues and explicit admission policies, avoid claiming end-to-end exactly-once effects from a broker alone, and validate behavior across crashes, retries, reconnects and mode transitions. Finally, I would compare measured consumer outcomes and total cost under the relevant latency, freshness and reliability contract.
The key principle is that the execution architecture must preserve what the product promises the consumer, not simply optimize how the model runs.
References and research transparency#
The authorized offline research exception was applied. The references below identify established protocol specifications, official documentation and primary systems research. Current URL availability and contents, and the current Supabase changelog, could not be live-verified. Four Mermaid diagrams use standard triple-backtick fences and were structurally reviewed; parser execution and live frontend rendering were not verified. The SQLite/Python example was executed locally with Python 3.13.5 and 14 checks passed. Tests use a single in-memory SQLite connection; concurrency, crash recovery, real brokers, network streaming, GPU performance and production integrations were not tested. All workload and cost examples are illustrative.
- IETF RFC 9110 — HTTP Semantics (202 Accepted, idempotent methods)
- WHATWG HTML Living Standard — Server-sent events
- IETF RFC 6455 — The WebSocket Protocol
- Apache Kafka — Documentation
- Apache Flink — Time and Watermarks
- Apache Flink — Stateful Stream Processing
- Akidau et al. — The Dataflow Model
- Google SRE — Addressing Cascading Failures
- Amazon Builders' Library — Making retries safe with idempotent APIs
- PostgreSQL — Transactions
- SQLite — Transaction documentation
- Yu et al. — Orca: A Distributed Serving System for Transformer-Based Generative Models
References
- 1.
- 2.WHATWG HTML Living Standard — Server-sent eventshtml.spec.whatwg.org
- 3.IETF RFC 6455 — The WebSocket Protocolrfc-editor.org
- 4.Apache Kafka — Documentationkafka.apache.org
- 5.Apache Flink — Time and Watermarksnightlies.apache.org
- 6.Apache Flink — Stateful Stream Processingnightlies.apache.org
- 7.
- 8.
- 9.
- 10.PostgreSQL — Transactionspostgresql.org
- 11.SQLite — Transaction documentationsqlite.org
- 12.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython