Putting a retrieval-augmented generation demo on the internet feels harmless right up until you look at the request path. A visitor types a sentence, and the server creates an embedding, searches PostgreSQL, calls a language model, writes a log entry, and returns a nicely formatted answer. That is useful machinery. It is also a sequence of paid or capacity-limited operations attached to a public form.

The concern was not a dramatic movie-style hack. It was much more ordinary: bots opening fresh sessions, replaying requests, and quietly turning a small herbal-research site into an unexpected inference bill. A prompt can be perfectly harmless and still be abusive if somebody sends ten thousand copies of it.

So I added several layers around Herbistry's RAG endpoint. Some stop automated form abuse, some cap usage, and some give me a central place to observe model traffic. Just as importantly, the exercise made the remaining gaps obvious. A daily quota is not a concurrency limiter, and a vector search is not an off-topic detector.

The two public doors

The interactive page lives at https://herbistry.cc/ask. The form submits JSON to POST /ask. There is also a programmatic endpoint:

GET https://herbistry.cc/api/ask?q=what%20is%20turmeric%20good%20for
X-API-Key: <user's API key>

Those endpoints have different abuse models. The browser form gets Cloudflare Turnstile plus an IP or account quota. The API requires a real API key and has a per-key quota. Letting anonymous callers hit the API directly would have made the browser protections mostly decorative.

The order of operations matters

The web request currently works like this:

question must be non-empty
        ↓
verify the Turnstile token
        ↓
check the visitor's rolling 24-hour allowance
        ↓
embed the question
        ↓
retrieve five pgvector matches
        ↓
generate the answer through LiteLLM
        ↓
record the completed search and return citations

The important detail is that the cheap rejection steps happen before embedding and generation. An empty question, a failed Turnstile check, or an exhausted allowance does not reach the model calls. Rejected requests also do not consume a completed-search slot.

Layer one: Cloudflare Turnstile

Turnstile gives the browser a token, and the browser includes it as turnstile_token in the JSON body. The server does not trust a JavaScript variable or a hidden form field on its own. It sends that token to Cloudflare's siteverify endpoint and accepts the request only when Cloudflare returns success.

When a Turnstile secret is configured, a missing token, a rejected token, or a verification-request failure closes the door with HTTP 403. For local development, leaving TURNSTILE_SECRET unset deliberately disables this check so I can test the application without fighting a browser challenge on localhost.

That development escape hatch is configuration-driven, not a special exception for my user account. Production needs the secret configured; otherwise this layer is intentionally absent.

Turnstile is good at raising the cost of cheap form automation. It is not a user identity, a quota, or proof that a question belongs on the site. I still need the layers below it.

Layer two: separate rolling quotas

The application records completed RAG searches in PostgreSQL and counts records from the last 24 hours. This is a rolling window, not a counter that everyone resets at midnight.

CallerQuota keyDefault allowance
Anonymous web visitorClient IP address5 completed RAG searches / 24 hours
Signed-in web userUser ID25 completed RAG searches / 24 hours
API callerAPI key ID100 completed RAG searches / 24 hours

The values are environment settings: RAG_ANON_LIMIT, RAG_USER_LIMIT, and RAG_APIKEY_LIMIT. When a caller reaches the limit, the endpoint returns HTTP 429 rather than starting more model work.

Ordinary product and herb searches are logged separately and do not consume the RAG allowance. Browsing the catalog should not feel like spending a scarce resource, because those requests do not invoke the embedding and generation pipeline.

API keys add another useful boundary. Herbistry stores a SHA-256 digest rather than the plaintext key, shows the plaintext only when the key is created, and lets the user revoke it. The API checks the key before doing retrieval. Its 100-request allowance is per key, not a vague promise attached to a whole account.

Layer three: LiteLLM as the model gateway

The application does not need to scatter provider-specific credentials and URLs throughout the RAG code. When configured, both operations use LiteLLM's OpenAI-compatible interface:

  • The question goes to the embeddings endpoint using the text-embedding-3-small alias.
  • The retrieved context and question go to /v1/chat/completions using the configured generation-model alias.

The current answer generator is from the gpt-oss 20B family served through Ollama. OpenAI supplies the query embedding; it is not generating the final answer in this setup. That distinction matters when reading a usage dashboard or deciding which provider limit protects which part of the request.

LiteLLM gives me one control point for model routing, credentials, and usage/cost visibility. It can also enforce gateway-side controls where those are configured. But the gateway is not automatically aware of my anonymous visitor, signed-in user, and API-key quotas. The application still owns those decisions.

Provider limits are a backstop, not the whole design

I also want tight usage, rate, and budget controls on the upstream OpenAI account or project, using whatever controls the account supports. If the application has a bug or a key leaks, a provider-side ceiling is better than discovering the problem on the invoice.

That said, provider limits are a coarse last line of defense. They do not understand that one Herbistry user has already asked 25 questions, and they do nothing to protect the separate Ollama generation service from overload. Good protection has to exist at the application and gateway layers too.

The embedding client has a 30-second timeout and three attempts with short exponential backoff. Generation has a 60-second timeout. Those bounds keep an upstream problem from waiting forever, although they are not a substitute for a full queueing policy.

Visibility: keep an audit trail

Completed searches are written to the rag_searches table with the question, caller identity where available, IP address, search type, source, result count, timestamp, and a truncated answer. The admin log view can filter ordinary searches from RAG requests and page through the history.

This serves two purposes. The same records power the rolling quotas, and they let me inspect actual usage instead of guessing why costs changed. Telemetry failures are logged without turning a successful answer into a failed user request.

There is still room to improve the accounting. A historical tokens_used column exists, but the current RAG path does not populate it with real usage returned by the providers. Gateway reports are therefore the better source for model usage until that is wired up.

The uncomfortable part: this is not concurrency control

Five requests per IP per day sounds small, but all five can arrive at the same moment. Each one can pass the quota check before any of them has completed and written its log row. That is a classic check-then-act race. The current code limits daily volume; it does not impose a strict global cap on in-flight model calls.

There is also no RAG work queue in the current application. No Redis, Celery, Temporal, or worker pool is sitting between POST /ask and the model call. FastAPI receiving requests asynchronously does not magically serialize the synchronous database and HTTP work inside the handler.

I would rather state that plainly than describe a queue I have not built.

If the current protection is not enough: add a bounded queue

The next useful layer is a small, bounded admission queue with explicit concurrency limits. The goal is not to let an unlimited number of visitors wait politely while the server runs out of memory. An unbounded queue is just a slower outage.

A reasonable policy for this site would look like this:

  1. Reject bad input, failed Turnstile tokens, and exhausted quotas first.
  2. Allow only a small, benchmarked number of generations to run at once; start conservatively with two or three.
  3. Allow one in-flight RAG request per browser user or API key so one caller cannot occupy every worker.
  4. Put excess accepted requests into a queue with a small fixed capacity.
  5. Return queue position or an honest retry response instead of pretending the work is instantaneous.
  6. When the queue is full, return HTTP 429 or 503 with Retry-After.
  7. Apply a queue-wait deadline and cancellation so disconnected clients do not leave useless work behind.

For a single application process, an asyncio.Queue and a fixed set of workers could be enough for an experiment. For multiple containers or workers, the limit has to be shared through something like Redis or a dedicated job system; otherwise each process creates its own supposedly global queue.

LiteLLM can provide an additional concurrency backstop at the gateway. That is worth configuring, but application-level fairness still matters. A gateway-wide cap does not stop one API customer from monopolizing every available slot.

Fix the quota race at the same time

A serious flood should not be able to exceed a daily allowance merely by arriving concurrently. The stronger design reserves a unit of quota in a database transaction before the expensive work begins. The reservation can later be marked completed, or released if the upstream request fails.

That changes the log from a count-after-the-fact mechanism into admission state. It is slightly more code, but it closes the gap between “five per day” and “five per day unless you send them all at once.”

Stop paying to answer obvious garbage

At the moment, any non-empty web question that passes Turnstile and quota goes through embedding, retrieval, and generation. There is no lightweight topic router and no vector-distance cutoff. The prompt tells the generator to say when the supplied context is irrelevant, but that happens after the system has paid for the work.

A better pipeline would use cheap validation first, then a small local or inexpensive scope classifier, then retrieval with a calibrated similarity threshold. Only questions that look herbal and have usable evidence would reach the large generator. Ambiguous cases could fail closed with a suggestion to use ordinary search.

The threshold needs to be measured on real relevant and irrelevant questions. Picking a cosine distance because it “looks about right” is how a relevance gate becomes a random rejection machine.

The remaining layers I would add

  • Edge controls: Cloudflare or nginx request-rate limits, body-size limits, and stricter rules for repeated API failures.
  • Input bounds: a sensible maximum question length, strict JSON handling, and consistent 400 responses for malformed requests.
  • Answer caching: a short, privacy-aware cache for identical normalized public questions, so repeated requests do not repeat model work.
  • Per-user gateway accounting: propagate an end-user identifier or use separate gateway keys where appropriate, rather than making every visitor look like one application key.
  • Alerts: notify on unusual request rates, repeated 429s, upstream latency, and sudden changes in token spend.
  • A kill switch: one configuration flag that disables generation while leaving product and herb browsing available.

The model I want

No single feature makes a public RAG endpoint safe or affordable. The useful design is a stack:

Cloudflare / nginx       block cheap floods and malformed traffic
Turnstile                raise the cost of browser automation
Application quotas       enforce fair use by IP, account, and API key
Topic + evidence gates   avoid generating answers to irrelevant input
Bounded queue            cap concurrency and fail gracefully under load
LiteLLM                  centralize model routing, controls, and accounting
Provider limits          act as the final financial backstop
Logs + alerts            show what actually happened

Herbistry currently has the browser challenge, separate rolling quotas, authenticated API access, gateway routing, timeouts, and search logs. The most important next additions are a bounded concurrency queue, transactional quota reservation, and a real relevance gate.

That is a much less glamorous answer than “the AI handles it,” but it is the one that keeps the text box from becoming an open-ended bill.