Performance Cost Optimization & Resource Efficiency Questions
Optimizing for the money and resources a given level of performance consumes, not just raw speed. Covers cost-per-request, training-cost and cost-per-inference reasoning, right-sizing and cost-driven autoscaling of compute, memory and storage, choosing between on-demand, reserved and spot capacity, storage tiering and egress-cost reduction, cloud-bill diagnosis and reduction plans, and cost allocation or chargeback across teams and tenants. A question belongs here when the primary deliverable is a cost or resource-consumption calculation, decision or reduction plan, not when cost is one line among several unrelated technical considerations. Distinct from defining or measuring latency, percentiles, SLOs and latency budgets on their own, from profiling and bottleneck diagnosis such as flame graphs, hotspots and query tuning, from production incident and on-call triage, from general multi-axis trade-off frameworks where cost is incidental to a decision about latency, freshness or complexity, from concurrency, batching and thread-safety mechanics, and from garbage-collection and memory-leak tuning: those are covered by dedicated sibling topics.
You're tasked with reducing the inference cost of a large transformer model by 80% while keeping p95 latency within 2x of the current SLO. Walk through how you would approach this: what levers would you evaluate, how would you estimate each one's expected cost reduction and implementation complexity, and what would you prioritize first?
Sample Answer
Framing
An 80% cost cut on a large transformer's inference is a big enough number that no single lever gets there alone; it needs several multiplicative levers, evaluated for expected cost reduction, engineering complexity, and their effect on the 2x latency ceiling, then sequenced from safest to most disruptive.
Levers, in the order I would evaluate them
- Dynamic batching (grouping concurrent requests so the accelerator processes several at once instead of one at a time): typically the single biggest, cheapest win for accelerator-bound inference, since that hardware is built for parallel work and a batch of one wastes most of its throughput. Low engineering complexity if the serving framework already supports it; the main cost is added queueing latency while requests wait to be batched, which needs to stay inside the 2x latency budget.
- Quantization (running the model at lower numeric precision, such as INT8 instead of FP32 or FP16): another large, comparatively low-complexity win, since it directly increases throughput per accelerator for compute-bound work. Needs a quality validation pass, since a quantized model can lose accuracy, but rarely adds latency; if anything it usually reduces it.
- Caching repeated or near-duplicate requests: if a meaningful share of traffic repeats, a cache in front of the model avoids paying compute at all for those requests. Cost reduction scales with the repeat rate, which has to be measured, not assumed; complexity is low to moderate.
- Hardware or accelerator change: moving to a cheaper accelerator generation or a purpose-built inference chip can meaningfully change dollars-per-inference, but requires re-benchmarking the model on the new hardware and possibly recompiling it, so this is medium complexity and takes longer to validate.
- Knowledge distillation (training a smaller student model to mimic the large model's outputs): potentially the biggest single win, since a much smaller model can be dramatically cheaper to run, but it is the highest-complexity lever here, effectively a new model training and validation effort, with real risk of a quality regression that only shows up on certain input types.
Prioritization for an 80% target
I would start with batching and quantization together, since they are both low complexity, reversible, and roughly multiplicative (each can independently raise throughput per dollar), which in combination can plausibly get a large fraction of the way to the target on their own. I would measure the actual combined effect before assuming a number, then check the remaining gap against the target. If batching and quantization alone are not enough, I would layer in caching if the traffic has a meaningful repeat rate, since it is still comparatively low effort. Only if the target is still not met would I take on distillation or a hardware migration, since those are the highest-effort, highest-risk levers, keeping the full-size model available as a fallback for latency-sensitive or quality-critical traffic segments rather than replacing it everywhere at once.
Respecting the latency ceiling
Every lever above gets checked against the 2x latency SLO (service level objective, the internal latency target the team commits to) specifically, not just against cost: batching's queueing delay, quantization's negligible latency change, and a smaller distilled model's typically lower latency all need to be measured together, since the combination that saves the most money is only valid if the resulting p95 latency (the value below which 95% of requests complete) still lands inside twice the current SLO.
Design a capacity and cost estimation plan for a periodic training job: the dataset is 50TB, you retrain weekly, the wall-clock budget is 24 hours, and the current baseline is an 8-node A100 GPU cluster. Walk through how you'd right-size compute, storage IO, and network egress for this job, and what changes you'd consider to bring the cost down without blowing the 24-hour window.
Sample Answer
Direct answer
Size compute from the throughput actually needed to move the dataset within the time available for it, not the full 24 hours, since input and output usually overlap with compute rather than running strictly before it. Size storage and network for locality, keeping the data co-located with the compute so a weekly job is not re-paying cross-region transfer on the full dataset every cycle. Bring cost down primarily by shrinking what gets re-moved each cycle (an incremental cache instead of a full re-fetch) rather than by adding nodes.
Structured elaboration
Right-sizing compute: determine whether the job is compute-bound or I/O-bound at this data volume, by comparing the storage layer's achievable read throughput to what the GPUs need to stay fed; if storage cannot keep up, either add parallel read paths or pre-stage data onto faster local storage before the run starts.
Storage I/O: verify aggregate read bandwidth against the throughput required to avoid stalling the GPUs, and prefer fast local caching over per-step remote reads whenever the dataset volume allows it.
Network egress: if the dataset lives in a different region, cloud, or bucket than the compute cluster, every weekly retrain re-pays cross-region transfer on the entire dataset, usually the single largest and most avoidable recurring cost in this kind of job. Co-locating data and compute, or maintaining an incrementally-updated regional copy, removes this recurring cost almost entirely.
Cost-down changes that respect the 24 hour window:
- Incremental data: if only a fraction of the dataset changes week to week, fetch and process only that delta, reusing a cached copy of the rest, cutting both transfer time and egress dollars roughly in proportion to the new fraction.
- Compression or a columnar format: reduces bytes moved and stored at some CPU decode cost, usually free headroom on a GPU-bound node, but worth confirming the CPU is not already saturated elsewhere in the pipeline.
- Spot or preemptible compute for this job specifically: a weekly retrain is restartable and not customer facing, so it is a good fit, provided checkpointing survives a preemption.
- Right-sizing node count: a smaller cluster run for longer, up to the 24 hour ceiling, can beat a larger cluster that finishes with slack, since warm-up and checkpoint I/O overhead scale with node count.
Worked example
Baseline: an 8-node cluster (64 A100 GPUs), 50TB dataset stored in a different region than the compute. Profiling shows compute takes 16 hours, and the pipeline naively downloads the full dataset over cross-region network before training starts, at an achievable 2 GB per second aggregate: 50,000 GB / 2 GB/s = 25,000 seconds, about 6.94 hours, run serially before compute. Total wall clock: 16 + 6.94 ≈ 22.94 hours, uncomfortably close to the 24 hour ceiling with almost no retry margin.
weekly cost=(compute GPU-hours×$/GPU-hour)+(egress GB×$/GB)
Illustrative rates: compute $4.10 per GPU-hour, egress $0.02 per GB. Weekly compute cost = 64 × 16 × $4.10 ≈ $4,198, so about $218,317 a year. Weekly egress = 50,000 GB × $0.02 = $1,000, about $52,000 a year. Baseline total ≈ $270,317 a year.
Fix 1, co-location plus incremental caching: suppose logs show only 8% of the dataset (4,000 GB) is genuinely new each week. Fetching only that delta at the same rate takes 4,000 / 2 = 2,000 seconds, about 0.56 hours, easily overlapped with compute instead of run serially, so the I/O tax is effectively removed from the 24 hour budget. If the delta is still transferred across a boundary, egress drops to about $80 a week (8% of $1,000), roughly $4,160 a year, a 92% reduction from $52,000; if the copy is fully co-located, it drops to near zero.
Fix 2, spot compute for this batch job: at an illustrative 60% spot discount plus about 7% overhead for occasional preemption and restart, compute cost becomes roughly 0.40 × 1.07 ≈ 0.428 of on-demand, about $93,440 a year instead of $218,317.
Combined new total ≈ $4,160 + $93,440 ≈ $97,600 a year, versus the $270,317 baseline, a 63.9% reduction, while also cutting the serial I/O time from 6.94 hours to about 0.56 hours, well inside the 24 hour window with real margin for retries.
Trade-offs and pitfalls
Spot preemption risk against a hard 24 hour deadline is real: without a well-tuned checkpoint cadence, a late preemption could blow the window, so checkpoint frequency needs to be sized against preemption risk, and a small on-demand fallback reservation is a reasonable safety net. Incremental caching depends on correctly tracking what changed, a bug there silently trains on stale or duplicated data, so validate periodically against a full refresh. Compression adds CPU decode cost that must be confirmed as free headroom, not assumed. Shrinking node count can extend wall clock time, always re-check against the 24 hour ceiling with realistic margin, not just the average case.
Case study: your baseline model takes 100 GPU-hours to reach target accuracy, and you're asked to cut that to 20 GPU-hours (a 5x reduction) while keeping at least 99% of baseline accuracy. Walk through the plan you would propose: what you would try first, what categories of change you would consider (algorithmic, model architecture, data, and tooling), and how you would estimate the expected compute savings and risk of each before committing engineering time to it.
Sample Answer
Direct answer
Attack the 5x compute reduction in order of risk and speed of validation: start with tooling and data levers that are cheap to pilot and carry near zero accuracy risk (mixed precision, fixing an I/O-bound data pipeline, batch size and learning-rate tuning, early stopping tuned to the actual validation curve), then bring in a model architecture change, the riskiest lever, only if the low-risk levers do not close the gap alone, sizing each lever on a small pilot before committing full engineering time to it.
Structured elaboration
Categories, in the order to try them:
- Tooling (lowest risk): mixed precision training (using 16-bit floating point formats like FP16 or BF16 instead of 32-bit, with loss scaling to avoid numerical underflow) typically gives 1.5 to 2 times speedup on modern GPUs with no accuracy change when done correctly.
- Data: fix an I/O-bound pipeline (more loader workers, prefetching, local caching instead of re-fetching over the network every step), and deduplicate or curate the training data, both of which can cut the effective steps or wall clock needed without touching the model.
- Algorithmic: a larger batch size with a scaled learning rate can converge in fewer steps, up to a point (past a workload-specific "critical batch size" the returns flatten or reverse), and early stopping tuned to the measured validation curve avoids training past the point of diminishing returns instead of running a fixed epoch budget.
- Architecture (highest risk, try last): a smaller model or a distilled version trains faster per step, but changes model capacity, which risks falling under the required accuracy floor, so it needs the most validation.
Estimating savings and risk before committing full engineering time: run each lever on a small pilot, a short slice of steps or a small fraction of the data, measure its speedup and any early accuracy signal, then extrapolate, and rank levers by estimated savings per engineering day to implement and validate, stopping once the cumulative estimate reaches the target rather than implementing every lever regardless of need.
Worked example
Target: cut 100 GPU-hours to 20 GPU-hours (a 5x reduction) while keeping at least 99% of baseline accuracy.
GPU-hoursfinal=GPU-hoursbaseline×∏i(1−si)
where each si is the fractional reduction measured on a pilot for lever i, applied in sequence.
Step 1, mixed precision, pilot measures 1.7x throughput: 100 / 1.7 ≈ 58.8 GPU-hours, accuracy unaffected on the pilot (the standard result for correctly loss-scaled mixed precision).
Step 2, fixing the data pipeline, a profiler shows GPU utilization rising from 61% busy to 94% busy for the same computation (the GPU was previously idle 39% of the time waiting on data): 58.8 × (61 / 94) ≈ 38.2 GPU-hours.
Step 3, larger batch size with learning-rate scaling, a pilot at double batch size converges in 30% fewer steps to the same validation accuracy: 38.2 × 0.70 ≈ 26.7 GPU-hours.
Step 4, early stopping tuned to the measured validation curve, which shows the model reaches 99.5% of its final accuracy at 85% of the previously used step budget: 26.7 × 0.85 ≈ 22.7 GPU-hours.
After four low-risk, pilot-validated levers, the run is at roughly 22.7 GPU-hours, a 4.4x reduction, close to but short of the 5x target, and none of them touched model capacity. Step 5, the riskiest lever, distilling into a smaller architecture, a pilot measures 25% faster steps with accuracy within the 99% floor after fine-tuning: 22.7 × 0.75 ≈ 17.0 GPU-hours, a 5.9x reduction, overshooting the target and leaving margin for the architecture change's accuracy uncertainty.
Trade-offs and pitfalls
A speedup measured on a short pilot does not always hold at full scale, a fixed I/O bottleneck can reveal a new one once the GPU runs faster than the pipeline can feed it, so re-validate the combined pipeline once fully assembled, not just each lever in isolation. Batch size increases past the workload's critical batch size can need MORE steps to converge, not fewer, always validate on a pilot rather than assuming linear scaling. The accuracy floor must be measured on the exact same held out evaluation set across every lever, comparing against a shifting evaluation set invalidates the whole exercise. The model architecture change is the one lever that is not easily reversible without retraining, which is exactly why it belongs last and smallest first, not first because it looks like the biggest single win on paper.
Your product uses a large language model for customer support, and inference cost per request is high because contexts are long and the model generates many tokens per response. Walk through how you would bring that cost down: what levers you'd pull, how you'd prioritize them by likely ROI, and how you'd validate that each change actually saved money without hurting response quality.
Sample Answer
Framing the cost. Inference cost roughly tracks (input tokens + output tokens) times a per-token price, plus fixed per-request overhead. Long contexts inflate the input-token term; long, verbose generations inflate the output-token term (output tokens are usually billed at a higher rate than input tokens, since generation is the more expensive step). The first job is figuring out which term is actually driving the bill for this workload before picking a lever.
Levers, ordered by likely ROI
- Trim and cache the context (usually the highest ROI, lowest risk). If the same system prompt, tool schema, or retrieved documents repeat across requests, use provider-side prompt caching so the repeated prefix is priced far below a fresh token. Separately, stop pasting entire documents into context: retrieve only the passages relevant to the current question (retrieval-augmented generation) instead of stuffing a whole knowledge base in every turn.
- Cap output length. Set a
max_tokensceiling, ask the model for a concise answer, and use stop sequences to end generation as soon as the useful content is done. Since output tokens are typically the pricier half, this is cheap to implement and low risk to answer quality if done carefully. - Route by difficulty. Not every support request needs the largest, most expensive model. Classify or cascade: try a smaller, cheaper model first, and escalate to the large model only when the small model's confidence is low or the query matches a known "hard" pattern. This needs a quality-preserving router and an evaluation set, so it's more effort than the first two levers but usually the second-biggest win.
- Batch what isn't real time. If part of the workload (for example, overnight ticket triage) doesn't need an instant response, route it through a batch-style API tier, which is typically priced below the real-time interactive tier.
- Self-hosting and quantization (quantization: storing a model's weights with lower-precision numbers to shrink its size and speed it up, at some accuracy cost), last on the list unless volume is large enough to justify owning the serving stack: running a smaller, fine-tuned, or quantized model for a narrow task can be cheap per request, but it only helps if you already control the infrastructure, and it carries real engineering and quality-validation cost.
Validating that a change actually saved money without hurting quality
- Measure cost per resolved conversation, not cost per API call. A cheaper response that triggers a human escalation or a re-ask isn't a savings, it moved the cost somewhere else.
- Roll out gradually (a percentage of traffic) and watch a quality guardrail (escalation rate, thumbs-down rate, an offline eval score on a fixed test set) next to the cost metric, so a regression is caught before it reaches everyone.
- Prefer a held-out A/B or shadow comparison over a before/after time-series: traffic mix and query difficulty shift week to week, and a raw before/after can attribute someone else's change to your cost fix.
Worked example (illustrative pricing, not any specific vendor's real rate). Assume input tokens cost $0.003 per 1,000 and output tokens cost $0.015 per 1,000. A baseline support request uses 3,000 input tokens (mostly a repeated system prompt and stuffed documents) and 400 output tokens:
baseline cost = (3000/1000 * 0.003) + (400/1000 * 0.015)
= 0.009 + 0.006 = $0.015 per request
After retrieval trims context to 1,200 tokens (900 of which are a cached, repeated system prompt billed at an illustrative 10% of fresh-token price, 300 fresh) and output is capped at 200 tokens:
optimized cost = (900/1000 * 0.003 * 0.10) + (300/1000 * 0.003) + (200/1000 * 0.015)
= 0.00027 + 0.0009 + 0.003 = $0.00417 per request
That is roughly a 72% reduction under these illustrative numbers, and notice where it came from: almost all of it is the input side (caching plus trimming), because the context was large and repeated. That is a useful pattern to check for in any long-context, high-volume LLM workload before reaching for a smaller model.
Compare the cost trade-offs between training large models and serving them for inference. For a model used in production with periodic retraining, describe when compute should be invested in more training to reduce inference complexity (distillation), versus optimizing serving cost (quantization, batching). Include examples of amortization over requests.
Sample Answer
Direct answer
Compare training and serving on the same basis, dollars per served request, by amortizing
the periodic training cost over the requests served before the next retrain; apply
quantization and batching first since they are cheap, reversible, serving-side levers, and
only invest in distillation once request volume is high enough that a smaller per-request
serving win, multiplied across that volume, clearly exceeds the extra training cost.
Structured elaboration
Training cost is periodic and amortized: total training cost for a retrain cycle,
compute plus validation effort, divided by however many requests that model version serves
before the next retrain, gives a training dollars per request figure directly comparable to
serving cost.
Serving cost is recurring and per request: driven by instance-hours needed to hold the
latency SLA at the given QPS (queries per second), itself a function of the model's
inference cost and how
efficiently requests are packed through batching and precision through quantization.
Distillation, spending more at training time to shrink the served model, is worth it
when request volume is high enough that a small per-request serving win, multiplied across
that volume, exceeds the extra training cost that recurs every retrain cycle, plus the
ongoing accuracy-validation overhead of maintaining a second, smaller model. It's a poor
trade at modest volume or frequent retraining, since the training cost repeats before the
serving win has enough requests to compound over.
Quantization, typically INT8 at serving time, is usually the highest-return first
move, since it is a post-training conversion step, far cheaper than a full distillation
run, that directly cuts compute and memory per inference, letting more requests batch
together or fit on cheaper hardware, at the cost of a validation pass to confirm accuracy
holds.
Batching is a free throughput lever requiring no training investment at all,
amortizing fixed per-request overhead across many requests, limited by how much added wait
time the latency SLA can absorb.
Decision order: apply quantization and batching first, cheap, fast, and reversible,
measure the resulting cost per request, then evaluate whether distillation clears the bar
against the actual volume being served, since the cheaper levers may already close enough
of the gap that the extra training investment isn't justified.
Worked example
Model retrained monthly at an illustrative $8,000 in compute plus $2,000 of validation
effort, $10,000 per retrain cycle, serving 5 billion requests before the next retrain.
Negligible on its own, about $2 per million requests, and roughly constant regardless of
how the serving side is optimized.
Average QPS at this volume is about 1,929. An unoptimized model sustains 50 requests per
second per instance:
At $0.50/hour, 47 instances cost about $17,155/month.
Quantization triples throughput to 150 requests per second per instance:
instances≈⌈1501,929×1.2⌉=16About $5,840/month, saving roughly $11,315/month with no new training run needed, clearly
worth it on its own.
Distillation triples throughput again, to 450 requests per second per instance, but adds an
illustrative $6,000/month of amortized distillation-training cost on top of the base
training cost.
About $2,190/month serving, a further $3,650/month saved versus quantization alone, against
the extra $6,000/month training cost: net is about negative $2,350/month, not worth it at
this volume.
At five times the volume, roughly 9,645 QPS, redo the same two instance counts: quantized
needs about 78 instances (9,645 divided by 150, times the 1.2 margin, rounded up), or about
$28,470/month; distilled needs about 26 instances (9,645 divided by 450, times the same
margin), or about $9,490/month. The serving-side saving is now $28,470 minus $9,490, about
$18,980/month, against the same fixed $6,000/month distillation training cost, for a net of
roughly positive $12,980/month, clearly worth it at this volume. Distillation's payoff is a
function of request volume, not a fixed yes or no.
Trade-offs and pitfalls
Comparing a one-time-feeling training number against a monthly serving number without
amortizing over actual request volume makes any conclusion meaningless; always convert both
to dollars per request first. A distillation decision made at one volume can flip as volume
changes, so revisit it each retrain cycle using current volume, not the volume from when the
choice was first made. Quantization's accuracy cost is usually small but not zero; validate
the specific quantized model against a held-out set before shipping, since "usually fine"
is not the same as verified fine for this model.
Unlock Full Question Bank
Get access to all 10 Performance Cost Optimization & Resource Efficiency interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.