AiCredits
Async Patterns

How to Use DeepSeek API with FastAPI: Async Patterns That Scale

Build a FastAPI service that calls the DeepSeek API with async patterns that hold up under load — connection reuse, backpressure, SSE streaming, and retries.

Published 2026-09-25 Updated 2026-09-25 8 min

Why the obvious FastAPI wrapper falls over

The first version of most FastAPI + LLM services looks the same. An endpoint constructs AsyncOpenAI() inside the handler, awaits one completion, returns the text. It passes review. It survives a load test with ten concurrent users. Then real traffic arrives and latency goes vertical.

Three failures happen at once. A new client per request means a fresh TCP and TLS handshake on every call instead of reusing a warm connection. Unbounded concurrency means a traffic spike turns into a wave of upstream errors. And a single long generation pins a worker while everything else waits behind it.

None of this requires exotic architecture to fix. It requires four habits: one process-wide client, a semaphore for backpressure, streaming that respects client disconnects, and error handling that knows what the SDK already retries.

One client, one pool, one lifespan

# pip install fastapi uvicorn "openai>=1.40" pydantic
import asyncio
import os
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Request
from openai import AsyncOpenAI
from pydantic import BaseModel, Field

BASE_URL = 'https://api.aicreditsapi.com/v1'
FAST_MODEL = 'deepseek-v4-flash'


@asynccontextmanager
async def lifespan(app: FastAPI):
    # One client per process -> one pooled set of HTTP connections.
    app.state.client = AsyncOpenAI(
        api_key=os.environ['AICREDITS_API_KEY'],
        base_url=BASE_URL,
        timeout=45.0,
        max_retries=2,
    )
    # Hard ceiling on concurrent upstream calls.
    app.state.slots = asyncio.Semaphore(16)
    # Streams hold a slot for their whole lifetime, so cap them separately.
    app.state.stream_slots = asyncio.Semaphore(8)
    try:
        yield
    finally:
        await app.state.client.close()


app = FastAPI(lifespan=lifespan)


class Prompt(BaseModel):
    text: str = Field(min_length=1, max_length=8000)


@app.post('/summarize')
async def summarize(prompt: Prompt, request: Request) -> dict:
    client: AsyncOpenAI = request.app.state.client
    async with request.app.state.slots:
        try:
            resp = await client.chat.completions.create(
                model=FAST_MODEL,
                messages=[
                    {'role': 'system', 'content': 'Summarize in three short bullet points.'},
                    {'role': 'user', 'content': prompt.text},
                ],
                temperature=0.2,
            )
        except Exception as exc:  # timeout, 429, 5xx, connection reset
            raise HTTPException(status_code=502, detail='upstream model error') from exc
    return {'summary': resp.choices[0].message.content or ''}

The lifespan context manager is the whole trick. The client is created once when the app boots, so every request reuses the same connection pool and the TLS handshake cost is paid once instead of thousands of times. It is also closed cleanly on shutdown, which matters in container environments where workers are recycled constantly.

If you run multiple Uvicorn or Gunicorn workers, each process gets its own client and its own semaphore. Size accordingly: a desired global concurrency of 64 across four workers means 16 per process.

Notice that the model name is a module constant, not a request field. Keep it that way unless a caller has a real reason to choose, and validate against an allowlist if they do.

Backpressure: a semaphore is cheaper than a retry storm

A semaphore of 16 means at most sixteen calls are in flight against the API. Request seventeen waits inside your process for a fraction of a second rather than arriving as a burst the provider has to shed. Waiting is cheaper, more predictable, and easier to reason about than retrying.

The async with block matters for more than style. It releases the slot even when the call raises, so one bad request cannot permanently shrink your capacity over a long uptime.

Tune the number by measuring rather than guessing: raise it while p95 latency stays flat, then stop. If throughput no longer improves when you add slots, you are queueing inside the HTTP pool instead of in your own code, and the semaphore has stopped being the bottleneck.

Watch out for the interaction with the connection pool. If you pass a custom httpx.AsyncClient with a small max_connections limit, httpx will silently queue requests below your semaphore. Keep pool size above semaphore size.

Streaming: keep the client honest and the slot bounded

import json

from fastapi.responses import StreamingResponse


def sse(payload: dict) -> str:
    return f'data: {json.dumps(payload)}\n\n'


@app.post('/stream')
async def stream_summary(prompt: Prompt, request: Request) -> StreamingResponse:
    client: AsyncOpenAI = request.app.state.client
    stream_slots: asyncio.Semaphore = request.app.state.stream_slots

    async def event_stream():
        async with stream_slots:
            try:
                stream = await client.chat.completions.create(
                    model=FAST_MODEL,
                    messages=[{'role': 'user', 'content': prompt.text}],
                    stream=True,
                    temperature=0.2,
                )
                async for chunk in stream:
                    if await request.is_disconnected():
                        await stream.close()
                        return
                    if not chunk.choices:
                        continue  # final usage-only chunk
                    delta = chunk.choices[0].delta.content
                    if delta:
                        yield sse({'delta': delta})
                yield 'data: [DONE]\n\n'
            except Exception:
                yield sse({'error': 'stream_failed'})

    return StreamingResponse(
        event_stream(),
        media_type='text/event-stream',
        headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'},
    )

Two details break more streaming endpoints than anything else. The first is await request.is_disconnected(): when a user closes the tab, you must stop generating and close the upstream stream, otherwise you keep paying for tokens nobody will read while holding a slot. The second is X-Accel-Buffering: no, which stops nginx and similar reverse proxies from buffering your event stream until the response completes, defeating the point of streaming.

Guard chunk.choices before indexing it. Some chunks carry no choices, and an unguarded index access is a classic intermittent 500 in production.

Because a streaming response holds its semaphore slot for the entire generation, give it a separate, smaller pool. Mixing long streams and short completions behind one limit means a handful of slow streams starves the fast path.

Bounded fan-out for batch work

class BatchPrompt(BaseModel):
    items: list[str] = Field(min_length=1, max_length=50)


async def classify_one(
    client: AsyncOpenAI, slots: asyncio.Semaphore, text: str
) -> str:
    async with slots:
        resp = await client.chat.completions.create(
            model='deepseek-v4-flash',
            messages=[
                {'role': 'system', 'content': 'Reply with one word: billing, bug, or other.'},
                {'role': 'user', 'content': text},
            ],
            temperature=0.0,
        )
    return (resp.choices[0].message.content or 'other').strip().lower()


@app.post('/classify-batch')
async def classify_batch(prompt: BatchPrompt, request: Request) -> dict:
    client: AsyncOpenAI = request.app.state.client
    slots: asyncio.Semaphore = request.app.state.slots

    results = await asyncio.gather(
        *(classify_one(client, slots, item) for item in prompt.items),
        return_exceptions=True,  # one bad item must not sink the batch
    )
    labels = [r if isinstance(r, str) else 'error' for r in results]
    return {'labels': labels}

asyncio.gather over a bounded helper is the sweet spot for batch classification, extraction, and tagging. The semaphore keeps the batch from becoming a self-inflicted spike, and return_exceptions=True means one malformed item returns an error marker instead of failing the whole request.

Cap the batch size in Pydantic (50 above, not 5000). A single HTTP request that fans out to thousands of upstream calls is a denial-of-service vector you wrote yourself. If a caller genuinely has thousands of items, give them a job endpoint that writes results somewhere and returns an id.

Pass temperature=0.0 for classification. It makes labels stable enough to cache, and cache hits are billed far more cheaply than fresh input, which matters once your batch job runs on every new ticket.

The knobs that actually matter

KnobWhere to set itWhy it matters
Connection pool size`httpx.AsyncClient(limits=...)` passed to `AsyncOpenAI`Keep it above your semaphore, or httpx queues requests invisibly and your limit stops meaning anything
Semaphore size`lifespan`Turns traffic spikes into short waits instead of upstream errors
Streaming pool size`lifespan`, separate from the main poolLong streams hold a slot for their entire lifetime
TimeoutClient constructor, or `client.with_options(timeout=...)` per callFails stalled requests fast instead of pinning workers
max_retriesClient constructorThe SDK retries connection errors and transient 5xx/429 with backoff for you

Error handling the SDK already does for you

  • Catch exceptions at the endpoint boundary, not around every await. Translate to a stable 502 or 504 and never leak upstream error text to clients.

  • The OpenAI-compatible SDK retries connection errors and transient 5xx or 429 responses with exponential backoff. Your knob is max_retries. A hand-rolled retry loop stacked on top multiplies attempts rather than adding resilience.

  • Retries cannot rescue a stream that already emitted tokens. Either buffer until the first chunk arrives and commit there, or surface a terminal error event on the wire after partial output.

  • Client errors such as malformed input or oversized context will never succeed on retry. Validate with Pydantic and cap input length before the call leaves your process.

  • Log a request id alongside the model name so a spike in 502s is attributable to a deploy, a prompt change, or an upstream incident.

  • Do not log full prompts and completions by default. Redact, sample, or hash them; your users' data is not telemetry.

Routing between flash and pro

deepseek-v4-flash is the right default: fast, inexpensive, and good enough for summarization, classification, extraction, and most chat turns. Reserve deepseek-v4-pro for the minority of requests where the task is genuinely hard — multi-step reasoning, tricky code, or output that a human will sign off on. Pro costs more than flash, so route to it deliberately rather than by default.

A workable pattern is a cheap heuristic first: short inputs and clearly templated tasks go to flash; anything flagged as complex, or any request that already failed a quality check, escalates to pro. Expose the model as an optional field only if you validate it against an allowlist, so a caller cannot send a string that does not exist.

Where you can, cache aggressively. Identical or near-identical prompts across a batch cost less when they hit cache, and off-peak traffic is priced more kindly than peak. Those two levers move your bill more than micro-optimizing the prompt text.

AiCredits sells DeepSeek API credits to developers outside mainland China, payable by card or PayPal with no Chinese phone number or bank account required, and the base URL in the code above is all you change. Current rates are at aicreditsapi.com/pricing.

Throughput is not how many requests you can launch. It is how many you can finish without making the next one slower.

FAQ

Should I use OpenAI() or AsyncOpenAI() in a FastAPI endpoint?

AsyncOpenAI, always, inside async endpoints. The synchronous client blocks the event loop and serializes every request in the worker. If you are stuck on the sync client, run it in a threadpool, but you lose clean async streaming.

How many concurrent DeepSeek calls should one FastAPI worker allow?

Start around 8 to 16 in flight per process and watch p95 latency. Raise the semaphore while latency stays flat, then stop. The goal is not maximum concurrency but a flat latency curve under load, which is usually a lower number than people expect.

Do streaming and non-streaming requests need separate limits?

Yes. A streaming response holds its concurrency slot for the full generation, so a limit tuned for short completions will starve streams and vice versa. Two semaphores with different sizes keep both paths healthy.

Does the OpenAI SDK work against the AiCredits endpoint?

Yes. Point base_url at https://api.aicreditsapi.com/v1, use your AiCredits key, and everything else in your code stays the same. AiCredits sells credits to international developers with card or PayPal payment and no Chinese phone number or bank account.

What is a sensible timeout for a generation request?

Set a client-level timeout as a backstop against hung connections, and use client.with_options(timeout=...) for latency-sensitive paths that should fail fast. Streaming deserves a longer timeout than a short classification call.

Ship the boring version first

The scaling story for a DeepSeek-backed FastAPI service is not clever. It is a single client created in lifespan, a semaphore that converts spikes into waits, a streaming path that closes when the client walks away, and error handling that leans on the retries the SDK already implements instead of duplicating them.

Get those four right and you can leave the architecture alone for a long time. Add routing to deepseek-v4-pro, prompt caching, and per-tenant rate limits only when a specific metric tells you they are the bottleneck. AiCredits also publishes linting tools for teams that want their generated and hand-written code held to the same standard before it ships.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×