Committed verbatim (per its own instruction #0) so every future session can re-read the full 11-phase program without it being re-pasted. This is the source-of-truth prompt driving
docs/SCALE_BASELINE.md,docs/CAPACITY_PLANNING.md,eval/load/, and every phase’s own PR. Status tracker: Phase 0 — done (seedocs/SCALE_BASELINE.md). Phases 1-10 — not started. Re-read this file at the start of every new phase’s session before planning it.
How to use this: open this codebase in your IDE’s AI agent and paste everything below the line. It is written as a phased program, not a single task. Run one phase per session (or per PR). Each phase ends with a hard verification gate — do not start the next phase until the gate passes. Commit this file to
docs/SCALE_OUT_PROMPT.mdso every session can re-read it.
You are a principal engineer taking this Text-to-SQL LangGraph platform from a single-instance, single-user-oriented application to a horizontally scalable, multi-tenant, production AI service — the way real hosted AI products (ChatGPT-, Claude-, Perplexity-style services) are built: stateless API tier, queued/streamed inference, a separate model-serving tier, distributed rate limiting and quotas, tenant isolation, and full observability.
Before writing any code, read CLAUDE.md, docs/ARCHITECTURE.md, docs/THREAT_MODEL.md,
docs/PRODUCTION_READINESS_REPORT.md, docs/PERFORMANCE_BASELINE.md, and SECURITY.md.
Follow this repo’s existing conventions: pinned dependencies with a comment explaining
each, pydantic-settings for all config, docstrings that explain why, idempotent
migrations, and a test for every behavior change. Do not remove any existing security
control (SQL validator, input guard, moderation gate, sensitive-column blocking,
read-only enforcement, prompt-injection defences). Every one of them must keep working
identically after each phase — the existing test suite and
eval/security_benchmark must stay green.
“Billions of simultaneous users” is not a real engineering target — no AI service runs that concurrently, and LLM inference cost, not code, is the binding constraint. The real goal is an architecture where capacity scales linearly by adding nodes and regions, with no single-process or single-machine component in the request path, plus a capacity model that says exactly how many nodes a given load needs.
Design targets to build and test against:
| Metric | Target |
|---|---|
| API tier | Stateless; any replica serves any request; scale 3 → N pods with zero code change |
| Concurrent connected users (validated by load test) | 10k on a small cluster; documented linear path to 1M+ |
| Time to first token (streamed) | p50 < 800 ms, p95 < 2.5 s (excluding DB execution) |
| Non-LLM API endpoints (auth, history, schema list) | p95 < 150 ms |
| Availability | 99.9% per region; no single point of failure |
| Overload behavior | Graceful: queue → 429 with Retry-After → degraded mode. Never OOM, never hang |
| Isolation | Zero cross-tenant data access, proven by automated tests |
api/main.py::ask is a sync def,
and _run_orchestrated_with_timeout spawns a raw threading.Thread per request and
abandons it on timeout (the work keeps running, uncancelled). Under load this
exhausts the AnyIO thread pool (~40 threads) and piles up orphaned inference.agent/rate_limit.py and api/rate_limit.py are
per-process (BoundedLimiterCache, SlidingWindowRateLimiter). With N replicas every
limit becomes N× the configured value. The LLM-call limiter is process-global, not
per user or tenant.request.client.host). Behind a load balancer this
is the LB’s IP (everyone shares one bucket); behind carrier NAT, thousands of users
share one IP. Limits must key on authenticated principal + tenant.PersistentClient on a container volume
(embeddings/.chroma) cannot be shared across replicas./ask returns only when the whole graph finishes
(retrieve → plan → generate → review → validate → cost → execute → insight). Users
wait for the slowest node with nothing on screen.functools.cache / lru_cache engines and schema data are
warmed per process; there is no shared cache, and nothing caches repeat questions.identity/models.py has users/roles/sessions but no
tenant_id/org_id. Database connections, golden examples, chat history, documents
and vector collections are global.docker-compose.yml is one service, 2 CPU / 4 GB,
no Kubernetes, no autoscaling, no multi-replica story.eval/load/ using k6 (preferred) or Locust, with
scenarios: login → ask (streamed) → execute → history; a burst scenario; a soak
(60 min) scenario. Mock-LLM mode (deterministic fake with configurable latency) so
the API tier can be tested independently of inference cost.docs/SCALE_BASELINE.md. Every later phase must re-run this and append its numbers.make load-test and a CI job that runs a short smoke load test (mock LLM).Gate: baseline documented; harness runs in CI.
async def end to end. Blocking work (DB drivers without
async support, sqlglot parsing, pandas) goes through bounded executors
(anyio.to_thread.run_sync with an explicit CapacityLimiter), never unbounded threads._run_orchestrated_with_timeout’s abandon-the-thread pattern. Use
asyncio.timeout / anyio.fail_after with real cancellation that propagates into
the LLM HTTP call (cancel the httpx request) and into the DB (cancel the query /
close the connection — reuse db/execution.py’s timeout logic).ainvoke / astream_events) and make graph nodes async.
Use async clients: ollama.AsyncClient or an OpenAI-compatible async client,
SQLAlchemy 2.0 create_async_engine for PostgreSQL/MySQL (asyncpg, aiomysql);
keep sync drivers (pyodbc, oracledb) behind a bounded executor with their own pool.--workers) and add
a test proving two workers produce identical behavior./livez and /readyz (readyz checks Redis,
DB pool, inference gateway reachability); keep /health as an alias.Gate: load test shows no thread-pool exhaustion at 10× baseline concurrency; cancelled requests verifiably stop LLM and DB work; full test suite green.
POST /ask/stream returning Server-Sent Events (keep /ask for compatibility;
implement it on top of the same stream by collecting events).status (node started/finished — retrieving schema, generating SQL,
validating, estimating cost, executing), sql (final validated SQL), token (insight
text streamed token by token), rows (result page), chart, error, done.
Include request_id and a monotonically increasing seq on every event.sql event is emitted only after the validator
passes. The Confirm-and-Run flow stays exactly as it is.frontend/): consume the stream with fetch + ReadableStream (not
EventSource, so the bearer header works), render node progress, stream insight text,
support Stop. Handle reconnect with Last-Event-ID where a job is resumable (Phase 4).Gate: time-to-first-event < 300 ms p95; Stop cancels server work; UI tests added.
SlidingWindowRateLimiter interface so call
sites barely change; keep the in-memory implementation as the local-dev backend
selected by config.tenant_id + user_id (+ API key id for machine clients). Use client
IP only for unauthenticated routes (login, register, password reset), and derive it
from X-Forwarded-For only when the request comes from a configured trusted-proxy CIDR.Retry-After,
before doing any expensive work. Prioritise paid tiers and interactive over batch.RateLimit-Limit, RateLimit-Remaining,
RateLimit-Reset, Retry-After on 429.Gate: with 3 replicas the effective limit equals the configured limit (± 1 window); tests for each layer; chaos test with Redis killed.
agent/llm_client.py behind a provider
interface: OllamaProvider (dev), OpenAICompatibleProvider (for vLLM / TGI
in production — continuous batching and paged attention are what make many concurrent
users affordable), and optionally a hosted API provider. Config chooses the provider
per task (SQL generation, planning, review, insight, routing) so a small fast model can
handle routing/classification while a stronger model generates SQL.202 Accepted + job id; client polls or subscribes to SSE for progress. Jobs must be
idempotent (idempotency key), have retries with a dead-letter queue, and be cancellable.stt-service
(faster-whisper), tts-service (Piper), embedding-service (text + CLIP), ocr-media-worker.
The API process must no longer import torch, ctranslate2, or opencv. Add a CI check
that fails if it does.Gate: API image size and memory drop measurably; load test with a real vLLM/Ollama backend shows queueing (not failure) under overload; circuit breaker verified by fault injection.
PersistentClient with a networked vector store behind the
existing retriever interface: pgvector (preferred — one fewer system, same Postgres
as identity) or Qdrant/Chroma server mode. Collections/partitions per tenant (or a
tenant_id filter enforced inside the repository layer, never by callers).docs/CAPACITY_PLANNING.md (replicas × workers × pool_size ≤ DB max).read_only: true on the container root filesystem.(tenant_id, user_id, updated_at). Add retention policies per tenant.Gate: kill any single API pod mid-conversation — the user’s next request succeeds on another pod with full history and context.
tenants (organizations) and memberships via an Alembic migration in
identity/migrations/. Every tenant-owned table gets tenant_id NOT NULL + index.
Write a data migration that places existing data into a default tenant.tenant_id into the access token claims and into a request-scoped context
(contextvars). Repository functions take tenant from context, not from parameters
callers can forget.SET app.tenant_id per transaction via the pooled connection)..env (keep .env as the bootstrap/default tenant path). Connection
secrets go to a secrets manager (Vault / AWS Secrets Manager / Azure Key Vault,
pluggable), encrypted at rest with envelope encryption — never in the app DB in plaintext.identity/rbac.py,
agent/authz.py) with tenant-scoped roles (tenant_admin, analyst, viewer, …)
plus per-database and per-table/column grants, so retrieval only surfaces tables the
caller may see and the validator rejects SQL referencing anything else. Keep
sensitive-column blocking. Consider row-level policies pushed down as mandatory
WHERE predicates injected at the AST level (sqlglot) for tenants that need them.tests/security/test_tenant_isolation.py):
for every endpoint and every repository function, user of tenant A must get 404 (not
403, to avoid existence leaks) for tenant B’s resources. Include vector search, semantic
cache, result cache, job status, media URLs, and SSE streams. This suite is a CI gate.Gate: isolation suite passes; RLS verified by a test that deliberately omits the tenant filter at the ORM level and still gets zero rows.
RS256/ES256 (asymmetric) instead of HS256, keys
loaded from the secrets manager, published via a JWKS endpoint, with kid-based key
rotation and overlap. Short-lived access tokens (5–15 min); keep the existing
rotating, hashed refresh tokens with reuse detection.security/oidc.py) per tenant — Entra ID,
Okta, Google Workspace — plus SAML via a broker if needed; SCIM provisioning for
enterprise tenants; enforce MFA (TOTP + WebAuthn/passkeys) per tenant policy.identity/password_policy.py.observability/redaction.py);
ensure retrieved documents/web content are always wrapped as untrusted data in prompts;
per-tenant model/tool allowlists; re-run eval/security_benchmark in CI on every PR
touching agent/, rag/, search/, or prompts.docs/security/sbom), image signing (cosign), vulnerability scanning (Trivy/Grype) as
a CI gate, Dependabot/Renovate.Gate: OWASP ASVS L2 checklist in docs/SECURITY_ASVS.md with evidence per item;
ZAP baseline scan in CI; token rotation and revocation proven across pods.
tenant_id (not user PII) as an attribute. Propagate the
existing correlation id as the trace id.observability/metrics.py and /metrics/performance rather than duplicating.observability/redaction.py), sampled at
high volume.deploy/observability/.eval/ harness before full rollout.Gate: a single request can be followed end to end in one trace; alerts fire in a staged fault-injection test.
deploy/helm/: api, worker, stt, tts,
embedding, llm-inference (vLLM on GPU nodes), Redis (or managed), Postgres (or
managed), object storage. Keep docker-compose.yml working for local dev with all
services (add Redis, Postgres+pgvector, MinIO, and a mock LLM).Gate: load test at 10× Phase 0 on the Helm deployment with autoscaling; chaos scenarios documented with results.
Write docs/CAPACITY_PLANNING.md with a spreadsheet-style model:
tokens per request (measured, per graph path), GPU throughput per model (measured on
vLLM), cache hit ratio, → GPUs, API pods, DB connections, and monthly cost per 1k / 100k /
1M daily active users. State plainly where the next bottleneck appears at each scale step
and what fixes it. Include per-tenant cost attribution so pricing tiers can be set.
/ask, /execute, and existing auth flows keep working; new
behavior behind config flags that default to today’s behavior in local dev.config/settings.py with a docstring and in .env.example.docs/ARCHITECTURE.md, docs/DEPLOYMENT.md, docs/CONFIGURATION.md,
and appends measured results to docs/SCALE_BASELINE.md. No claims without numbers.Start with Phase 0. First, give me a short summary of what you found in the code that confirms or contradicts the bottleneck list above, then the Phase 0 plan.