Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 19: Evaluation and Observability

Week 19 / Lesson 3

Tracing latency, tokens, and failures

Link measured request stages and identify the source of a cost or latency increase.

Section 3.1 1 of 7

Overview

Focus

Link measured request stages and identify the source of a cost or latency increase.

Your route through the lesson

  • 3.2 Traces and spans across model and tool boundaries
  • 3.3 Token accounting, prices, and local resource use
  • 3.4 Latency distributions, retries, and bottlenecks
  • 3.5 Put it into practice
  • 3.6 Guided comparison
  • 3.7 A retry causing a tail-latency spike

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 7

Traces and spans across model and tool boundaries

Focus

Link request stages with trace identifiers and preserve retry attempts as separate spans.

A trace is the record of one request across components. A span is a timed unit of work within that trace, such as retrieval, model generation, or a tool call. A trace identifier links related spans; a parent identifier expresses nesting. Generate an identifier at admission and propagate it across boundaries instead of guessing relationships from nearby timestamps.

Imagine request R retrieves a document, invokes a model, then calls a ticket tool twice after a timeout. Record four spans with one trace identifier and distinct attempt numbers. The retry is not a second user request. Include status, release manifest, and operation identifier so the record can explain both latency and effects. Avoid putting secrets or full private prompts into ordinary diagnostic logs.

Use a monotonic clock for durations. Python time.perf_counter() returns a high-resolution counter whose differences measure elapsed time without relying on wall-clock calendar adjustments. Store wall-clock timestamps separately when correlating an incident timeline. A duration of twenty milliseconds means elapsed work at this boundary; it does not reveal whether an external service spent that time computing, waiting, or transmitting unless that service supplies more detailed measurements.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. One request calls a tool twice after timeout. How should attempts be linked?
2. Which Python clock is appropriate for elapsed local duration?
3. A diagnostic log needs correlation without exposing credentials. What should it store?

Section 3.3 3 of 7

Token accounting, prices, and local resource use

Focus

Keep token usage, monetary estimates, and local resource measurements distinct.

Token accounting records input and output units using the actual model's tokenizer. A tokenizer maps text to the model's discrete units; character counts are not reliable substitutes. Include cached-token categories and retries when the runtime exposes them. An application's visible answer can be short while repeated prompts consume substantial input tokens.

A cost estimate multiplies usage by explicitly dated price assumptions. If hypothetical input costs two currency units per million tokens and output costs six, then one thousand input tokens and one hundred output tokens cost (1000×2 + 100×6)/1,000,000, or 0.0026 units. This is an arithmetic example, not a current provider quote. Requests, storage, network transfer, and minimum charges may add other terms.

Local execution has no per-token invoice by default, but it still consumes processor time, memory, energy, and operator effort. Record hardware, runtime, quantization, context length, and concurrency before comparing runs. Peak memory is the maximum observed usage during the measured interval; final resident memory is only a snapshot. A model fixture proves neither real token consumption nor actual model resource demand.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Hypothetical rates are 2 input and 6 output per million; usage is 1000 and 100. What is cost?
2. An answer contains 100 characters. What establishes its model token count?
3. A local process ends using 400 megabytes. Is that its measured peak?

Section 3.4 4 of 7

Latency distributions, retries, and bottlenecks

Focus

Interpret latency distributions and identify retries on the request critical path.

Latency is elapsed time for a request or stage. The median describes the middle observation after sorting. A tail statistic such as the ninety-fifth percentile describes unusually slow requests, but its exact calculation convention must be stated. In a nearest-rank calculation, select sorted position ceiling(0.95×n), counting from one. With five observations, that selects the largest, which is a very unstable estimate of a production tail.

For sequential stages, request duration approximately includes retrieval, generation, tool work, and orchestration overhead. For parallel stages, summing every span overcounts wall time because intervals overlap. The critical path is the dependent chain that determines completion. A retry on that path increases the user's wait even when most requests remain fast.

Suppose four requests finish in ten milliseconds and one retries a slow tool, finishing in fifty. The median stays ten while the nearest-rank ninety-fifth percentile becomes fifty. Before blaming the model, inspect the tool attempts. Measure enough representative requests for a meaningful operational estimate, and keep cold-start loading, deliberate injected delays, and ordinary warm requests separately labeled.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Durations are 10,10,10,10,50 milliseconds. What is the median?
2. Two independent 40-millisecond spans run concurrently. What can their sum misstate?
3. Five observations use nearest-rank 95th percentile. Which position is selected?

Section 3.5 5 of 7

Put it into practice

Focus

Execute local tracing while labeling synthetic model work and controlled delay.

Save week19.py and run python week19.py --lesson 3. Its standard-library imports include uuid for unique identifiers, statistics for the median, math for ceiling, and time for elapsed measurement. A list holds span dictionaries. The script records five traces through retrieval, model_fixture, and tool stages.

The fifth request's tool stage has two attempts, each with a five-millisecond sleep. This creates an explicit controlled delay. The printed numbers are actual measurements of this local harness, including scheduling overhead; they are not real model generation latency. Expect sixteen span records, five request totals, and a final request whose injected delays dominate its work. Exact milliseconds can vary by machine.

The same output includes a hypothetical monetary estimate of 0.0026 units from declared rates. Keep that estimate separate from measured elapsed time. Extend this artifact by adding a status field and a parent span identifier, then assert that every retry shares the request trace. Do not assert an exact clock value: operating-system scheduling makes exact timing brittle even when the workload is deterministic.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A lab labels a span model_fixture. What latency does it measure?
2. Five requests contain three stages; one stage adds a retry. How many spans result?
3. A sleep requests five milliseconds but reports seven. Which assertion is appropriate?

Section 3.6 6 of 7

Guided comparison

Focus

Read the trace evidence before assigning responsibility for a latency increase.

The lab's first four requests perform tiny calculations, so their measured durations mostly reflect local overhead. The fifth tool stage includes two intentional sleeps. Sorting request totals therefore exposes the deliberately slow path without measuring any language model. The median summarizes common harness behavior while the tail highlights the injected retry.

A trace also explains why the extra time occurred. There are two tool attempts under the same request identifier. If the report contained only a total, the increase could equally have come from model loading, a long prompt, a busy database, or a slow dependency. Stage records reduce that ambiguity, although they still cannot reveal an external dependency's internal cause.

Compare measurements under the same workload and release configuration. If one version changes both document count and retry policy, a slower total cannot be attributed uniquely to either change. Preserve versions, counts, status, and token categories so the interpretation can be revisited. The useful engineering conclusion is limited but concrete: the tracing harness links the retry to the slow request and its counters are internally consistent. Real-model performance remains a separate run.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A slow request has two delayed tool spans and a tiny model fixture span. What is supported?
2. Two benchmark versions change prompt size and retry policy. What is uncertain?
3. A trace shows external-call duration but no server detail. What remains unknown?

Section 3.7 7 of 7

A retry causing a tail-latency spike

Focus

Explain a retry-driven tail spike without hiding amplification or duplicate-effect risk.

A ticket assistant normally completes retrieval in twenty milliseconds, generation in eighty, and a tool call in thirty. One tool response is lost after the ticket was committed. The application waits two hundred milliseconds and retries. Most requests still finish near one hundred thirty milliseconds, so the median may barely move, while affected requests push up the tail.

The trace must link both attempts with the same operation identifier as well as the same trace identifier. A trace groups diagnostics; an operation identifier lets the tool recognize the intended business effect. If the second call uses a new operation identifier, it can create a duplicate ticket even though both calls are correctly logged.

Recovery inspects the durable effect record before repeating work. Monitoring should count attempts per successful operation, not only final successful responses. A service can show excellent final success while silently doubling dependency traffic and increasing cost. The corrective choice is a bounded retry policy plus idempotent effect handling, followed by a measurement confirming reduced amplification and preserved completion. A shorter model prompt would not repair this particular missing acknowledgement.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A ticket commits but its response is lost. What should a retry preserve?
2. Final success stays high while attempts double. Which metric reveals amplification?
3. A tool acknowledgement is lost. Which repair addresses the mechanism?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Handling dependency failure predictably →