TECHNOLOGIESTieInn Technologies

Serving an LLM app: async calls, streaming and timeouts

Shipping AI Apps · 10 questions

Short notes

Key idea

An LLM endpoint spends most of its time waiting on the model. Make it async so one server handles many users at once, stream tokens so users see progress, and set timeouts so a stuck call doesn't hang a request.

Syntax

import asyncio
from fastapi.responses import StreamingResponse

@app.post("/ask")
async def ask(q: Question):
    try:
        r = await asyncio.wait_for(
            client.aio.models.generate_content(model=MODEL, contents=q.text),
            timeout=30)
    except asyncio.TimeoutError:
        raise HTTPException(504, "The model took too long. Please try again.")
    return {"reply": r.text}

@app.post("/stream")
async def stream(q: Question):
    async def gen():
        async for chunk in await client.aio.models.generate_content_stream(model=MODEL, contents=q.text):
            yield chunk.text
    return StreamingResponse(gen(), media_type="text/plain")

Example

With a sync endpoint, 20 users each waiting 4 seconds queue behind each other. With async, all 20 wait at the same time and get answers in about 4 seconds.

Traps

  • Calling a sync SDK inside async def blocks the event loop.
  • No timeout lets one slow call pile up connections.
  • Errors mid-stream can't change the status code; send an error message in the stream.
  • Create the client once at startup, not per request.

Want the full lesson with step-by-step examples, a project and a certificate? Shipping AI Apps course, ₹180 →

Questions

Open in Code Lab5 free questions
5 questions

    Serving an LLM app: async calls, streaming and timeouts

  1. Question 1medium

    Why make an LLM endpoint async def and use the SDK's async client?

  2. Serving an LLM app: async calls, streaming and timeouts

  3. Question 2easy

    Where should the genai.Client be created in a FastAPI service?

  4. Serving an LLM app: async calls, streaming and timeouts

  5. Question 3medium

    What does this print?

    import asyncio
    async def slow_model():
        await asyncio.sleep(0.3)
        return "answer"
    async def handler():
        try:
            return await asyncio.wait_for(slow_model(), timeout=0.1)
        except asyncio.TimeoutError:
            return 504
    print(asyncio.run(handler()))
  6. Serving an LLM app: async calls, streaming and timeouts

  7. Question 4medium

    The provider returns "503 UNAVAILABLE: high demand". What should the user see?

  8. Serving an LLM app: async calls, streaming and timeouts

  9. Question 5easy

    What does this print?

    pieces = ["Pack ", "items ", "in bubble", " wrap."]
    print("".join(pieces))

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

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