AI service integration patterns
Choose an integration contract
An AI deployment connects a model or deterministic substitute to an application through a controlled interface. Imagine a shop that labels product descriptions overnight. A scheduled batch job reads a versioned input snapshot, processes bounded chunks, and stores results with a run ID. A synchronous HTTP REST endpoint fits an interactive request with a small deadline; gRPC offers typed RPC contracts and unary or streaming methods. A queue fits work that can finish later: accept a job, return an identifier, process it in a worker, and provide status through a separately authorized endpoint. A streaming API sends incremental chunks before completion; consumers must distinguish partial output from a final validated result. Local inference keeps computation on a host, edge inference runs near the data or device, and hosted inference delegates computation to a provider. These are placement choices, not guarantees of speed, privacy or availability.
Validate the request before dispatch
For a fictional catalog, accept only item and text fields, reject blank descriptions and apply an 80-character cap. The authenticated tenant and its allowed item set are independent trusted inputs. The example rejects extra fields and does not trust a tenant identifier from the request. The character cap is not a byte or token limit; a real HTTP service also limits request bytes before parsing, validates encoding and schema, and checks the tokenizer budget before inference. The three calls demonstrate accepted, denied and oversized requests. A real endpoint would map these internal outcomes to documented transport statuses and avoid revealing whether an unauthorized resource exists. The accepted outcome permits dispatch only; it is not a completed inference.
def admit(request, tenant, allowed_items, max_chars=80): # tenant and allowed_items come from trusted, authenticated context. if type(request) is not dict or set(request) != {"item", "text"}: return "invalid" item, text = request["item"], request["text"] if type(item) is not str or type(text) is not str or not text.strip(): return "invalid" if len(text) > max_chars: return "too_large" if (tenant, item) not in allowed_items: return "denied" return "accepted"
acl = {("shop-a", "p1"), ("shop-b", "p2")}print(admit({"item": "p1", "text": "blue mug"}, "shop-a", acl))print(admit({"item": "p2", "text": "blue mug"}, "shop-a", acl))print(admit({"item": "p1", "text": "x"*81}, "shop-a", acl))Design the queue and response lifecycle
A synchronous response should carry the contract version, request ID, status, validated result or error, and safe metadata. For a queued request use accepted, running, completed, failed, expired or cancelled states, scoped to tenant and job ID. Store an idempotency key with the tenant and canonical request identity; repeated delivery must not duplicate the committed effect. A conflicting payload for the same key is rejected. Standard SQS delivery can duplicate messages [1]; a visibility timeout alone does not provide exactly-once processing. Acknowledge only after durable result publication; use atomic state transitions or transactional outbox patterns where appropriate. Bound queue depth, attempts, worker concurrency, payload size and retention; apply backpressure or reject new work rather than allow unbounded growth. Poison jobs need quarantine and review. For streaming, define chunk ordering, termination and error events, limit output, and never commit a partial structured result. Recheck authorization at execution and result retrieval, not merely admission.
Propagate deadlines and cancellation
The local fake model below has two simulated stages of 20 ms each. It assigns kitchen only to a whitespace-delimited mug word. Deadline is an exclusive elapsed-time boundary: a result finishing at the deadline is too late. Cancellation at or before the earlier of completion and deadline takes precedence; cancellation after completion does not undo a completed result. The first run completes; the second finishes at its deadline and returns timeout; the third is cancelled. This arithmetic simulates scheduling and never sleeps, starts a server or invokes an actual model. A real gRPC deadline bounds how long a caller will wait [2]; cancellation does not automatically terminate arbitrary application work [3]. Pass remaining time to downstream calls, check cancellation during processing, and release reservations in cleanup. Use a monotonic clock for elapsed budgets and define behavior for ambiguous outcomes; never retry a possibly committed effect blindly.
def run_job(text, step_ms, deadline_ms, cancel_at_ms=None): # Simulated elapsed times, not a real scheduler or clock. if type(text) is not str or not 1 <= len(text) <= 80: raise ValueError("invalid text") if type(step_ms) is not int or step_ms <= 0 or type(deadline_ms) is not int or deadline_ms < 0: raise ValueError("invalid time budget") if cancel_at_ms is not None and (type(cancel_at_ms) is not int or cancel_at_ms < 0): raise ValueError("invalid cancellation time") # Two simulated stages: prepare, then predict. finish = 2 * step_ms if cancel_at_ms is not None and cancel_at_ms <= min(finish, deadline_ms): return {"status": "cancelled", "tag": None} if finish >= deadline_ms: return {"status": "timeout", "tag": None} # Fictional local model: a fixed keyword rule, not trained inference. tag = "kitchen" if "mug" in text.lower().split() else "other" return {"status": "complete", "tag": tag}
print(run_job("blue mug", 20, 50))print(run_job("blue mug", 20, 40))print(run_job("blue mug", 20, 50, 15))Practice and integration decisions
Design an overnight batch for 500 fictional items with a 20-item chunk size, then an interactive single-item request and a delayed queue variant. Record contract, authentication, maximum input/output, deadline, cancellation mechanism, and replay policy for each. Choose REST for a simple interoperable JSON interface or gRPC where typed contracts and streaming fit the client ecosystem; measure actual overhead rather than assuming one wins. Avoid exposing internal exceptions or secrets. Keep the fake model behind an adapter so tests do not require a GPU or network. See the earlier tool-execution and security lessons for permissions and idempotency; see the separate ByteMind Networking and API tracks when their canonical links are verified. No live service is needed for this worksheet.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
AI service integration patterns quiz
Assess integration contracts, deadlines, health, fallback and rollback.
Which pattern fits overnight catalog tagging?
Where should tenant identity come from?
What does accepted mean in a queued contract?
What happens when the fixture finishes exactly at its deadline?
Why use idempotent worker effects?