TECHNOLOGIESTieInn Technologies

Cost, rate limits, retries and streaming

LLM Fundamentals & Prompting · 11 questions

Short notes

Key idea

Production LLM apps must control cost (tokens × price), respect rate limits, recover from temporary errors, and feel fast. Streaming shows the reply as it's generated.

Syntax

  • Cost: input tokens × input price + output tokens × output price; output is usually dearer.
  • Rate limits: requests and tokens per minute; a 429 error means slow down.
  • Retries: retry 429 and 5xx errors with exponential backoff and jitter; don't retry 400s.
import time, random
for attempt in range(4):
    try:
        r = client.models.generate_content(model=MODEL, contents=q); break
    except errors.APIError as e:
        if e.code not in (429, 500, 503): raise
        time.sleep(2 ** attempt + random.random())

for chunk in client.models.generate_content_stream(model=MODEL, contents=q):
    print(chunk.text, end="")

Example

A summariser calls the API 10,000 times a day with 2,000 tokens in and 200 out. Trimming the prompt to 800 tokens cuts input cost by 60% with the same answers.

Traps

  • Retrying everything (including bad requests) wastes money and hides bugs.
  • No timeout: a stuck call hangs the user's request.
  • Long system prompts repeated every call are a hidden cost.
  • Streaming doesn't reduce cost; it only improves perceived speed.

Want the full lesson with step-by-step examples, a project and a certificate? LLM Fundamentals & Prompting course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    Cost, rate limits, retries and streaming

  1. Question 1easy

    Example prices: $0.10 per million input tokens and $0.40 per million output tokens. What does this print?

    cost = (2_000_000 * 0.10 + 500_000 * 0.40) / 1_000_000
    print(round(cost, 2))
  2. Cost, rate limits, retries and streaming

  3. Question 2easy

    Why do providers usually charge more for output tokens than input tokens?

  4. Cost, rate limits, retries and streaming

  5. Question 3easy

    What does an HTTP 429 response from an LLM API mean?

  6. Cost, rate limits, retries and streaming

  7. Question 4medium

    With base 2 seconds and no jitter, what are the waits before attempts 2, 3 and 4?

    base = 2
    print([base * 2 ** (attempt - 1) for attempt in [1, 2, 3]])
  8. Cost, rate limits, retries and streaming

  9. Question 5hard

    Write call_with_retries(model, messages, sleep, max_attempts=4, base=1) that calls model.generate(messages), and on RateLimitError or ServerBusyError calls sleep(base * 2 ** (attempt - 1)) and tries again, up to max_attempts attempts in total (re-raise on the last). Run it with sleep=waits.append. Store the reply text in result.

    Store your answer in result.

6 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.