AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals

Capacity Planning for End-to-End AI Systems: Traffic, Storage, and Compute

Question 16 of 47 · Updated

On this page

Capacity planning translates a user-facing workload and its service objectives into a resource envelope for every stage of an AI application. Begin with logical demand and its peak distribution, propagate demand through branches, fan-out, caching and retries, estimate concurrent work, size storage and network traffic, and benchmark CPU and GPU deployment units under the required latency and quality constraints. Reserve headroom for bursts and failures, compute the economics of the complete deployment, and validate the estimate with representative load tests.

Original curriculum question: How do you estimate traffic, storage, throughput, latency and compute requirements for an end-to-end AI system?

Module 01 — Architecture fundamentals | ASD-003. ASD-001 selected the architecture family; ASD-002 established business objectives, service-level objectives and acceptance criteria. ASD-003 takes those inputs and constructs an end-to-end resource ledger. The existing MLOps compute/storage and autoscaling lessons, LLM GPU-capacity and inference-cost lesson, and RAG index memory/storage lessons are prerequisites for deeper component-specific analysis. This lesson focuses on demand propagation across heterogeneous services, reconciling capacity units, queueing, network and storage peaks, failure domains, background jobs and whole-system cost. The Netflix distributed training case concerns training architecture rather than the integrated workload sized here. ASD-004 will compare execution modes; later infrastructure lessons will address detailed scheduling, cross-service budgets and attribution.

All workload counts, hardware configurations, assumed benchmark results and prices below are fictional educational inputs. They are not actual vendor prices, measured production capacity or an approved infrastructure configuration. Only the small Python calculator was executed.

1. Establish a workload contract#

A request could mean an HTTP call, a completed customer task, an embedding operation, a retrieval query or an inference attempt. These are different units. Counting logical customer tasks alone can substantially underestimate internal work.

Consider a fictional read-only support system. Some requests need a deterministic order lookup; others need retrieval and language generation. A background ingestion service refreshes documents and embeddings, and an evaluation process samples outcomes.

Workload inputIllustrative assumption
Offered logical tasks864,000 per day
Peak factor over selected interval5 times daily mean
Direct route40% of tasks
Retrieval-generation route60% of tasks
Attempt amplification1.1 AI attempts per logical AI task
Search fan-outTwo queries per AI attempt
Mean tokens per AI attempt1,200 input; 200 output
Mean admitted AI-stage residence time3 seconds
End-to-end latency objectiveAI-route p95 under 5 seconds; direct-route p95 under 300 ms
Audit record size2,000 bytes per logical task
Retention30 days, two independently budgeted audit copies

The attempt multiplier assumes, for example, at most one additional attempt on 10% of AI tasks. We conservatively count two searches for every attempt, including retries. Real implementations may reuse retrieval evidence or retry individual dependencies independently. Replace assumptions with measurements from the actual request graph. A peak factor requires a defined interval: a five-minute peak is not a one-second burst. Forecast a range for launch traffic, regional and seasonal concentration, growth, dependency outages and changing input mix. Count offered work separately from admitted, successful, rejected and cancelled work.

2. Draw the demand graph before selecting machines#

Loading diagram…

For each stage record the input unit, conditional branch probability, number of operations per parent task, cache-miss rate, attempt count, work per operation, deadline, output size and resource pool. Expected demand at a child is the parent arrival rate times the conditional expected invocations. At a join, add only compatible non-overlapping contributions. For a cache with a measured 80% hit rate, 100 eligible lookups/s generate about 20 backend misses/s in the stable mean, but cold starts and synchronized expiration can create very different peaks.

Retries amplify load, especially under correlated failures. The geometric formula 1/(1-p) for expected attempts assumes constant independent failure probability p and unlimited retries; it is not a recommendation to retry indefinitely. Use bounded attempts, deadlines, backoff, jitter and safe retry semantics. Measure each dependency independently and account for cancelled work and cleanup.

The graph is more useful than a single QPS number: the API sees logical tasks, the retrieval service sees fan-out, inference sees amplified attempts, the audit store sees logical events, and the background indexer sees document changes.

3. Average traffic, peak QPS and internal throughput#

For a full 24-hour day:

average tasks/s = daily logical tasks / 86400
peak tasks/s = average tasks/s × peak factor
stage operations/s = upstream task rate × expected stage operations per task

The example yields 864,000/86,400 = 10 average tasks/s, and 10×5 = 50 peak tasks/s. At peak, direct demand is 50×0.4 = 20 tasks/s. AI-route demand is 50×0.6 = 30 logical tasks/s, expanded to 30×1.1 = 33 AI attempts/s. Retrieval sees 33×2 = 66 searches/s. If the same mix holds at average load, generation sees 6.6 attempts/s and retrieval 13.2/s.

Do not confuse active users with arrival rate. Ten thousand users each issuing one request per minute average about 167 requests/s under the assumed activity pattern. A single automated client can produce hundreds of requests per second. Measure requests and connection state separately.

The peak forecast should be built from observed hour/minute arrival distributions and short-burst traces. Include joint workload shifts: traffic may peak precisely when prompts grow longer and dependencies retry more often. Add an explicit growth scenario rather than silently multiplying by arbitrary safety factors at every stage.

4. Concurrency and Little's Law#

Little's Law states that for stable systems under appropriate long-run averaging conditions, mean occupancy L equals effective arrival or throughput rate lambda times mean residence time W:

L = lambda × W
requests = requests/second × seconds

If all 33 AI attempts/s are admitted, and mean residence time in the measured AI stage is three seconds, mean in-flight work is 99 attempts. At a five-second mean with unchanged admitted rate, it grows to 165. If the direct lookup stage admits 20/s with a mean residence time of 80 ms, its mean occupancy is 1.6. Fractional occupancy is a long-run average, not a fractional actual request.

Use consistent boundaries. If W includes waiting plus execution, L includes queued and executing work. If W measures execution only, L describes that execution boundary. Do not combine offered requests rejected before admission with admitted residence times.

Little's Law is not a percentile calculation. Peak QPS times p95 latency is not necessarily p95 concurrency. It does not establish a finite steady-state occupancy for a queue whose arrival rate persistently exceeds capacity. Use realistic load replay and queueing analysis for tail occupancy.

For asynchronous work, 200 admitted jobs/hour with a mean residence time of 30 minutes implies a mean of 100 outstanding jobs under stable conditions. This does not mean 100 workers are required: some jobs may be waiting, or may use multiple workers. Model each resource boundary separately.

5. Workload distributions and token throughput#

Requests differ greatly in computational cost. In LLM inference, input/output lengths, decoding configuration, cache reuse and tool rounds matter. In search, filters, shard fan-out, index locality and candidate count matter. In multimodal tasks, resolution, frame count and audio duration matter.

A two-class illustrative generation distribution:

ClassShareInput tokensOutput tokens
Short question80%800100
Long document question20%2,800600

The means are 1,200 input tokens and 200 output tokens. At 33 attempts/s this gives 39,600 input tokens/s and 6,600 output tokens/s. If the long-request share increases to 40%, mean lengths become 1,600 input and 300 output, increasing demand to 52,800 and 9,900 tokens/s respectively, without a QPS increase. Benchmark the joint distribution, not only average length.

At 864,000 tasks/day, expected attempts are 864,000×0.6×1.1 = 570,240/day. Assuming full mean token work on every attempt, this is 684,288,000 input and 114,048,000 output tokens/day. Aborted attempts may consume less or different work; measure actual billing and compute.

The peak corresponds to 1,980 attempts/minute, 2,376,000 input tokens/minute and 396,000 output tokens/minute. Hosted services can enforce different request, token and concurrency quotas, with varying burst behavior. Verify actual contractual limits. Input and output tokens are not equivalent resource units: prefill and decode stress different parts of the accelerator, and batching or cache reuse changes computation.

Goodput is successful work satisfying a specified SLO per time unit. Keep it distinct from offered request throughput and raw token throughput. A benchmark of six good responses/s is not automatically six offered attempts/s if the test drops some requests. Here the replica-sizing inputs are sustainable offered rates measured under an acceptable success/deadline contract. Actual hardware benchmarking is required to establish those rates.

6. CPU sizing and service demand#

For an approximately CPU-bound stage:

busy CPU-core equivalents = operation rate × CPU-seconds per operation
initial allocated cores ≈ busy cores / target CPU utilization

If each of 50 API tasks/s uses 12 ms of CPU time, the workload consumes about 0.6 fully busy core equivalents. At 60% target utilization, the arithmetic lower-bound allocation is one core. CPU time is processor execution, not elapsed time including waiting for other services. The estimate omits TLS, runtime, memory, I/O, locks, uneven load and resilience.

Assume one proposed one-vCPU API replica sustains 30 offered tasks/s within its measured contract. A planning factor of 0.8 gives 24 tasks/s. The demand requires ceil(50/24)=3 replicas; four are needed to preserve the target envelope after losing one replica. Initial allocation is four vCPUs plus sidecars and platform overhead.

At 66 retrieval queries/s and an invented 8 ms CPU demand per query, busy CPU is 0.528 core-equivalents. But retrieval might be constrained by RAM, random reads, filters or tail latency rather than CPU alone. Assume one tested deployment unit with two vCPUs and 32 GiB RAM sustains 40 searches/s. At 75% of that rate, each contributes 30/s; three cover 66/s and four allow one loss. The initial allocation is eight vCPUs and 128 GiB RAM across replicas. Neither the memory allocation nor the benchmark throughput is a real measurement here.

Profile document parsing, tokenization, compression, image preprocessing and serialization separately. CPU utilization metrics may use different denominators across containers, hosts and processes. Compare real resource limits, contention and sustained throughput under load.

7. GPU and accelerator memory sizing#

Check memory fit before estimating throughput. Approximate raw model-weight bytes as parameter count times bytes per stored parameter. An invented dense 8-billion-parameter transformer with BF16 weights requires about 16 GB decimal, or 14.90 GiB. Quantized weights need additional metadata and compatible kernels; resident expert weights in a mixture-of-experts model may be much larger than the activated parameter subset.

For an ordinary decoder transformer with grouped-query attention and uncompressed key/value tensors, the simplified KV cache payload is:

KV bytes/token = 2 × layer count × KV heads × head dimension × bytes/element

For 32 layers, eight KV heads, head dimension 128 and two bytes per element:

2 × 32 × 8 × 128 × 2 = 131072 bytes/token = 128 KiB/token
32 sequences × 2048 resident tokens × 128 KiB/token = 8 GiB

Add 4 GiB illustrative runtime/workspace to 14.90 GiB weights and 8 GiB KV cache. Subtotal is 26.90 GiB. If a device exposes 48 GiB and the plan reserves 20% (9.6 GiB), the usable planning envelope is 38.4 GiB; the synthetic fit test passes.

This is not a guarantee. Actual memory includes paging/block rounding, allocator fragmentation, attention workspaces, CUDA graphs, prefix caches, draft models, speculative decoding and other device allocations. Context length and output growth determine the live KV footprint. Use the actual model configuration and serving runtime, not a universal memory multiplier. In training, gradients, optimizer state and activations have different memory requirements from inference.

The 32-sequence limit is an assumed per-replica envelope, not inferred from the 99 stage-wide in-flight attempts. Some attempts are waiting rather than actively consuming KV cache. Monitor admitted sequences and cached tokens per device. For a model that needs multiple GPUs, size a working parallel replica as the unit; include topology and communication, and do not assume ideal sharding or linear scaling.

8. GPU throughput and batching#

Assume a proposed one-GPU replica sustains six offered AI attempts/s with the stated representative workload and acceptable latency/error behavior. At a 75% planning factor, capacity is 4.5 attempts/s per replica.

demand replicas = ceil(33 / 4.5) = 8
installed replicas = 8 + 1 spare = 9
GPU count = 9 × 1 GPU/replica = 9

After one loss, eight replicas provide 36 attempts/s of planned capacity. Eight installed replicas without a spare would fall to seven and provide only 31.5/s at that planning factor. A benchmarked offered-rate envelope is distinct from physical GPU compute utilization; 75% of tested capacity does not imply exactly 75% GPU utilization.

Batching can improve utilization but introduce queueing and memory overhead. Static batching waits for a configured group; dynamic batching chooses groups under size/time limits; continuous or iteration-level batching admits and retires sequences during generation. Which technique helps depends on the model and workload. Measure time to first token, inter-token latency, p95/p99 completion, success fraction, peak memory and useful goodput. More raw tokens/s is not an improvement if the application misses deadlines or produces invalid results.

At 4.5 admitted attempts/s per replica and three seconds mean residence, mean occupancy at that boundary is 13.5. Do not interpret that as active batch size or tail occupancy. Distinguish time spent queued, in prefill, decoding, and postprocessing. GPU throughput is a benchmark result, not obtained simply by dividing theoretical FLOPS by parameter count.

9. Storage and retention: construct a ledger#

For a steady append-only stream:

retained bytes = events/day × stored bytes/event × retention days × copies

The example stores one 2,000-byte event per logical task: 864,000×2,000 = 1.728 GB/day. Thirty days is 51.84 GB per copy. Two independently budgeted copies total 103.68 GB. Add row/index overhead, tracing events, ingest charges and compression according to measurement. Prefer minimized audit events over unnecessary storage of prompts or personal data.

The search index contains five million chunks, each with one 768-dimensional float32 vector:

5,000,000 × 768 × 4 = 15,360,000,000 bytes = 15.36 GB

With a hypothetical 1.5× index/metadata factor, one full copy occupies 23.04 GB. Four retrieval replicas each hosting a complete copy need 92.16 GB. In a sharded system count the actual shard placement and replication instead. This is persistent storage, not necessarily the resident memory footprint. Index implementations differ, and the overhead factor needs validation on a representative index. Separate raw document storage from derived index storage and ensure metadata is not double counted.

CategoryIllustrative steady bytes (decimal GB)
Task audit events, two copies103.68
Retrieval index, four copies92.16
Source documents100.00
Three 16 GB model weight artifacts48.00
Derived evaluation snapshots20.00
Separately budgeted recovery backups60.00
Subtotal423.84

An overlapping full index rebuild adds up to 92.16 GB, giving 516 GB; 25% extra reserve yields 645 GB in an illustrative aggregate storage ledger. In practice different stores have distinct capacity and billing domains; ensure each pool can accommodate its own maintenance peak. Add database state, temporary processing, replication, logs and backups not covered in the table. A managed service may already include redundancy in its price; do not bill it again as an independent copy.

GB means 10^9 bytes; GiB means 2^30 bytes. SSD, system RAM, accelerator VRAM and object storage are not interchangeable. Storage retention requires business need, security and deletion rules; inexpensive bytes do not justify indefinite retention.

10. Network bandwidth and dependencies#

Estimate each directed link independently:

payload bytes/s = messages/s × mean payload bytes
payload bits/s = payload bytes/s × 8

At 50 tasks/s with 2 KB inbound and 6 KB outbound, public API payload is 100 KB/s inbound (0.8 Mbps) and 300 KB/s outbound (2.4 Mbps), or 3.2 Mbps aggregate. At 66 retrieval queries/s with a 1 KB request and 12 KB result, aggregate payload is 858 KB/s or 6.864 Mbps; the two directions are 0.528 and 6.336 Mbps. At 33 generation attempts/s with an 8 KB prompt payload and 2 KB result, aggregate is 330 KB/s or 2.64 Mbps. These are invented serialization sizes, not derived from a universal tokens-to-bytes conversion.

Use full-duplex direction-specific capacity rather than compare a bidirectional sum to a link rate without defining the convention. Add protocols, streaming frames, TLS, retries, replication, inter-zone traffic and egress charges. Connection counts, packet rates, load-balancer limits and network tail latency can constrain a service with modest payload bandwidth.

Model distribution can dwarf serving traffic. Nine full copies of a 16 GB artifact sent independently from one origin total 144 GB. To finish in five minutes requires 480 MB/s, or 3.84 Gbps average raw origin egress, before overhead. Staggering, regional caches or hierarchical distribution changes the source bottleneck.

Account for database and external service quotas. For example, a shared backend receiving one authorization lookup per 50 peak tasks/s plus two reads per 20 direct tasks/s sees 90 read-like operations/s, assuming no caching or separate dependency. Actual query complexity, writes, transactions, index selectivity and connection behavior need benchmark evidence.

11. Latency budgets and the critical path#

Start with the user-visible objective, then allocate engineering deadlines to the stages. For a five-second AI-route completion budget:

StageIllustrative allocation
API, authentication and routing100 ms
Retrieval and evidence assembly400 ms
Admission, queue, prefill and decode3,800 ms
Validation and response200 ms
Unallocated contingency500 ms
Total5,000 ms
Loading diagram…

The last node represents reserved slack, not an executable delay. These are allocations, not component p95 measurements. Adding p95 values does not establish end-to-end p95. Parallel mandatory operations contribute their maximum completion time to the critical path, not their sum. If k independent identical branches have latency CDF F(t), the maximum has CDF F(t)^k, but real dependencies are often correlated. Measure the complete workflow.

For streaming, distinguish first-token latency, inter-token cadence and final completion. Allocate separate direct-route objectives rather than allow an overall mean to hide the user experience of either route. Downstream calls must respect a common deadline; optional tasks cannot consume the whole budget. ASD-060 covers detailed cross-service budget propagation; this lesson establishes the resource envelope needed to meet the budget.

12. Queueing, utilization, headroom and failures#

In an ideal M/M/1 queue (Poisson arrivals, exponential service time, one server), mean residence time is 1/(mu-lambda) when lambda is below mu. With service rate 10/s, a 5/s arrival rate yields 0.2 s mean residence; at 9/s, mean rises to 1 s. This is illustrative queueing theory, not a fitted model for batched inference. Near saturation, wait time can grow faster than throughput.

Suppose a 60-second burst offers 50 generation attempts/s while only 36/s can be served. A simple fluid approximation with no rejection or expiry accumulates (50-36)×60=840 attempts. If arrivals fall to 20/s, net drain is 16/s and recovery takes 52.5 seconds. Many interactive requests would miss deadlines. Bounded queues, admission control and approved fallback are required; adding unlimited waiting does not create capacity.

Reserve headroom for traffic variation, cold caches, rolling deployments, failures and scaling delay. N+1 protects only the specified one-replica-loss scenario. If several replicas share a node, zone, or network dependency, one failure may remove multiple units. Check every required failure domain. Headroom relative to benchmark throughput is not equal to CPU or GPU occupancy; track memory, bandwidth, I/O, queue and useful goodput independently.

13. Coordinated stage capacity calculation#

For an independently scalable homogeneous stage:

installed replicas =
  ceil(peak offered stage rate / (tested offered rate × planning factor))
  + replicas lost in specified failure scenario
StagePeak offered rateAssumed tested ratePlanning factorPlanned rate per unitInstalled replicas including one spare
API50/s30/s0.8024/s4
Retrieval66/s40/s0.7530/s4
Generation33/s6/s0.754.5/s9

After one loss within each respective stage, planned surviving rates are 72 API tasks/s, 90 searches/s and 36 generation attempts/s. Compare in a common unit: each logical task generates on average 1.32 searches and 0.66 generation attempts under the fixed mix. The equivalent logical capacities are 72, 90/1.32 ≈ 68.18, and 36/0.66 ≈ 54.55 tasks/s. Generation is the tightest of these modeled stages. This is not a complete service guarantee: other dependencies and shared capacity can be tighter.

If the AI-route share rises to 80% with unchanged attempts and benchmark mix, peak generation becomes 44/s and search 88/s. Generation needs ceil(44/4.5)+1 = 11 replicas; retrieval needs ceil(88/30)+1 = 4. API demand is unchanged. Rebenchmark if route shifts also change token distributions or cache behavior.

14. Tested implementation: workload and capacity calculator#

This standard-library Python example implements the fictional sizing model, checks input validity, and calculates mean concurrency, retained audit bytes, and the replica counts using a specified failure allowance. It is an arithmetic helper, not a queue simulator or hardware benchmark.

PYTHON
from math import ceil, isfinite from hashlib import md5 def replicas(rate, tested_rate, load=.75, failures=1): if not all(map(isfinite, (rate, tested_rate, load))): raise ValueError('nonfinite capacity') if rate < 0 or tested_rate <= 0 or not 0 < load <= 1: raise ValueError('invalid capacity') if type(failures) is not int or failures < 0: raise ValueError('invalid failure allowance') return ceil(rate / (tested_rate * load)) + failures def sizing(daily=864000, peak_factor=5, ai_share=.6, attempts=1.1): if not all(map(isfinite, (daily, peak_factor, ai_share, attempts))): raise ValueError('nonfinite workload') if daily < 0 or peak_factor < 1 or not 0 <= ai_share <= 1 or attempts < 1: raise ValueError('invalid workload') avg = daily / 86400 peak = avg * peak_factor llm = peak * ai_share * attempts retrieval = llm * 2 return dict(avg=avg, peak=peak, llm=llm, retrieval=retrieval, input_tps=llm*1200, output_tps=llm*200, inflight=llm*3, api_replicas=replicas(peak, 30, .8), search_replicas=replicas(retrieval, 40), gpu_replicas=replicas(llm, 6), log_bytes=daily*2000*30*2) r = sizing() assert r['avg'] == 10 and r['peak'] == 50 assert abs(r['llm']-33) < 1e-9 and abs(r['retrieval']-66) < 1e-9 assert abs(r['input_tps']-39600) < 1e-8 assert abs(r['output_tps']-6600) < 1e-8 assert abs(r['inflight']-99) < 1e-8 assert r['api_replicas'] == 4 assert r['search_replicas'] == 4 assert r['gpu_replicas'] == 9 assert r['log_bytes'] == 103_680_000_000 assert replicas(9, 6) == 3 assert replicas(0, 6, failures=0) == 0 assert sizing(ai_share=0)['llm'] == 0 for fn in [lambda: sizing(ai_share=1.1), lambda: sizing(attempts=.9), lambda: replicas(3, 0), lambda: replicas(float('nan'), 6)]: try: fn() except ValueError: pass else: raise AssertionError('invalid input accepted') print('16 checks passed')

Observed execution on Python 3.13.5:

16 checks passed

The twelve direct assertions cover average/peak rates, internal fan-out, input/output token rates, mean concurrency, the three stage allocations, log storage, exact-boundary sizing, zero demand and zero AI share. Four additional invalid-input cases verify rejection. The unused hashlib import does not affect results. With zero stage demand and a one-spare policy, the function still plans one replica; explicitly set the failure allowance to zero for a disabled route. Production implementations should use suitable exact arithmetic for integer thresholds near floating-point boundaries and reject unreasonable inputs that could overflow intermediate operations. The helper assumes fixed mix and independent homogeneous capacity. Tests establish arithmetic behavior for the fixtures, not real production throughput.

15. Background processing and training capacity#

Do not let online serving capacity conceal offline work. Size embedding refresh, data transformations, training, evaluation, snapshots, backup and maintenance using work volume and completion deadlines.

For 500,000 new or changed chunks to embed in four hours, required average throughput is 500,000/14,400 ≈ 34.72 chunks/s. If a tested worker processes 12 chunks/s and the plan uses 75% of that rate, each contributes nine/s. Four workers provide 36/s. Five are needed to maintain that capacity after a single worker loss for the entire interval, assuming independent workers, uniform workload and no restart overhead. Include queue setup, retries, write/index throughput and reconciliation; the actual job may need more.

If a training job processes four million samples over three epochs at a measured cluster rate of 5,000 samples/s, pure sample processing is 12 million/5,000 = 2,400 seconds, or 40 minutes. Add startup, validation, checkpointing, communication and restart overhead. Scaling is rarely linear, and throughput depends on the actual sample and model. The previous distributed training article covers training architecture; here it is one workload in the total capacity ledger.

Separate online and offline resource pools or validate shared scheduling, memory isolation, deadline admission and preemption compatibility. A background GPU job or model download can harm serving even when daily-average resource use looks small. Plan for overlapping rebuilds and peak interactive traffic rather than assuming background work occurs only when users are absent.

16. Autoscaling and readiness#

An autoscaler needs a demand signal tied to the bottleneck, a desired envelope, minimum/maximum capacity, readiness definition and scale reaction policy.

Loading diagram…

Useful signals include offered request rate and CPU work at the gateway; search QPS, index residency and tail latency at retrieval; waiting tokens, active sequences, KV occupancy, TTFT and deadline-compliant goodput at inference; remaining work and deadline slack for background jobs; and storage exhaustion horizon for persistent data.

New GPU replicas may wait for available hardware, download weights, initialize and warm up. Search replicas may load large indexes. Measure actual readiness time, including its tail. A 60-second surge cannot depend on a replica that takes minutes to become ready. Use forecast-aware prewarming, minimum capacity, bounded queueing and approved degradation. Scale-down must drain streams and preserve task state. Stabilization and hysteresis reduce oscillation. Respect dependency quotas and placement limits; scaling the API into a saturated database can make an outage worse.

17. Infrastructure cost and sensitivity#

Use a resource ledger rather than a single model-call price:

total attributable cost =
  sum(resource units × billed hours × hourly unit rate)
  + storage + I/O + network + provider fees
  + background work + monitoring + review + attributable operations

unit cost = total attributable cost / observed successful logical tasks

Fictional hourly rates for the fixed peak deployment:

ResourceUnitsInvented hourly rateHourly subtotal
API4$0.08$0.32
Retrieval4$0.40$1.60
GPU9$2.00$18.00
Total$19.92

Over 30 days (720 hours) this replica-only subtotal is $14,342.40. There are 25.92 million offered tasks at the stated volume. If 97% satisfy the whole task-success contract, there are 25.1424 million successful tasks. The subtotal is about $0.0005704 per successful task, or $0.5704 per thousand successes. Do not use theoretical maximum capacity as the cost denominator, nor present this subtotal as fully loaded system cost.

For comparison, fictional hosted rates of $0.50 per million input tokens and $2 per million output tokens yield 684.288×0.50 + 114.048×2 = $570.24/day, or $17,107.20 per 30 days, for the token component only. This is not a real quote or a like-for-like total. Compare quality, quota, latency, privacy, cache billing, failed attempts, operational burden and background work under the same task contract. Do not charge both self-hosted GPU generation and hosted token fees to the same path unless both are incurred.

For a simple autoscaling sensitivity, one hour/day at 50 QPS and the remaining 23 hours at about 8.26 QPS gives a 10 QPS daily average. The low interval needs three GPU replicas under the fixed mix and one-spare policy; the peak needs nine. An ideal step schedule uses 9×1+3×23=78 GPU-hours/day versus 216 always-on GPU-hours. This is an optimistic arithmetic illustration before startup windows, reservations, bursts and minimums, not measured savings.

Estimate actual storage by tier, read/write charges, egress and cross-zone traffic, database/cache services, provider quotas, evaluation, trace ingestion, artifact transfer, recovery and human review. Obtain current contractual rates before procurement. State how shared infrastructure costs are allocated.

18. Validate the model before committing capacity#

An estimate is a hypothesis. Use a progressive evidence plan:

  1. Benchmark representative inputs and each deployment unit at multiple offered rates. Record success, errors, rejects, p95/p99 latency, queueing and peak memory.
  2. Replay correlated realistic workload classes through the complete system, including authorization, retrieval, generation, validation, streaming and background traffic.
  3. Test cold caches, long prompts, bursts, dependency failures, rolling deployment, rebuilds, replica loss and required zone/node failure domains.
  4. Measure scaling readiness and queue drainage; verify that approved admission and fallback preserve security and correctness.
  5. Compare actual stage counts, token work, occupancy, resource peaks and network traffic to the ledger.
  6. Recalculate cost per successful task from metered consumption and complete outcomes. Update forecast and owner-approved resource thresholds.

Open-loop tests issue offered arrivals according to a schedule even when the service slows. Closed-loop clients may issue fewer requests when responses slow down; that is a different workload. A poorly designed load generator can hide latency during pauses through coordinated omission. Report offered, admitted, completed, rejected, cancelled and SLO-compliant counts separately. Check quality when changing batching, context limits, retrieval settings, quantization or fallback.

Evaluate sensitivity to route share, long-request fraction, cache misses, retry amplification, index growth, retention, device rates and failure-domain policy. Schedule capacity reviews when assumptions drift, not merely after outages.

19. Common mistakes and architecture trade-offs#

MistakeBetter approach
Size only from average daily QPSUse defined peak intervals and burst distributions
Assume one task equals one model callPropagate conditional branches, fan-out and attempts
Multiply QPS by p95 and call it p95 concurrencyUse consistent mean Little's Law boundaries; measure tail occupancy
Treat input and output tokens as identical computeBenchmark prefill/decode on the joint length distribution
Size a GPU from raw weights aloneInclude live KV state, runtime, fragmentation and topology
Equate CPU time with wall latencyMeasure actual CPU service demand
Use maximum raw throughput as production capacityBenchmark sustainable offered load under the success/deadline contract
Ignore shared failure domainsCalculate surviving capacity in specified failures
Add component percentilesAllocate deadlines; measure full-path latency
Forget copies, rebuilds and retentionMaintain a per-store capacity ledger
Size only public network trafficCount internal fan-out, replication and model transfers
Assume scaling is instantaneousInclude readiness delay and admission policy
Quote cost at theoretical maximum utilizationUse actual good task outcomes and billed usage

More headroom improves resilience but increases idle expense. More batching may increase throughput at the cost of latency. Caching saves compute but requires correct tenant isolation, version and freshness semantics. Smaller models or quantization can reduce resource needs but require quality verification. Dedicated pools protect critical workloads; shared pools may save resources if isolation and deadlines are demonstrably maintained. Trade-offs should be expressed using the acceptance criteria from ASD-002.

20. Interview-ready answer#

I would define the logical workload, quality and latency targets, traffic peaks and request mix, then draw a demand graph showing how user tasks become internal operations through fan-out, branch selection, caching and retries. I would estimate mean in-flight work using Little's Law at consistent boundaries, and distinguish offered requests, accepted work and successful goodput. For generative workloads I would calculate input and output token rates separately and preserve the joint length distribution.

I would estimate CPU service demand, accelerator memory including model weights and KV cache, storage including copies, retention and rebuild peaks, and network bandwidth for each link. I would benchmark actual deployment units under the intended workload, size integer replica counts with headroom and the required surviving failure domains, and verify latency budgets through full-path tests. I would account for background jobs, scale-up readiness, queueing and downstream constraints.

Finally I would combine the resources into a cost ledger, calculate total attributable cost per successful logical task, test traffic and failure scenarios and revise assumptions based on evidence. Capacity planning does not provide an exact hardware prediction from QPS alone; it produces an explicit, testable resource envelope that preserves the application's business and service objectives.

References and research transparency#

The authorized offline research exception was applied. These references identify established research and technical documentation; current content, URL availability and the current Supabase changelog were not live-verified. The three diagrams use standard triple-backtick Mermaid fences and were structurally reviewed; Mermaid parser execution and frontend rendering were not verified. The Python calculator was locally executed on Python 3.13.5, with 16 checks passing. All workload and benchmark assumptions and prices are illustrative; no real GPU or full-stack load test was performed.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython