Skip to content
Streak:0Loading your progress…Sign in

Module 8 · Lesson 2 of 2

Pagination, CORS & streaming

Cursor pagination, a strict CORS allow-list, and SSE for chat UIs. ~30 min

Lesson notes

Cursor pagination beats offset pagination on large or changing data: the cursor encodes the last-seen sort key, so you query WHERE id > :cursor ORDER BY id LIMIT :n. Return next_cursor (null at the end). Encode cursors (base64) so clients treat them as opaque.

CORS is enforced by browsers. A FastAPI back end serving a Vercel front end must allow-list the exact origins. Never combine allow_origins=["*"] with credentials.

Streaming an LLM response to the browser with SSE (FastAPI)
from fastapi.responses import StreamingResponse

@app.post("/v1/chat")
async def chat(body: ChatIn, user=Depends(current_user)):
    async def events():
        async with llm.messages.stream(model=MODEL, messages=body.messages, max_tokens=2048) as stream:
            async for text in stream.text_stream:
                yield f"data: {json.dumps({'delta': text})}\n\n"
        yield "data: [DONE]\n\n"
    return StreamingResponse(events(), media_type="text/event-stream")

Practice

  1. 1. Cursor pagination

    medium25 XP

    Write paginate(rows, limit, cursor=None) -> dict over rows (list of dicts sorted by unique int id). Return {"items": [...], "next_cursor": str | None}. Cursors are base64url-encoded JSON {"after": last_id}. Clamp limit to 1..100. An invalid cursor raises ValueError("invalid cursor").

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. CORS decision function

    medium25 XP

    Write cors_headers(origin, allowed, allow_credentials) -> dict. If origin is in allowed (exact match) return {"Access-Control-Allow-Origin": origin, "Vary": "Origin"} plus "Access-Control-Allow-Credentials": "true" when allowed. If allowed == ["*"] and credentials are off, return {"Access-Control-Allow-Origin": "*"}. Raise ValueError if "*" is combined with credentials. Otherwise return {}.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  3. 3. Format Server-Sent Events

    easy10 XP

    Write a generator sse(chunks) that yields "data: {json}\n\n" for each text chunk as {"delta": chunk}, then a final "data: [DONE]\n\n". Use json.dumps so quotes and newlines in chunks are escaped.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor