AI/ML Engineer Top 100 Interview Questions
100 AI/ML engineer interview questions with structured answers, comparison tables, flow diagrams, worked calculations and runnable code. Covers problem framing, classical algorithms, clustering, recommender systems, forecasting, text, evaluation, applied deep learning and MLOps, from fundamentals to system design.
Questions 61-80 of 100
Q61.How do you handle variable-length sequences in a batch?
Hardware processes batches as rectangular arrays, so sequences of different lengths must be padded to a common length, with masks that make the model and the loss ignore the padding. Group sequences by length to keep padding waste low.
- Pad shorter sequences with a special padding value up to the longest in the batch, not the longest in the dataset.
- Mask attention so real tokens never attend to padding positions.
- Mask the loss so padding positions add nothing to the loss or the metrics.
- Bucket by length: sort or group examples of similar length into the same batch to reduce wasted computation.
- Batch by token budget, not by a fixed number of sequences, so batches of short sequences hold more examples.
- Truncate or split very long sequences, with sliding windows when context across the cut matters.
- For recurrent networks, use packed sequences so computation stops at each sequence's real end.
Forgetting a mask is a silent bug: the model trains and gives plausible results, but learns from padding and behaves differently when the batch composition changes.
Example
Why bucketing matters for one batch of three sequences with 12, 15 and 300 tokens:
- Padded to 300, the batch holds
3 × 300 = 900positions, of which only12 + 15 + 300 = 327are real, so 64% of the computation is wasted. - With bucketing, the two short sequences go into a batch with other short ones, padded to 15, and the long one joins other long ones.
- Across a dataset with many short sequences, this commonly cuts training time substantially without changing the model at all.
Q62.What is an autoencoder, and what is it used for?
An autoencoder is a neural network trained to reproduce its input after squeezing it through a narrow middle layer, the bottleneck. To reconstruct well, the encoder must learn a compact representation that keeps the most important information.
flowchart LR A["Input"] --> B["Encoder"] B --> C["Bottleneck code"] C --> D["Decoder"] D --> E["Reconstruction"] E -->|reconstruction error| F["Training loss"]Common uses:
- Dimensionality reduction: the bottleneck code is a learned, nonlinear compression of the data.
- Anomaly detection: trained on normal data only, it reconstructs unusual inputs poorly, so high reconstruction error flags them.
- Denoising: trained to map corrupted inputs to clean ones, it learns to remove noise.
- Pretraining: the encoder becomes a feature extractor for a downstream task with few labels.
- Generation: variational autoencoders learn a smooth code space that can be sampled to create new data.
Pitfalls:
- Without a real bottleneck or other constraint, it can learn to copy the input, which is useless.
- For anomaly detection, any anomalies in the training data teach it to reconstruct them well, so clean the training set.
Q63.How do generative adversarial networks and variational autoencoders differ?
A generative adversarial network trains a generator to fool a discriminator that tries to tell real from generated data. A variational autoencoder learns to encode data into a smooth probability distribution over codes and decode samples from it, trained by reconstruction plus a penalty that keeps codes well organized.
Generative adversarial network Variational autoencoder Trained against a competing discriminator Trained on reconstruction error plus a distribution penalty Sharp, realistic samples Often blurrier samples Hard to train: can oscillate or collapse Stable, like ordinary training May collapse to a few modes of the data Covers the data more evenly No built-in encoder for real inputs Has an encoder for real inputs by design Gives no likelihood estimate Gives an approximate lower bound on likelihood When to use which:
- Adversarial networks when realism of individual samples matters most, such as image synthesis or super-resolution.
- Variational autoencoders when you need a structured latent space, an encoder, stable training or anomaly scores.
For high-quality image generation, diffusion models, which learn to remove noise step by step, have largely replaced both. Their samples are realistic, they cover the data well and they train stably, at the cost of slower generation.
Q64.How do you measure object detection quality with intersection over union?
Intersection over union measures how well a predicted box overlaps the true box: the area they share divided by the area they cover together. A prediction counts as correct only if its overlap with an unmatched true box of the same class passes a threshold.
IoU = area of overlap / (area of box A + area of box B − area of overlap)
What each term means:
- Overlap: the intersection rectangle, with width
max(0, min(right edges) − max(left edges)), and height computed the same way. - Union: both areas added together, minus the overlap that was counted twice.
How detection metrics use it:
- Each predicted box is matched to the true box it overlaps most, in descending order of confidence.
- A match with IoU at or above the threshold, commonly 0.5, is a true positive; otherwise it is a false positive. Unmatched true boxes are false negatives.
- Precision and recall across confidence levels give average precision per class, and its mean over classes summarizes the detector.
Stricter thresholds, such as 0.75, reward precise localization. Averaging over thresholds from 0.5 to 0.95 rewards both finding objects and drawing tight boxes.
Example
One true box from (10, 10) to (60, 60), an area of 2,500, compared with three predictions of the same size:
- Prediction at (30, 30) to (80, 80): overlap
30 × 30 = 900, union2,500 + 2,500 − 900 = 4,100, so IoU ≈ 0.22, a false positive at a 0.5 threshold. - At (20, 20) to (70, 70): overlap
40 × 40 = 1,600, union 3,400, so IoU ≈ 0.47, still just below 0.5. - At (15, 15) to (65, 65): overlap
45 × 45 = 2,025, union 2,975, so IoU ≈ 0.68, a true positive.
A shift of only 5 pixels on 50-pixel boxes separates a hit from a miss, which is why IoU thresholds strongly affect reported results.
Q65.Implement non-maximum suppression for object detection.
Detectors usually predict several overlapping boxes for the same object. Non-maximum suppression keeps the highest-scoring box, removes the others that overlap it too much, and repeats with the remaining boxes.
- Sort boxes by confidence, highest first.
- Take the top box and keep it.
- Remove every remaining box whose intersection over union with the kept box is at or above a threshold, such as 0.5.
- Repeat until no boxes remain.
Key points:
- Run it per class, so a person box does not suppress an overlapping bicycle box.
- Filter low scores first, which removes most boxes cheaply before the pairwise comparisons.
- Threshold trade-off: a low threshold can merge genuinely adjacent objects, such as people in a crowd; a high one leaves duplicates.
- Soft variants lower the scores of overlapping boxes instead of deleting them, which helps in crowded scenes.
The simple version compares pairs of boxes, so its cost grows with the square of the box count. That is fine after score filtering leaves a few hundred boxes.
Example
Suppressing duplicate detections of two objects, with boxes written as left, top, right and bottom:
def iou(a: tuple, b: tuple) -> float: x1, y1 = max(a[0], b[0]), max(a[1], b[1]) x2, y2 = min(a[2], b[2]), min(a[3], b[3]) overlap = max(0, x2 - x1) * max(0, y2 - y1) area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) return overlap / (area_a + area_b - overlap) def nms(boxes: list[tuple], scores: list[float], threshold: float = 0.5) -> list[int]: order = sorted(range(len(boxes)), key=scores.__getitem__, reverse=True) keep = [] while order: best = order.pop(0) keep.append(best) order = [i for i in order if iou(boxes[best], boxes[i]) < threshold] return keep boxes = [(10, 10, 60, 60), (12, 12, 62, 62), (100, 100, 150, 150), (14, 8, 58, 64), (105, 98, 148, 152)] scores = [0.92, 0.85, 0.80, 0.60, 0.75] print(nms(boxes, scores)) # [0, 2] print(round(iou(boxes[0], boxes[1]), 3)) # 0.855 print(round(iou(boxes[2], boxes[4]), 3)) # 0.805Boxes 1 and 3 overlap box 0 heavily and are removed, and box 4 is removed by box 2. One box survives per object.
Q66.How do data parallelism and model parallelism differ for training?
Data parallelism copies the whole model to every device and splits each batch between them, combining gradients after each step. Model parallelism splits the model itself across devices, because it is too large for one, and passes activations between them.
Data parallelism Model parallelism Splits the batch Splits the model's layers or tensors Each device holds the full model plus its share of activations Each device holds only part of the model Sends gradients once per step Sends activations and gradients between devices many times per step Used when the model fits on one device and you want more speed Needed when the model does not fit on one device Low complexity, widely automated High complexity, needs careful partitioning Variations used in practice:
- Sharded data parallelism: each device stores only a slice of the optimizer state, gradients and even weights, gathering them when needed. It trains much larger models with data-parallel simplicity.
- Pipeline parallelism: consecutive groups of layers sit on different devices, and micro-batches flow through them like an assembly line to keep every device busy.
- Tensor parallelism: single large matrix operations are split across devices, which needs fast links between them.
Large models usually combine all three. Data parallelism is always the first tool, because it is the simplest and scales well until the model no longer fits.
Q67.How does mixed-precision training speed up training?
Mixed-precision training does most computation in 16-bit floating point while keeping a 32-bit master copy of the weights for updates. Modern accelerators run 16-bit matrix operations several times faster than 32-bit ones, and 16-bit activations take half the memory.
How it works:
- Keep 32-bit master weights.
- Each step, run the forward and backward passes in 16-bit, using a 16-bit copy of the weights.
- Scale the loss up before the backward pass so small gradients do not round to zero in 16-bit, then scale them back down. A 16-bit format with the full 32-bit exponent range avoids most of this need.
- Apply the update to the 32-bit master weights.
- Keep numerically sensitive operations, such as large sums and normalization statistics, in 32-bit.
Where the gains come from:
- Faster matrix math on specialized hardware units.
- Half the activation memory, which allows larger batches or longer sequences.
- Less data to move between memory and compute, and between devices.
Weight and optimizer memory does not shrink much, because the master weights and optimizer state stay in 32-bit. The big memory saving is in activations.
Example
Memory for a 350-million-parameter model trained with an adaptive optimizer on one 24 GB device, assuming activations of 20 GB at 32-bit for the chosen batch:
- Weights, gradients and optimizer state take about 16 bytes per parameter in both setups, so about
350 million × 16 = 5.6 GB. - 32-bit training:
5.6 + 20 = 25.6 GB, which does not fit. - Mixed precision: activations halve to 10 GB, so
5.6 + 10 = 15.6 GB, which fits with room to spare. - Matrix operations also run faster, so each step takes less time as well.
Q68.How would you debug a neural network that is not learning?
Work from the simplest possible check upward: first prove the model can memorize a tiny dataset, then check data, loss and gradients, and only then tune hyperparameters. Most failures are bugs, not bad architecture choices.
flowchart TD A["Loss not improving"] --> B{"Can it overfit a tiny batch?"} B -->|no| C["Check data, labels, loss and output layer"] B -->|yes| D{"Gradients healthy?"} D -->|no| E["Fix initialization, normalization or learning rate"] D -->|yes| F{"Validation also flat?"} F -->|yes| G["Check features, leakage and model capacity"] F -->|no| H["Tune regularization and schedule"]- Overfit one small batch: a working setup reaches near-zero loss on 10 to 50 examples. If not, there is a bug.
- Inspect the data the model actually receives: shapes, value ranges, label alignment and augmentation output.
- Check the loss and output layer match: for example, applying softmax twice, or using a loss that expects raw scores on probabilities.
- Check the initial loss: it should match random guessing, such as
ln(10) ≈ 2.3for ten balanced classes. - Watch gradients and activations: zeros, values that are not numbers, or exploding norms point to the learning rate, initialization or normalization.
- Run a learning rate range test to find a workable rate.
- Compare with a simple baseline to confirm that the data contains a learnable signal at all.
Q69.How do you choose a loss function for a problem?
Choose the loss that matches the type of output, the noise in the data and the cost of different errors, and make sure it moves in the same direction as the metric you report.
Regression Regression with outliers Forecasting a range Binary classification Squared error Absolute error, or a loss quadratic near zero and linear beyond Quantile loss Log loss When large errors are especially bad and noise is roughly symmetric When a few extreme values should not dominate When you need, say, the 90th percentile for safety stock When you need good probabilities Multi-class classification Multi-label classification Heavy class imbalance Ranking and similarity Cross-entropy over softmax Log loss per label Weighted cross-entropy or focal loss Pairwise, listwise or contrastive losses When exactly one class is correct When several labels can apply at once When easy majority examples swamp the signal When order or closeness matters more than exact scores Points that matter:
- Asymmetric costs can be built into the loss with weights, or handled later with the decision threshold.
- Losses that must be differentiable cannot be metrics such as accuracy directly, so use a smooth proxy and report the real metric.
- Check the scale: combining several losses needs weights, or one will dominate the gradients.
Q70.What is contrastive learning, and why does it work without labels?
Contrastive learning trains an encoder so that two different views of the same example land close together in embedding space, while views of different examples land far apart. The views come from data augmentation or from naturally paired data, so no human labels are needed.
flowchart LR A["Image"] --> B["View 1: crop and recolor"] A --> C["View 2: different crop"] B --> D["Encoder"] C --> D D --> E["Pull matching views together"] D --> F["Push other examples apart"]How it works:
- Make two augmented views of each example in a batch.
- Encode all views into vectors.
- For each view, treat its partner as the positive and every other example in the batch as a negative.
- Use a softmax over similarities, with a temperature, so the loss is lowest when the positive is the most similar.
Why it learns useful features: to identify its partner among many others, the model must keep what makes an example distinctive and ignore what the augmentations change, such as color or cropping.
Practical points:
- Augmentation choices define what is ignored; heavy color changes are wrong if color matters to the task.
- More negatives help, which favors large batches or memory banks of past embeddings.
- The same idea aligns paired data, such as images with captions, into one shared embedding space.
Q71.What is MLOps, and how does it differ from DevOps?
MLOps applies DevOps practices, such as automation, version control, testing and monitoring, to machine learning systems. It extends them because model behavior depends on data as well as code, and models can degrade silently without any code change.
DevOps MLOps Versions code and configuration Versions code, data, features, models and configuration Tests logic, integration and performance Also tests data quality, model quality and fairness Releases when code changes Also releases for new data, retraining and drift Fails with errors and outages Also fails silently, with worse predictions Monitors latency, errors and saturation Also monitors input drift and prediction quality Involves developers and operations Also involves data scientists and data engineers Core MLOps practices:
- Reproducible training pipelines that record exactly which data, code and parameters produced each model.
- Automated validation gates for data and models before deployment.
- A model registry with versions, lineage and approval status.
- Safe deployment, such as shadow or canary releases, plus a fast rollback.
- Monitoring of data, predictions and business outcomes, feeding retraining decisions.
Maturity usually grows in steps: manual notebooks, then automated training pipelines, then automated retraining and deployment with monitoring that closes the loop.
Q72.What are the stages of an automated machine learning pipeline?
An automated pipeline takes raw data to a deployed, monitored model through repeatable stages, each of which can stop the run if quality checks fail.
flowchart LR A["Ingest data"] --> B["Validate data"] B --> C["Build features"] C --> D["Train"] D --> E["Evaluate against current model"] E --> F{"Passes gates?"} F -->|no| G["Stop and alert"] F -->|yes| H["Register model"] H --> I["Deploy gradually"] I --> J["Monitor and trigger retraining"]- Ingest: pull a defined snapshot of data, so the run is reproducible.
- Validate data: schema, ranges, missing values and distribution shifts, against expectations.
- Build features with the same code used in serving.
- Train with recorded parameters, code version and data version.
- Evaluate on held-out data, per important slice, and against the current production model.
- Gate: promote only if the new model beats or matches the current one without regressions in key slices or fairness checks.
- Register the model with its lineage and evaluation report.
- Deploy with a shadow run, canary or experiment.
- Monitor inputs, outputs and outcomes, and trigger retraining when needed.
Each stage should be idempotent and independently re-runnable, so a failure at evaluation does not mean reloading all the data.
Q73.What is a feature store, and how does it keep training and serving consistent?
A feature store is a shared system for defining, computing, storing and serving machine learning features. Each feature is defined once and used for both training data and live predictions, which prevents the two from drifting apart.
flowchart LR A["Batch and stream sources"] --> B["Feature pipelines"] B --> C["Offline store with full history"] B --> D["Online store with latest values"] C -->|point-in-time join| E["Training datasets"] D -->|low-latency reads| F["Live model serving"]What it provides:
- One definition per feature, so training and serving use the same logic instead of two separately written implementations.
- An offline store with historical values and timestamps, used to build training sets with point-in-time joins.
- An online store with the latest value per entity, readable in milliseconds during live predictions.
- A registry where teams discover and reuse existing features, with owners and documentation.
- Freshness monitoring and backfills when definitions change.
When it is worth it: several models share features, real-time serving needs the same features as training, or training-serving mismatches have already caused incidents. A single batch model may not need one.
Q74.What is point-in-time correctness, and how do you guarantee it in training data?
Point-in-time correctness means every feature in a training row uses only the information that was available at the moment the prediction would have been made. Joining today's feature values onto past labels leaks the future and makes offline results look far better than production will be.
How leaks happen:
- Joining the latest value of a feature, such as the current account balance, onto labels from months ago.
- Aggregates computed over the whole history, including data after the prediction time.
- Records that were updated later, such as a corrected address, overwriting what was known at the time.
- Ingestion delays: data stamped at 10:00 that arrived at 14:00 was not available for a prediction at 11:00.
How to guarantee it:
- Store feature history with validity timestamps, rather than overwriting values.
- Join "as of" each label's prediction time: take the latest value at or before that time.
- Use availability time, not event time, when data arrives late.
- Generate training data with the same code the feature store uses, rather than ad hoc queries.
- Check for leakage: a single feature with suspiciously high importance often signals future information.
Example
An as-of join for a credit limit that changes over time, compared with a naive join on the latest value:
from bisect import bisect_right limit_history = { # customer -> (valid from, credit limit), in date order "c1": [("2026-01-01", 1000), ("2026-02-15", 2500), ("2026-03-10", 4000)], "c2": [("2026-01-20", 500)], } labels = [("c1", "2026-02-01", 0), ("c1", "2026-03-01", 1), ("c1", "2026-03-20", 0), ("c2", "2026-01-10", 0)] def as_of(customer: str, when: str): history = limit_history.get(customer, []) position = bisect_right([start for start, _ in history], when) return history[position - 1][1] if position else None for customer, when, label in labels: latest = limit_history[customer][-1][1] print(f"{customer} {when} as-of {as_of(customer, when)} latest {latest} label {label}") # Output: # c1 2026-02-01 as-of 1000 latest 4000 label 0 # c1 2026-03-01 as-of 2500 latest 4000 label 1 # c1 2026-03-20 as-of 4000 latest 4000 label 0 # c2 2026-01-10 as-of None latest 500 label 0The naive join gives every row the March limit of 4,000, including predictions made in February. Customer c2 had no limit at all on 10 January, and the as-of join correctly leaves it empty.
Q75.What belongs in a model registry?
A model registry is the system of record for trained models: it stores each version together with everything needed to understand, reproduce, approve, deploy and roll it back.
Model artifact and version Lineage Evaluation report Parameters and hyperparameters The exact file to deploy and to roll back to Training data version, code commit and feature definitions, for reproducibility Metrics overall and per slice, compared with the previous version How the model was configured and trained Environment Input and output signature Stage and approvals Owner and documentation Library versions and hardware needed to run it The expected schema, so serving can validate requests Staging, production or archived, with who approved and when Who to contact, intended use and known limitations How it is used:
- Deployment pipelines pull a specific registered version, never a file from someone's laptop.
- Promotion between stages requires passing automated checks and, for high-risk models, a human approval.
- Rollback is switching production back to the previous registered version.
- Audits can answer which model made a given decision, trained on which data.
Keep the registry the single source of truth. A model running in production that is not in the registry is an untracked risk.
Q76.How do you version data alongside code and models?
Treat every dataset used for training as an immutable, identifiable snapshot, and record its identifier in the model's lineage together with the code commit and parameters. Any model can then be traced to, and rebuilt from, exactly the data it learned from.
Practical techniques:
- Immutable snapshots: write each training dataset once, to a versioned path or table version, and never edit it in place.
- Table formats with time travel, which let you query a table as it was at a past version or timestamp.
- Content hashes of files or partitions, so identical data gets the same identifier and silent changes are detected.
- Pointers, not copies: store large data once and version the metadata that says which files make up a dataset.
- Version labels separately: labeling guidelines and label sets change over time, and they matter as much as the raw data.
- Version schemas and feature definitions, since a changed transformation is a changed dataset.
- Link it all in the registry: model version, data version, code commit, environment and parameters.
Complications to plan for:
- Deletion requests and retention rules may require removing a person's data from old snapshots, so record which models used which data in order to retrain them.
- Storage costs grow with snapshots, so set retention for datasets no production model depends on.
Q77.What should trigger retraining a model?
Retrain when there is evidence that the model has gone stale or that new data will improve it: on a schedule suited to how fast the domain changes, when monitoring detects drift or a drop in performance, or when the business or data sources change.
Schedule Input drift Performance drop Retrain weekly on the latest data A feature's stability index passes an agreed threshold Precision falls below target once labels arrive Simple and predictable; may retrain unnecessarily Early warning before labels arrive The strongest signal, but often delayed New labeled data Business change Upstream change Enough new labels to matter, such as 20% more A new product line, market or policy A source system changes a field's meaning Useful when data is scarce Old patterns may no longer apply May need a fix, not just a retrain Guardrails:
- A retrain is not a release. Every retrained model passes the same validation gates and comparison against the current model before deployment.
- Investigate before retraining on drift: a data pipeline bug looks like drift, and retraining on broken data bakes the bug in.
- Track how much each retrain helps, which tells you the right cadence. If weekly retrains rarely change anything, monthly may be enough.
Q78.What tests should a machine learning pipeline run before a model ships?
Test the data, the code that transforms it, the model's quality and behavior, and the serving system. Ordinary software tests catch only a fraction of machine learning failures.
Data validation Feature unit tests Training-serving parity Model quality Checks schema, ranges, missing values and distribution shifts Checks that each transformation gives expected outputs Checks that offline and online feature code give identical values Checks metrics against a baseline and the current model, per slice Age between 0 and 120; no column suddenly half empty Date features handle time zones and leap years Same inputs produce the same feature vector in both paths No important slice drops by more than 2 points Fairness Behavioral tests Performance Integration Checks error rates across relevant groups Checks invariance and direction Checks latency, throughput and memory Checks the serving endpoint end to end False positive rates compared across groups Changing a customer's name never changes the prediction 99th-percentile latency under 50 ms at expected load Golden inputs return the expected outputs How to run them: put cheap checks, such as data validation and unit tests, on every pipeline run, and expensive ones, such as full evaluation and load tests, as gates before promotion. Record every result with the model version in the registry.
A failed gate should stop the release automatically and say exactly which check failed. Teams then fix the cause instead of arguing about whether a drop was acceptable.
Q79.When would you use a multi-armed bandit instead of an A/B test?
An A/B test splits traffic in fixed proportions for a set period to measure the difference between options accurately. A multi-armed bandit shifts traffic toward better-performing options while the test runs, earning more along the way at the cost of a less precise measurement.
A/B test Multi-armed bandit Traffic split fixed for the test duration Traffic shifts toward the best option Goal: learn the true effect with confidence Goal: maximize reward during the test A poor option keeps its traffic for the whole test A poor option loses traffic quickly High statistical clarity: clean effect sizes and intervals Lower clarity: biased estimates, harder to analyze Best for major, lasting decisions Best for many options, short-lived content, ongoing optimization When to use which:
- A/B tests for launching a new model or feature where you need a trustworthy estimate of the effect, including on guardrail metrics.
- Bandits for headline or creative selection, short promotions, and continuously choosing among many similar options where only reward matters.
- Contextual bandits pick the best option per user context, and work like a lightweight, continuously learning recommender.
Bandits rely on quick feedback. If the outcome takes weeks to observe, such as retention, the adaptation comes too late to help.
Example
Choosing among three page layouts with 300,000 visitors, where the true conversion rates are 5%, 6% and 4%:
- Equal split: 100,000 visitors each, giving
5,000 + 6,000 + 4,000 = 15,000conversions. - Bandit: suppose it sends about 80% of traffic to the best layout once it has learned. That gives
240,000 × 0.06 + 30,000 × 0.05 + 30,000 × 0.04 = 17,100conversions. - Ideal, if the best were known in advance:
300,000 × 0.06 = 18,000. - The A/B test gives up 3,000 conversions to measure every layout precisely; the bandit gives up 900 but leaves a less precise estimate of the weaker layouts.
Q80.How do you serve a model with low latency at high request rates?
Combine a lean model, efficient serving, and enough horizontally scaled capacity sized from measured per-request costs, keeping everything that is not prediction out of the hot path.
Techniques:
- Make the model cheaper: smaller architectures, distillation into a compact model, quantization and pruning.
- Precompute features: read them from a low-latency online store instead of computing aggregates per request.
- Batch dynamically: group requests that arrive within a few milliseconds, which multiplies throughput on accelerators.
- Cache predictions for repeated inputs, such as popular items or anonymous pages.
- Use an optimized runtime with compiled graphs and fused operations.
- Scale horizontally behind a load balancer, with autoscaling on request rate or queue time.
- Set a latency budget per stage: network, feature lookup, inference and post-processing, and measure the 99th percentile, not the average.
- Plan a fallback, such as a simpler model or a default answer, for when the budget is exceeded.
A useful sizing rule:
requests in flight = request rate × latency. It tells you how much concurrency the serving fleet must support.Example
Sizing serving for 10,000 requests per second with a 50 ms latency budget at the 99th percentile:
- On CPUs: one request takes 8 ms on one core, so each core serves
1,000 / 8 = 125requests per second, and10,000 / 125 = 80cores are needed. With 50% headroom, plan about 120 cores. - On accelerators with batching: a batch of 64 takes 20 ms, so one device serves
64 / 0.020 = 3,200requests per second, and10,000 / 3,200 ≈ 3.1, so 4 devices, or 5 with headroom. - Latency check: waiting up to 20 ms to fill a batch plus 20 ms of compute gives 40 ms, inside the 50 ms budget. A 30 ms wait would break it, so the batching window is capped.