Hosting AI applications: what's different

Streaming responses, slow requests, API key costs and vector search change how you host an app. Here is what to plan for.

Three interlinked ceramic rings around a terracotta sphere

An AI application is still a web application. It has routes, a database and environment variables. What changes is the shape of the work: requests that take tens of seconds, responses that arrive word by word, an API bill that grows with every user message, and data you may be sending to a third party.

This guide is for developers building chatbots, assistants, summarisers or search features on top of a language model. By the end you will know which hosting decisions matter, have a working streaming endpoint, and know where the usual problems hide.

Calling a model API vs running your own model

There are two ways to put a model behind your app.

Call a hosted model API. You send a request to a provider and pay per token (roughly, per word fragment) of input and output. Your server does very little computing: it builds a prompt, waits and relays the answer. An ordinary app server with modest CPU and memory is enough.

Self-host a model. You run an open-weight model on your own hardware. Anything beyond small models needs a GPU with enough memory to hold the model, and that hardware is expensive whether it is busy or idle. You also take on model serving software, updates and capacity planning.

For most teams the first option is the right starting point. Self-hosting makes sense when data cannot leave your environment, when volume is high and steady enough to justify dedicated GPUs, or when you need a model the APIs don't offer.

Streaming responses

A model can take many seconds to finish an answer. Waiting for the whole thing and then sending it feels slow. Streaming sends each piece as it is generated, usually with server-sent events (SSE): an HTTP response with the text/event-stream content type that stays open while the server writes data: lines.

Here is a FastAPI endpoint that relays a streamed answer from an OpenAI-compatible chat completions endpoint. It uses plain HTTP rather than a vendor SDK, so it is an example of the pattern, not of any one provider. Check your provider's documentation for the exact URL, model names and response format.

Python
import os

import httpx
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

app = FastAPI()

API_URL = os.environ["LLM_API_URL"]  # e.g. https://api.example.com/v1/chat/completions
API_KEY = os.environ["LLM_API_KEY"]
MODEL = os.environ["LLM_MODEL"]


class ChatRequest(BaseModel):
    message: str


@app.post("/chat")
async def chat(req: ChatRequest):
    payload = {
        "model": MODEL,
        "stream": True,
        "messages": [{"role": "user", "content": req.message}],
    }

    async def relay():
        timeout = httpx.Timeout(10.0, read=120.0)
        async with httpx.AsyncClient(timeout=timeout) as client:
            async with client.stream(
                "POST",
                API_URL,
                json=payload,
                headers={"Authorization": f"Bearer {API_KEY}"},
            ) as upstream:
                if upstream.status_code != 200:
                    yield "event: error\ndata: upstream request failed\n\n"
                    return
                async for line in upstream.aiter_lines():
                    if line:
                        yield line + "\n\n"

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

The upstream lines already look like data: {...}, so the code forwards them as SSE events. The X-Accel-Buffering: no header asks nginx-style proxies not to buffer the stream. In the browser, read the response with fetch and a stream reader (the built-in EventSource only supports GET requests).

Timeouts

Long requests meet timeouts at every layer: your HTTP client, your app server, any reverse proxy and any CDN. Cloudflare's proxy, for example, returns a 524 error if the origin doesn't respond within 100 seconds by default. Set an explicit read timeout on calls to the model, as above, so a stuck request fails cleanly instead of holding a worker forever. Streaming helps because bytes start flowing within a second or two.

Background jobs and queues

Some AI work is too slow for a request: summarising a long document, processing an upload, generating embeddings for a whole knowledge base. Put it on a queue instead:

  1. The request creates a job record and returns at once with a job ID.
  2. A worker process picks the job from a queue, often backed by Redis (for example Celery or RQ in Python, BullMQ in Node).
  3. The worker saves the result to the database.
  4. The browser polls a status endpoint or listens for an update.

Store job state in the database so a restart doesn't lose work, and make jobs safe to retry, because model APIs fail and rate-limit.

API keys, rate limits and cost control

Your model API key is effectively a payment card. Anyone who has it can run up your bill.

  • Keep it on the server, in environment variables, never in front-end code. See Environment variables and secrets.
  • Rate-limit per user (requests per minute and tokens per day), with counters in Redis.
  • Cap max_tokens on every request and limit the input size you accept.
  • Set spending limits or alerts in your provider's dashboard where available.
  • Require sign-in before anyone can reach expensive endpoints.

Vector search with pgvector

Retrieval-augmented generation (RAG) means finding relevant passages from your own data and adding them to the prompt. You turn text into embeddings (lists of numbers) and search for the nearest ones. You don't need a separate vector database to start: the pgvector extension adds this to PostgreSQL.

SQL
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
  id bigserial PRIMARY KEY,
  content text NOT NULL,
  embedding vector(1536)
);

CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);

-- $1 is the query embedding, passed as a parameter
SELECT id, content
FROM documents
ORDER BY embedding <=> $1
LIMIT 5;

The number in vector(1536) must match your embedding model's output size. The extension has to be available on your PostgreSQL server; if CREATE EXTENSION fails, ask your database provider whether pgvector is supported. For the database choice itself, see PostgreSQL vs MySQL.

Caching and observability

Identical prompts produce near-identical answers, so cache where it is safe: embeddings for unchanged text, answers to common questions, and expensive retrieval results. Redis with a sensible expiry works well.

Log, for every model call, the model name, input and output token counts, latency, the user or account, and whether it succeeded. That is enough to spot one user consuming most of your budget, a prompt that suddenly doubled in size, or a provider slowdown. Avoid logging full prompts by default; they often contain personal data.

Common mistakes

  • Calling the model from the browser with your key. Fix: proxy every call through your server.
  • No timeout on model calls. Fix: set connect and read timeouts and handle failure.
  • Doing slow work inside the request. Fix: move it to a queue and return a job ID.
  • Unlimited usage per user. Fix: per-user rate limits and token caps.
  • Buffered streams. Fix: send text/event-stream, disable proxy buffering and flush each chunk.

Security notes

  • Treat model output as untrusted input. Escape it before rendering and never run it as code or SQL.
  • Prompt injection is real: text in a document or web page can instruct the model to ignore your rules. Don't give the model access to tools or data the current user couldn't access directly.
  • Read your provider's data retention and training terms, and tell users where their data goes.
  • Rotate the API key if it ever appears in a log, a repository or a screenshot.

Troubleshooting

SymptomCauseFix
Answer appears all at onceA proxy or the framework buffers the responseUse StreamingResponse, set X-Accel-Buffering: no, check CDN settings
524 or 504 errorsRequest exceeds a proxy timeoutStream, or move the work to a background job
429 from the model APIProvider rate limitRetry with exponential backoff and queue bursts
Bill much higher than expectedLarge prompts or abusive usersLog tokens per user, cap max_tokens, add rate limits
type "vector" does not existpgvector not enabledRun CREATE EXTENSION vector; if your provider supports it

Frequently asked questions

Do I need a GPU to host an AI app?

Not if you call a hosted model API. The model runs on the provider's hardware, and your app server only handles ordinary web work.

Should I use a dedicated vector database?

Start with pgvector if you already use PostgreSQL. It keeps your data in one place and handles many small to medium workloads. Consider a dedicated service when your scale or query patterns need it.

How do I deploy the streaming example?

Add fastapi, uvicorn and httpx to requirements.txt and start it with uvicorn main:app --host 0.0.0.0 --port $PORT. On Launchpad, put that command in a Procfile line starting with web:, and add the three LLM_ values in the Variables tab.

Next steps

Start with a hosted model API, stream responses, push slow work to a queue and watch your token usage from day one.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.