41. Design an API for text embeddings and compatible classifications.
The service receives raw text, owns deterministic preprocessing, and supports synchronous single-item requests plus larger asynchronous batches. Define versioned request and response contracts, item-level validation and partial failures, embedding and classifier training data and evaluation labels, an immutable compatibility registry, batching and accelerator scheduling, caching, tenant isolation, retries and checkpoints, online and batch serving, quality and drift monitoring, feedback, rollout and rollback, retraining triggers, privacy and retention, security boundaries, availability, and cost.
I would expose versioned embed and classify endpoints for synchronous single-item requests, plus an asynchronous batch API. Every path shares deterministic preprocessing and an immutable embedding-classifier compatibility registry. Batch workers use queues, accelerator-aware batching, retries, and checkpoints, while caching, tenant isolation, monitoring, feedback, safe rollout, privacy, and cost controls apply across the system.
The service accepts raw text and owns deterministic preprocessing, so training and serving must use the same versioned text rules. I would expose synchronous embedding and classification endpoints for single items and an asynchronous batch endpoint for larger jobs. Every request is tenant-aware, validated, versioned, and resolved through an immutable compatibility registry before inference. Batch jobs preserve successful items when others fail and resume through checkpoints after retryable failures. Online and batch serving share model artifacts, preprocessing, compatibility rules, response contracts, monitoring, privacy boundaries, feedback lineage, and rollout controls while using different scheduling behavior.
- What latency and request-size expectations should the synchronous endpoints support?
- How large can asynchronous batches become, and what completion-time expectations apply to them?
- Can a classification request run multiple classifier models against one embedding, or normally only one classifier?
- Can a classifier be approved for several embedding versions, or is each classifier tied to exactly one embedding version?
- What tenant isolation, retention, deletion, and regional requirements apply to raw text, embeddings, predictions, metadata, and logs?
- What availability and cost constraints should guide accelerator capacity, caching, batching, and graceful degradation?
The synchronous unit of work is one raw text item. The service, rather than the client, owns preprocessing. I would expose versioned endpoints such as POST /v1/embed and POST /v1/classify. The API gateway performs authentication and authorization, tenant isolation and quotas, rate limiting, request validation, routing, and API-version selection.
An embed request carries raw text, the requested model or version information, and supported options. Its response contains the embedding and metadata such as model version, preprocessing version, embedding dimension, and request metadata. A classify request similarly returns labels or scores plus version metadata. A response formatter keeps these contracts consistent across serving paths.
For larger workloads, I would expose POST /v1/batches. A valid batch submission returns an accepted job identifier instead of keeping the HTTP connection open until all items finish. Clients can query job status and retrieve completed results.
A malformed request envelope can fail the whole request. A multi-item job is different: one invalid text item should not normally discard valid work from all other items.
Each item therefore has its own success or error state. The final batch can be marked partial, with counts of succeeded and failed items, successful outputs, and explicit errors for failed indexes. This matches the diagram's partial-failure response model and avoids reprocessing expensive successful items.
Idempotency is also important. Repeating the same accepted batch request with the same idempotency key should not create duplicate logical jobs or duplicate committed results.
The preprocessing configuration store contains versioned rules used by both online inference and the offline training pipeline. Relevant transformations can include normalization, language detection, PII handling, tokenization, truncation, or other model-required text preparation.
The important rule is consistency. Whatever transformations a deployed model requires must be represented by a stable preprocessing version and applied with the same semantics during training and serving. That prevents training-serving skew.
An embedding model and classifier should not be combined merely because their dimensions appear compatible. A classifier was trained and evaluated against a particular embedding representation and configuration.
I would keep an immutable compatibility registry containing approved embedding-to-classifier relationships. An entry records the embedding version, classifier version, dimensional constraints when relevant, evaluation or threshold metadata, and the validity of that combination. Existing approved entries are not silently rewritten; a new combination creates a new versioned entry.
The online inference service and batch workers both consult this same compatibility information before running classification. If a requested combination is not approved, the request fails explicitly rather than silently substituting another model.
The model registry stores versioned model artifacts together with code and configuration versions, training-data snapshots, evaluation results, schema information, and other artifact metadata shown in the design. A published model therefore has traceable lineage back to the data, preprocessing, code, configuration, and evaluation that produced it.
The compatibility registry answers a different question from the model registry. The model registry says which artifacts exist. The compatibility registry says which embedding and classifier versions are approved to work together.
The synchronous path is optimized for interactive requests. The gateway sends a valid request to the online inference service, which applies deterministic preprocessing, resolves compatible model versions, performs embedding and optional classification, uses safe caches where applicable, and sends results through the response formatter.
Large jobs use the asynchronous path. A batch orchestrator maintains the job queue, chunks work into useful batches, schedules accelerator capacity, applies retry policy, records checkpoints, and sends work to batch inference workers. Workers preprocess items, run embedding and classification, checkpoint progress, and write results.
Keeping these paths separate prevents large backfills from consuming all resources required for interactive traffic.
Accelerators are usually most efficient when several compatible items are processed together. The scheduler can group queued work by compatible model versions and other execution constraints, then form batches that improve utilization.
The tradeoff is latency. Waiting longer to form a larger accelerator batch may reduce cost per item but increases queueing delay. Interactive traffic should therefore use tighter batching limits, while asynchronous jobs can tolerate larger batches and longer waits.
Tenant quotas and scheduler fairness must prevent one tenant or one large batch from monopolizing shared accelerator capacity.
A worker can fail after processing only part of a large job. Restarting from the beginning wastes accelerator time and risks duplicate writes.
The orchestrator records progress at stable chunk or item boundaries. After a retryable worker failure, processing resumes from the last committed checkpoint. Result writes and job-state transitions are idempotent so replay does not create duplicate logical results.
Permanent item failures, such as invalid input, remain item errors and are not retried forever. Retryable infrastructure failures are treated separately.
The diagram contains separate embedding and classification caches. An embedding cache key should represent the effective normalized input and the relevant model and preprocessing versions. Classification caching must additionally capture the classifier version and any options that change classification semantics.
Caches must also obey tenant-isolation rules. A cache optimization must never expose another tenant's raw text, embeddings, classifications, or metadata.
Caching reduces latency and accelerator cost when requests repeat, but it uses storage and provides little benefit when almost every text is unique.
The metadata store holds information such as tenants, quotas, API scopes, model aliases, endpoint limits, and related service metadata. The optional feature or vector store can hold versioned embeddings or vector indexes when downstream retrieval use cases require them, while keeping tenant partitions explicit.
These stores are not substitutes for the immutable model and compatibility registries. Each has a different responsibility: service metadata, optional vector data, model artifacts, and model compatibility should remain separately governed.
Offline training is separate from serving. The pipeline can ingest approved sources such as internal logs, user content, third-party data, or public corpora when permitted. Ingestion and labeling perform deduplication, PII handling, quality checks, and creation of the labels required for classifier training and evaluation.
The same deterministic preprocessing semantics used in serving are applied before training. Embedding-model training uses its appropriate representation-learning objective. Classifier training uses labeled examples for the classification task. If the classifier consumes embeddings, those training embeddings must be generated by the embedding version recorded in the compatibility relationship.
Training-data snapshots, preprocessing configuration, code, model configuration, artifacts, and evaluation results are versioned so the result can be reproduced and audited.
A training metric alone is not enough to deploy a model. The offline evaluation stage should measure metrics appropriate to the embedding or classification task, inspect errors, evaluate classifier calibration when its scores need probability-like interpretation, and examine meaningful slices when relevant.
The exact metric and acceptance threshold should come from product requirements rather than being invented. Evaluation results are stored with the artifact. Only models that pass the defined validation gate are published to the model registry and made eligible through compatibility entries.
Some labels or outcomes can arrive after inference. Each prediction therefore needs a stable identifier together with the model and preprocessing versions that produced it. User feedback, corrections, or later system outcomes can be joined back to the correct prediction at the correct entity and time.
After quality and privacy checks, this feedback can be analyzed, prioritized, and used as future training data. The join must not accidentally associate feedback with a different request or model version.
Observability should distinguish several kinds of signals. Service-health monitoring covers end-to-end latency, model execution time, error rate, saturation, queue health, accelerator use, and other resources. End-to-end latency includes preprocessing, queueing, networking, inference, and formatting, so it is different from model execution time alone.
Data-quality monitoring checks schema validity, missing or empty input, language behavior, nulls, ranges, and other expected properties. Drift monitoring compares current inputs, embeddings, or predictions with suitable references. Model-quality monitoring uses labels or outcomes when available. Business outcomes are monitored separately.
Drift alone is not proof that model quality has declined. It is a signal to investigate together with quality measurements and delayed outcomes.
After offline validation, a new approved version should be introduced through controlled rollout rather than immediately receiving all traffic. The design supports canary release, shadow evaluation when appropriate, and feature flags.
Service-health and model-quality guardrails determine whether traffic expands. If a defined SLO or quality guardrail is breached, routing can return to the previous approved version. Because preprocessing, model artifacts, and compatibility entries are all versioned, rollback restores a complete known-compatible combination rather than swapping one model independently.
Potential retraining triggers include meaningful data drift, demonstrated quality degradation, important business impact, scheduled maintenance, or an authorized manual trigger.
A trigger starts the training and evaluation workflow. It does not bypass evaluation, compatibility checks, rollout controls, or rollback preparation. This prevents a noisy drift signal from automatically replacing a healthy production model.
Raw text can contain sensitive data. The service therefore needs PII detection or masking where required, encryption in transit and at rest, tenant isolation, scoped API authentication and authorization, and restricted access to caches, metadata stores, model registries, vector stores, training data, and accelerator workers.
Retention policies apply to raw text, embeddings, classifications, metadata, logs, and training copies according to policy. Where required, deletion or export workflows should cover derived data as well as original text. Audit logs should record sensitive administrative operations without unnecessarily copying raw text into logs.
Interactive serving can run across multiple failure domains or regions and autoscale to protect availability. Asynchronous queues absorb bursts and let batch work wait for accelerator capacity. Rate limits and tenant quotas protect shared resources.
Graceful degradation must remain semantically safe. A valid cache hit can avoid model execution, and an asynchronous batch can wait for capacity. A missing, unavailable, or incompatible model should return an explicit failure rather than silently use an unapproved model.
Major costs include accelerator inference, training, retained model copies, embeddings or vector storage, caches, metadata storage, and redundant online capacity. Dynamic batching, caching, asynchronous scheduling, autoscaling, tenant quotas, retention policies, and cost monitoring control those costs. More batching improves utilization but can increase latency, while more spare online capacity improves resilience but costs more.
- Define versioned synchronous /embed and /classify contracts and an asynchronous /batches contract.
- Put authentication, authorization, tenant quotas, rate limits, request validation, idempotency, routing, and API-version handling at the gateway.
- Apply one versioned deterministic preprocessing contract in offline training, synchronous serving, and batch serving.
- Store immutable model artifacts and lineage in the model registry and approved embedding-classifier combinations in the compatibility registry.
- Route single-item traffic to online inference and large jobs to a batch orchestrator with queues, chunking, accelerator-aware scheduling, retries, and checkpoints.
- Use version-aware, tenant-safe embedding and classification caches where reuse is semantically valid.
- Use the metadata store for tenant, quota, scope, alias, and endpoint metadata, and use the optional feature or vector store only when versioned embeddings or indexes are required.
- Train embedding and classifier artifacts offline from versioned, quality-checked data and labels.
- Evaluate before publishing and never deploy from a training metric alone.
- Roll out approved versions with canary, shadow, or feature-flag controls and retain a complete rollback path.
- Monitor service health, data quality, drift, model quality, and business outcomes separately.
- Join feedback and delayed outcomes to prediction identifiers and versions, then use validated signals as retraining triggers.
- Apply PII handling, encryption, retention, deletion, tenant isolation, and scoped security boundaries.
- Balance synchronous availability against accelerator, batching, caching, storage, training, and redundant-capacity cost.
The most expensive computation is usually embedding and classification inference on accelerators. Dynamic batching improves accelerator utilization because several compatible items can share one execution batch, but waiting to form a batch can increase latency. Caching repeated computations can reduce both latency and accelerator cost, but caches consume storage and provide little value for unique text. Asynchronous jobs improve throughput and absorb bursts, but they require queue state, retries, checkpoints, result storage, and cleanup. Keeping older approved versions available makes rollback safer but consumes memory and capacity. Strong tenant isolation, encryption, retention controls, monitoring, lineage, and optional vector storage add operational cost. The practical design therefore protects synchronous capacity while allowing large workloads to use queued and efficiently batched accelerator capacity.
This design is useful when one service must provide reusable text embeddings and compatible classifiers to web applications, backend services, data-science notebooks, and large offline jobs. Examples include applications that need embeddings for semantic retrieval, systems that classify text into supported labels, and backfills that process many text items asynchronously. It is especially useful when several classifier versions depend on specific embedding versions and the platform must prevent untested combinations from reaching production.
This question tests whether a candidate can design the complete machine-learning service around text embeddings and classifiers, not just describe model inference. A strong answer connects API contracts, deterministic preprocessing, compatible model versions, synchronous and asynchronous serving, item-level failures, accelerator scheduling, caching, tenant isolation, training and evaluation, monitoring, feedback, safe rollout, privacy, availability, and cost. It also tests whether compatibility, reproducibility, and failure behavior are explicit system contracts rather than assumptions hidden inside application code.
Common mistakes include letting clients implement preprocessing independently; using mutable model names without immutable versions; assuming classifiers are compatible with any embedding of the same dimension; failing an entire batch because one item is invalid; retrying whole batches instead of resuming from checkpoints; omitting idempotency for retried jobs; using cache keys that omit model, preprocessing, classifier, or tenant semantics; letting large batch jobs starve synchronous traffic; training a classifier on embeddings from one version and serving it with another; mixing the responsibilities of the model registry, compatibility registry, metadata store, and vector store; deploying from training metrics without offline evaluation; treating drift as proof of quality loss; joining delayed feedback without prediction identifiers and version metadata; silently falling back to an incompatible model; retaining sensitive text indefinitely; and measuring model execution time while ignoring queueing, preprocessing, networking, and total end-to-end latency.
Draw the synchronous and asynchronous paths first. Then explain the contracts shared by both paths: deterministic preprocessing, immutable model compatibility, versioned artifacts, item-level failure handling, and tenant boundaries. Finish with offline training and evaluation, rollout and rollback, monitoring and feedback, retraining triggers, privacy, availability, and cost.










