Latency, throughput and cost
Measure latency and throughput separately
Latency is the elapsed time of one request. In a streaming text service, time to first token (TTFT) measures the wait from request start to the first generated token observed by the client; full latency ends at completion. Prefill processes the prompt before generation; decoding extends the output. Throughput measures work per shared unit of wall-clock time, such as completed requests per second or output tokens per second. Two overlapping requests can each take close to one second while the service completes two in that second. The synthetic observation window below lasts 1,000 ms and contains two completed streaming requests with 40 and 60 output tokens. The average TTFT is 250 ms, average full latency 850 ms, and aggregate throughput is two requests/s and 100 output tokens/s. Do not divide output tokens by the sum of overlapping latencies to estimate service throughput. Fraction preserves exact ratios. An empty window has zero completed throughput but undefined average latency. The fixture assumes both requests start and finish inside the window, and counts no partial tokens.
from fractions import Fraction
def window_metrics(records, window_ms): # All records are completed within one shared observation window. if type(window_ms) is not int or window_ms <= 0: raise ValueError("positive observation window required") for ttft, latency, output_tokens in records: if any(type(x) is not int for x in (ttft, latency, output_tokens)) or not ( 0 <= ttft <= latency <= window_ms and output_tokens > 0): raise ValueError("invalid completed streaming record") n = len(records) return (Fraction(sum(r[0] for r in records), n) if n else None, Fraction(sum(r[1] for r in records), n) if n else None, Fraction(n * 1000, window_ms), Fraction(sum(r[2] for r in records) * 1000, window_ms))
print(window_metrics([(200, 800, 40), (300, 900, 60)], 1000))print(window_metrics([], 1000))Understand batching and concurrency
Batching combines requests to improve accelerator utilization. A larger batch can raise aggregate throughput while increasing queue delay or per-user latency and consuming more cache memory. Continuous batching can admit or finish requests at different generation steps; it does not guarantee lower latency. Concurrency is the number of simultaneous in-flight requests, not necessarily batch size. Compare identical input/output length distributions, warm versus cold starts, concurrency and deadlines; record sample counts and p50/p95/p99 where enough observations exist. For streaming, track inter-token or inter-chunk intervals separately; a chunk can contain multiple tokens. Distinguish client end-to-end latency from server compute time. Include timeout and failed request counts instead of reporting successful latency alone. No actual benchmark is performed in this lesson.
Compute cost per completed task
Compare deployment modes on the same quality-approved task set and time window. A token API may charge for input and output separately; a managed endpoint may charge per allocated node-hour, including idle time; a local device has amortized purchase or rental, electricity, maintenance and operator costs. Our hypothetical rates are integer USD per million tokens or per node-hour. Extras are explicit microdollars (one millionth of a dollar) for storage, egress, human review and evaluation. Sum costs for all attempts including failures, not only final successful calls; missing usage makes the estimate incomplete. Divide by tasks that actually completed under the chosen acceptance criteria. If none completed, return None rather than zero or infinity. For 100 accepted tasks the API example costs $0.60 in total, or $0.006 per task; the local and managed examples use one allocated hour at illustrative $1 and $2 respectively, giving $0.013 and $0.023 per task. These are invented inputs, not prices, savings forecasts or evidence that any route can satisfy the same workload. The local and managed examples include zero token-metered charge; avoid double counting usage billed within the hourly rate.
from fractions import Fraction
def task_cost(completed, attempts, input_rate, output_rate, node_minutes, node_hour_rate, extras_micro): # All rates in hypothetical integer USD; extras in microdollars. if any(type(x) is not int or x < 0 for x in (completed, input_rate, output_rate, node_minutes, node_hour_rate, extras_micro)): raise ValueError("invalid costs or counts") if any(type(i) is not int or type(o) is not int or min(i, o) < 0 for i, o in attempts): raise ValueError("invalid usage") total = Fraction(sum(i * input_rate + o * output_rate for i, o in attempts) + extras_micro, 1_000_000) + Fraction(node_minutes * node_hour_rate, 60) return total, total / completed if completed else None
# Same 100 completed tasks; usage includes retry and failed attempts.print(task_cost(100, [(100_000, 20_000)], 2, 5, 0, 0, 300_000))print(task_cost(100, [], 0, 0, 60, 1, 300_000))print(task_cost(100, [], 0, 0, 60, 2, 300_000))print(task_cost(0, [(1000, 0)], 2, 5, 0, 0, 0))Select a deployment under constraints
An API reduces infrastructure ownership but requires approved external data processing and attention to provider limits. A local deployment may offer control over data movement, but it still needs security, monitoring, model licensing and capacity planning. Managed endpoints provide infrastructure and scaling abstractions with service-specific minimum capacity, startup, networking and billing rules. Include idle allocated time, replicas, storage, transfer, retries, review and evaluation, plus capacity constraints. Compare low, expected and peak demand scenarios; fixed cost per task grows when demand falls. Require comparable correctness, safety and latency before interpreting cost differences. A cheaper route that fails the quality gate is not a valid substitute. Consult current rate cards and reconcile real invoices; this chapter does not establish actual platform charges.
Practice and common mistakes
Double node-minutes while keeping completed tasks constant and explain the cost change. Repeat with half the completed tasks, holding all attempt costs fixed; per-task cost doubles. Add a failed attempt to the API fixture and preserve the completed denominator. Record a missing usage value as unknown in a worksheet rather than passing it into the integer calculator. Explain the difference between 100 output tokens/s for the whole observation window and per-user decoding rate. Do not assume equal quality, turn a hypothetical cost into a savings claim, average independent percentile statistics or measure only the fastest requests. Chapter 55 will apply these trade-offs to deployment architecture.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Latency, throughput and cost quiz
Assess memory estimation, inference performance and cost accounting.
What is aggregate output throughput for 100 completed output tokens in a one-second shared window?
Can batching increase throughput while worsening latency?
What is the API fixture cost per completed task?
What if no tasks complete but costs are incurred?
Which comparison supports a deployment decision?