Skip to main content

AI and machine learning · Advanced · 24 min

Make an LLM feature respond faster

By Padding · Updated 18 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · Claude Opus 5.5 and Claude Haiku 5.5

You will measure time to first token and total time for a Claude-powered support reply feature, then speed it up with streaming, prompt caching, shorter output, a lower effort level, a smaller model for easy requests and concurrent calls, checking every change against a small eval.

On this page

An LLM feature feels slow for a handful of reasons, and they stack up. The request travels to the API and may wait in a queue. The model reads your whole prompt before it writes anything, and a longer prompt takes longer to read. Claude Opus 5.5 always thinks before it answers, and that thinking takes time even when you never see it. Then it writes the reply one token at a time, so a long reply takes longer than a short one. Finally, your own code may wait for one call to finish before it starts the next.

Each of those has a lever, and they are not equal. Some cost nothing in quality (streaming, caching, running calls in parallel). Others trade quality for speed (shorter answers, less thinking, a smaller model). This tutorial pulls them in that order, and judges each against a small eval, so that a faster feature is not quietly a worse one.

The feature is a reply suggester for the support team of Kora Market, an invented online shop that delivers across Nigeria, Ghana and Kenya. It reads a customer message and drafts a reply from the shop's help notes. You will build it in ~/latency-demo, write a timing harness that reports two numbers for each request:

  • Time to first text: how long until the first words of the reply reach your code. This is the wait a person feels.
  • Total time: how long until the whole reply has arrived. This is what a background job or a chained call waits for.

You report each at p50 (the median request) and p95 (the slow requests: 95 in 100 are faster). Averages hide the slow tail, and the slow tail is what people remember. For readers on low-end Android phones and prepaid data, which is common across African markets, the first number matters even more: a reply that starts quickly and stays short reads better on a small screen and uses less data.

Step 1 · Create the project, the prompt and the eval set

Load the key you saved in the earlier tutorial into this terminal. set -a exports every variable the file defines, so the SDK can read ANTHROPIC_API_KEY:

Bash
set -a
. ~/.config/llm-demo/env
set +a

Create the project and add the SDK at the exact version this tutorial uses:

Bash
mkdir -p ~/latency-demo
cd ~/latency-demo
uv init --no-package
uv add "anthropic==2.14.0"

The system prompt is the shop's help notes. It is the same for every request, which makes it the stable prefix you will cache later. Save it as policy.md:

Bash
cat > policy.md <<'MD'
# Kora Market support notes

You draft replies to customer messages for Kora Market, an online shop that delivers household goods across Nigeria, Ghana and Kenya. A support agent reads every draft before it is sent.

Reply in the language the customer wrote in. Use only the facts in these notes. If a message needs something the notes do not cover, say that a team member will follow up within one working day, and do not guess. Never ask for a password, a card number or a one-time code.

## Accounts

- Password reset: in the app, go to Settings, then Security, and tap Reset password. The emailed link works for 30 minutes.
- Locked account: after five failed sign-ins the account locks for 15 minutes, then unlocks on its own.
- Email change: under Settings, then Profile. A confirmation link goes to the new address.

## Delivery

- Lagos and Abuja: 2 to 4 working days after dispatch. Other Nigerian cities: 3 to 6 working days.
- Accra and Nairobi: 3 to 5 working days after dispatch.
- A tracking link is sent by SMS when the parcel is dispatched.
- The delivery address can be changed under Orders until the parcel is dispatched. After dispatch it cannot be changed; the customer can refuse the parcel and order again.
- Missing parcel: if tracking shows delivered but the customer has nothing, ask for the order number and open a trace, which takes up to 3 working days.

## Payments and refunds

- A duplicate card or bank charge is refunded to the original payment method within 5 working days of the customer reporting it. Ask for the order number if it is missing.
- A failed mobile money payment is usually reversed to the customer's wallet within 48 hours. If it is not, ask for the transaction reference.
- Refunds for returned items are issued within 5 working days of the return reaching the warehouse.

## Returns

- Most items can be returned unused within 14 days of delivery. Food, cosmetics and opened bedding cannot be returned.
- The customer starts a return under Orders. A courier collects it within 3 working days.

## Damaged or wrong items

- Ask for a photo of the item and the packaging within 7 days of delivery. Kora Market then sends a replacement at no cost, or a refund if the item is out of stock.

## Support hours

- The support line is open Monday to Saturday, 8:00 to 20:00 West Africa Time. Messages sent outside those hours are answered the next working day.

## Tone

- Be warm and direct. Apologise once when something went wrong. Do not promise anything these notes do not state.
MD

The eval set is eight real-looking messages, each with the words a correct reply must contain. Keyword checks are crude, but they are fast and free, and they catch the failure you care about here: a faster setting that drops the one fact the customer needed. Save it as tickets.json:

Bash
cat > tickets.json <<'JSON'
[
  {"id": "t1", "text": "I forgot my password and the app will not let me log in.", "must_mention": ["settings"]},
  {"id": "t2", "text": "How long does delivery to Lagos take?", "must_mention": ["working days"]},
  {"id": "t3", "text": "When is your support line open?", "must_mention": ["monday"]},
  {"id": "t4", "text": "I was charged twice for order 5521 and I want my money back.", "must_mention": ["refund", "working days"]},
  {"id": "t5", "text": "My blender arrived broken. What can I do?", "must_mention": ["photo"]},
  {"id": "t6", "text": "My mobile money payment failed but the money has left my account.", "must_mention": ["48 hours"]},
  {"id": "t7", "text": "Can I change the delivery address on order 5530?", "must_mention": ["dispatch"]},
  {"id": "t8", "text": "Bonjour, ma commande n'est pas arrivée. Pouvez-vous m'aider ?", "must_mention": ["commande"]}
]
JSON

The French ticket checks that the reply stays in the customer's language. Add messages in the languages your own customers write in, such as Hausa, Yoruba, Swahili or Pidgin, with words you expect in a correct reply.

Check it worked

Bash
uv run python -c "import anthropic, json; print(anthropic.__version__, len(json.load(open('tickets.json'))), 'tickets')"

The command prints 2.14.0 8 tickets. If it fails with a JSON error, check the file for a missing comma.

Step 2 · Write a timing harness and measure the baseline

The harness sends every ticket, times each request, checks each reply against the eval and prints p50 and p95. It also holds every lever this tutorial uses as a named configuration, so each later step runs one more configuration and you compare the lines. Create fast.py:

Bash
cat > fast.py <<'PY'
import argparse
import asyncio
import json
import math
import time
from pathlib import Path

import anthropic

POLICY = Path("policy.md").read_text(encoding="utf-8")
TICKETS = json.loads(Path("tickets.json").read_text(encoding="utf-8"))

BIG = "claude-opus-5-5"
SMALL = "claude-haiku-5-5"
FAQ_WORDS = ("password", "how long", "open", "address")
SHORT = "\n\nReply in at most 60 words. Put the answer in the first sentence."

# Each configuration adds one lever to the one before it.
CONFIGS = {
    "baseline": {},
    "stream": {"stream": True},
    "cache": {"stream": True, "cache": True},
    "short": {"stream": True, "cache": True, "short": True},
    "low": {"stream": True, "cache": True, "short": True, "effort": "low"},
    "small": {"stream": True, "cache": True, "short": True, "effort": "low", "model": "small"},
    "routed": {"stream": True, "cache": True, "short": True, "effort": "low", "route": True},
}


def pick_model(ticket, cfg):
    if cfg.get("model") == "small":
        return SMALL
    if cfg.get("route") and any(word in ticket["text"].lower() for word in FAQ_WORDS):
        return SMALL
    return BIG


def build_request(ticket, cfg):
    block = {"type": "text", "text": POLICY + (SHORT if cfg.get("short") else "")}
    if cfg.get("cache"):
        block["cache_control"] = {"type": "ephemeral"}
    request = {
        "model": pick_model(ticket, cfg),
        "max_tokens": 3000 if cfg.get("short") else 8000,
        "system": [block],
        "messages": [{"role": "user", "content": ticket["text"]}],
    }
    if "effort" in cfg:
        request["output_config"] = {"effort": cfg["effort"]}
    return request


async def call_once(client, ticket, cfg):
    request = build_request(ticket, cfg)
    start = time.perf_counter()
    first = None
    if cfg.get("stream"):
        async with client.messages.stream(**request) as stream:
            async for _ in stream.text_stream:
                if first is None:
                    first = time.perf_counter() - start
            message = await stream.get_final_message()
    else:
        message = await client.messages.create(**request)
    total = time.perf_counter() - start
    return {
        # Without streaming, nothing can be shown until the whole reply is back.
        "ttft": total if first is None else first,
        "total": total,
        "text": "".join(block.text for block in message.content if block.type == "text"),
        "stop": message.stop_reason,
        "model": message.model,
        "cache_read": message.usage.cache_read_input_tokens or 0,
    }


def passes(ticket, result):
    if result["stop"] != "end_turn" or not result["text"].strip():
        return False
    text = result["text"].lower()
    return all(word in text for word in ticket["must_mention"])


def pct(values, p):
    """Nearest-rank percentile: the smallest value that p% of values do not exceed."""
    ordered = sorted(values)
    return ordered[max(0, math.ceil(p / 100 * len(ordered)) - 1)]


async def run(name, concurrency, repeat, show):
    cfg = CONFIGS[name]
    limit = asyncio.Semaphore(concurrency)
    async with anthropic.AsyncAnthropic() as client:

        async def one(ticket):
            async with limit:
                return ticket, await call_once(client, ticket, cfg)

        start = time.perf_counter()
        pairs = await asyncio.gather(*(one(ticket) for ticket in TICKETS * repeat))
        wall = time.perf_counter() - start

    results = [result for _, result in pairs]
    failed = [ticket["id"] for ticket, result in pairs if not passes(ticket, result)]
    summary = {
        "name": name,
        "concurrency": concurrency,
        "requests": len(pairs),
        "ttft_p50": pct([r["ttft"] for r in results], 50),
        "ttft_p95": pct([r["ttft"] for r in results], 95),
        "total_p50": pct([r["total"] for r in results], 50),
        "total_p95": pct([r["total"] for r in results], 95),
        "wall": wall,
        "words_p50": pct([len(r["text"].split()) for r in results], 50),
        "cache_read": sum(r["cache_read"] for r in results),
        "models": sorted({r["model"] for r in results}),
        "passed": len(pairs) - len(failed),
        "failed": failed,
    }
    Path("results").mkdir(exist_ok=True)
    Path(f"results/{name}-c{concurrency}.json").write_text(json.dumps(summary, indent=2))

    if show:
        for ticket, result in pairs:
            mark = "ok  " if passes(ticket, result) else "FAIL"
            print(f"{mark} {ticket['id']} [{result['model']}] {result['text']}\n")
    print(f"{name}: {len(pairs)} requests, concurrency {concurrency}, models {', '.join(summary['models'])}")
    print(f"  first text   p50 {summary['ttft_p50']:.2f} s   p95 {summary['ttft_p95']:.2f} s")
    print(f"  total        p50 {summary['total_p50']:.2f} s   p95 {summary['total_p95']:.2f} s")
    print(f"  wall clock {wall:.1f} s | words p50 {summary['words_p50']} | cache read tokens {summary['cache_read']}")
    print(f"  eval {summary['passed']}/{len(pairs)} passed" + (f", failed: {', '.join(failed)}" if failed else ""))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Time and check the reply suggester.")
    parser.add_argument("config", choices=CONFIGS)
    parser.add_argument("--concurrency", type=int, default=1)
    parser.add_argument("--repeat", type=int, default=1, help="send the ticket list this many times")
    parser.add_argument("--show", action="store_true", help="print every reply")
    args = parser.parse_args()
    asyncio.run(run(args.config, args.concurrency, args.repeat, args.show))
PY

A few choices in this file matter for honest numbers:

  • time.perf_counter() is a clock meant for measuring intervals. The wall-clock time can jump when the system clock is adjusted.
  • pct uses the nearest-rank method. With eight requests, p95 is simply the slowest one. That is enough to compare settings on your laptop, but before you trust a p95 for a decision, send at least 50 requests with --repeat, at the time of day your users are busy.
  • A reply that stops for any reason other than end_turn, such as hitting max_tokens, fails the eval even if it contains the words. A cut-off reply is not a reply you would send.
  • AsyncAnthropic is used from the start, with a semaphore that allows one request at a time. The last step raises that limit; nothing else changes.

The baseline sends each ticket without streaming, with no caching, no length instruction and no effort setting, so Claude Opus 5.5 runs at its default effort, medium. Run it with --show once to read the replies yourself:

Bash
uv run fast.py baseline --show

Check it worked

You see the eight replies, each marked ok or FAIL, followed by a summary like this one. Your numbers will differ:

Text
baseline: 8 requests, concurrency 1, models claude-opus-5-5
  first text   p50 6.80 s   p95 9.40 s
  total        p50 6.80 s   p95 9.40 s
  wall clock 57.2 s | words p50 104 | cache read tokens 0
  eval 8/8 passed

First text and total are the same, because without streaming nothing reaches your code until the reply is complete. Read every reply before you go on. The eval only checks words; you are the check that the drafts are correct, polite and in the right language. If a ticket fails at the baseline, fix the prompt or the expected words first, because every later comparison starts from here.

Step 3 · Stream the reply

Streaming does not make the model write any faster. It hands you each piece of text as it is written, so the person sees the start of the answer while the rest is still on its way. For a reply suggester in a support tool, that means the agent can start reading at once. The stream configuration switches call_once to client.messages.stream() and records when the first piece of text arrives:

Bash
uv run fast.py stream

The tutorial on streaming Claude responses in Python covers the event sequence, cancelling a stream and showing the text in a terminal. Here the text is only timed.

Streaming also protects long requests. The SDK refuses a non-streaming request whose max_tokens suggests it could run past its 10-minute default timeout, and an idle connection that waits minutes for a reply can be cut by a proxy along the way.

Check it worked

Text
stream: 8 requests, concurrency 1, models claude-opus-5-5
  first text   p50 2.30 s   p95 3.10 s
  total        p50 6.90 s   p95 9.20 s

First text is now well below total, while total stays roughly where it was. The eval still passes 8/8, because the request is the same; only the way you receive it changed.

Step 4 · Cache the stable prefix

Before it writes anything, the model processes your whole prompt. Prompt caching lets the API keep that work for a prefix it has seen recently, so a later request with the same start skips most of it. The help notes are identical in every request, so they are the prefix to cache. In build_request, the cache configuration adds one key to the system block:

Python
block["cache_control"] = {"type": "ephemeral"}

That marks the end of the cached part. Everything before the mark must match byte for byte for a later request to hit the cache. An entry lasts five minutes by default, and each hit renews it. Run it:

Bash
uv run fast.py cache

Three things can make the cache silently do nothing:

  • The prefix is too short. Claude Opus 5.5 and Claude Haiku 5.5 only cache prompts of at least 512 tokens. Below that, the request runs normally and no error is returned. The Kora notes, at about 450 words, should land a little over that line; a three-line system prompt does not.
  • Something in the prefix changes. A timestamp, a user's name or a shuffled list in the system prompt breaks the match for every request. Put changing content after the cached part, in the user message.
  • Requests arrive together. A cache entry becomes available only once the first response that writes it has started. If you send a burst of requests at the same moment, send one first and wait for its first text.

Caching also cuts the input cost of every hit. The tutorial on cutting LLM costs with prompt caching covers the prices, the longer lifetime and the other ways to place breakpoints.

Check it worked

The summary shows a non-zero count, such as cache read tokens 4011: the first request wrote the cache and the other seven read from it. If it shows cache read tokens 0, the prefix is below the minimum or changed between requests. First text is a little lower than in the stream run. The gain grows with the length of the prefix: a few hundred tokens of notes save little, a long document saves much more. The eval still passes 8/8, because the model sees exactly the same prompt.

Step 5 · Ask for a shorter answer

Output is usually the biggest part of total time, because the model writes one token after another. Fewer words means a shorter wait, and for the agent reading the draft, less to read. The baseline replies average around a hundred words, much of it polite filler. The short configuration adds one instruction to the end of the help notes:

Text
Reply in at most 60 words. Put the answer in the first sentence.

Asking in the prompt is the right control. Lowering the effort setting, the next step, barely changes how long the replies are.

The configuration also lowers max_tokens from 8,000 to 3,000. That is not how you shorten a reply: max_tokens is a hard cut, and a reply that hits it simply stops mid-sentence with stop reason max_tokens, which the eval counts as a failure. It is a guard against the rare runaway reply that would wreck your p95. Thinking counts toward the same limit, so leave plenty of room above the length you asked for: a ceiling of a few hundred tokens can be used up by thinking before any text appears.

Changing the system prompt changes the cached prefix, so the first request of this run writes a new cache entry. Run it with --show, so you can check that the shorter drafts still say what they need to:

Bash
uv run fast.py short --show

Check it worked

words p50 drops to 60 or fewer and total time drops with it, while first text stays about the same. Read the replies: they should still give the fact, the number or the next step the customer needs. If the eval fails a ticket now, the length limit is cutting something that matters. Raise the limit, or say in the instruction what must always be included.

Step 6 · Lower the effort setting

Claude Opus 5.5 always thinks before it answers, and thinking cannot be turned off. Its depth is controlled by output_config.effort, which runs from low through medium (the default on this model), high and xhigh to max. Thinking happens before the first word of the reply, so less of it shows up directly in time to first text. The low configuration adds:

Python
request["output_config"] = {"effort": "low"}

Effort is a signal, not a budget. At low, the model still thinks on a hard problem, just less than it would at a higher level. Answering a support question from a page of notes is a good fit for low; reasoning about a complicated refund dispute may not be. Run it:

Bash
uv run fast.py low --show

Check it worked

First text drops compared with the short run, and total time drops with it. Then compare the replies with the previous run. Quality loss from lower effort tends to show up as a missed condition or a wrong detail rather than a shorter reply, which is exactly what the eval words and your own reading catch. If a ticket fails, keep medium for that kind of request, or pass the effort level per request from your router.

Step 7 · Route easy tickets to a smaller model

Claude Haiku 5.5 is Anthropic's fastest current model and is aimed at high-volume work such as classification, extraction and routing. Some of the tickets are a lookup in the notes: a password reset, a delivery time, the opening hours. Others need more care: a double charge, a broken item. First, see what happens when every ticket goes to the small model:

Bash
uv run fast.py small --show

Look at the eval line. If the small model drops a required detail, such as the refund timescale or the request for a photo, it shows here as something like eval 6/8 passed, failed: t4, t5. Whether that happens depends on the model, the prompt and the tickets. The point of the eval is that you see it before your customers do.

So route instead. pick_model sends a ticket to Claude Haiku 5.5 only when it contains one of the FAQ_WORDS, and everything else to Claude Opus 5.5:

Bash
uv run fast.py routed

A keyword router is crude. "Open" also matches "I opened a dispute", which is not an easy ticket. In production, replace it with a router you can test: a short classification call to the small model, or the category the customer picked in your support form. Run the eval on each route, not only on the mix. Each model also keeps its own cache, so the first request to each one writes an entry.

Check it worked

The routed summary lists both models, and the eval is back to 8/8. Total time p50 is lower than in the low run, because half the tickets now go to the faster model. If a ticket the router sends to the small model fails, take its words out of FAQ_WORDS or improve the router; do not loosen the eval.

Step 8 · Run independent calls at the same time

Every run so far has sent one request at a time, so the wall clock is the sum of eight waits. The tickets do not depend on each other, so there is no reason to wait. run already wraps each call in async with limit, an asyncio.Semaphore, and starts them all with asyncio.gather. Raising the limit lets that many requests be in flight together:

Bash
uv run fast.py routed --concurrency 4

Concurrency changes how long the batch takes, not how long one request takes. Per-request first text and total stay about the same, while the wall clock falls. The same applies inside one feature: if a page needs a summary and a list of tags from the same text, send both calls at once instead of one after the other. Calls that need each other's output still have to run in order.

The semaphore matters. The API limits requests and tokens per minute, and going over answers with a 429 error. The SDK retries twice by default and honours the retry-after header, but an unlimited gather over a thousand tickets would hit the limit and spend its time in retries. Start with a small limit and raise it while watching for 429s. For many more requests at once, the tutorial on running many network calls at once with Python asyncio covers timeouts and error handling in a gather.

Check it worked

The summary shows concurrency 4 and a wall clock well under the routed run's, roughly a third to a quarter of it, with the eval still at 8/8. Compare the saved summaries side by side:

Bash
uv run python -c "import json, pathlib; [print(f'{p.stem:14} first {d[\"ttft_p50\"]:.2f} s  total {d[\"total_p50\"]:.2f} s  wall {d[\"wall\"]:.1f} s  eval {d[\"passed\"]}/{d[\"requests\"]}') for p in sorted(pathlib.Path('results').glob('*.json'), key=lambda p: p.stat().st_mtime) for d in [json.loads(p.read_text())]]"

Each line is one run, in the order you ran them. Read down the first text and total columns to see what each lever bought, and down the eval column to see what it cost. Keep the levers that moved your numbers without moving the eval.

Step 9 · Clean up

Delete the demo project. The key file stays for the other LLM tutorials:

Bash
cd ~
rm -rf ~/latency-demo

Check it worked

Bash
test ! -e ~/latency-demo && echo "demo removed"

The output is demo removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.