Versioned Prompt and Config Control for a Production RAG Service
System DesignModel answerLast updated
Design a system that versions LLM prompts, models, retrieval and decoding settings, rolls changes out gradually, traces every request to its exact config, and rolls back instantly.
Context
Your team runs a retrieval-augmented generation (RAG) assistant on top of a hosted LLM. Engineers regularly tweak the system prompt, point traffic at a different model endpoint, change how documents are retrieved, or adjust sampling settings such as temperature and top-p. Last week, a small edit to the system prompt made the assistant refuse far more requests than before. Nobody noticed for about a day.
Task
Propose a design that stops this kind of silent regression. Cover these four areas:
- Versioning. Where and how do you store prompt templates, model metadata and hyperparameters so that each request maps to one immutable identifier for the exact configuration it ran with?
- Gradual release. How do you ship a new system prompt to 5% of traffic and judge its effect on downstream signals such as faithfulness, latency and token cost before widening the rollout?
- Traceability. Given one production log entry for a hallucinated answer, how do you rebuild precisely what happened, including the retrieved context and the prompt that was used?
- Recovery. How do you revert to the last known good configuration quickly, without shipping new application code?
Constraints
- Throughput of thousands of requests per second.
- User data that appears in prompts must follow privacy rules, for example PII masking in stored logs.
- The configuration system must be highly available and must not be a single point of failure for inference.
State your assumptions, sketch the architecture, and discuss trade-offs and failure modes.
Hints
Hint 1
Treat prompts, model choices, retrieval settings and sampling parameters as release artifacts: immutable, content-addressed bundles, with a separate small mutable pointer that decides which bundle serves which traffic.
Hint 2
Keep the config service off the hot path: push snapshots to each serving pod, cache them in memory and on disk, and let pods keep serving the last snapshot if the control plane is down.
Hint 3
For rollouts, compare canary and control over the same time window using behavioral metrics (refusal rate, faithfulness sample scores, latency, cost), and use thresholds that trigger automatic rollback.
Hint 4
For debugging, log a structured record per request (bundle ID, index snapshot ID, chunk IDs, rendered-prompt hash, model version, params) and keep retrieval indexes versioned so chunk IDs stay resolvable.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is release engineering applied to LLM behavior. Prompts, model versions, retrieval settings and decoding parameters are deployable artifacts and should be handled like code: immutable, reviewed, evaluated before release, rolled out gradually, observable, and reversible in seconds.
The incident exposes three gaps: requests were not attributed to a config, there was no canary-versus-control comparison, and no alert watched a behavioral metric such as refusal rate.
Assumptions and sizing
- Peak 5,000 RPS; about 3k input tokens (mostly retrieved context) and 400 output tokens per request.
- Config resolution must cost under 1 ms, so it happens in-process with no network call per request.
- A trace is about 15 KB compressed, so 5,000 RPS is roughly 75 MB/s, or about 6.5 TB/day. Keep metadata for all traffic, and full payloads only for a sample plus all flagged requests.
- Detection target: minutes, not hours. To see a refusal rate move from 2% to 3% (alpha 0.05, power 0.8) you need about 3k samples per arm. A 5% canary at 250 RPS gets that in roughly 12 seconds, so the pipeline latency, not statistics, is the bottleneck.
1. Data model: immutable bundles, mutable pointers
Separate what a config is from who receives it.
PromptTemplate (id, version, body, input_schema, owner) immutable
ConfigBundle (bundle_id = sha256(canonical_json)) immutable
prompt, model{endpoint, pinned_version, max_tokens},
decoding{temperature, top_p, seed},
retrieval{index_snapshot_id, embedder, top_k, reranker},
guardrails{refusal_classifier, pii_policy},
eval_report_id, created_by, approved_by
Route (name, revision, allocations[{bundle_id, weight, mode}],
last_known_good_bundle_id) mutable, audited
The experiment ID is (route, revision, bundle_id). Since bundle_id is a content hash, the same ID always means the same behavior. Bundles are authored via Git PRs, schema-validated in CI, and published to a registry (Postgres for metadata, object storage for bodies). Promotion only moves pointers; nothing is edited in place.
2. Architecture
Control plane (low QPS, strongly consistent): registry, offline eval service, rollout controller. The controller publishes a full snapshot of routes and referenced bundles (megabytes) to a replicated store (etcd, or object storage plus pub/sub, or a CDN).
Data plane (high QPS, available): each pod runs an SDK or sidecar that watches for snapshots (1-5 s propagation), keeps them in memory, persists the last good one to disk, and has a baked-in default bundle for cold starts. The config service is therefore never on the request path. If it fails, pods keep serving and only new rollouts pause.
Request flow:
- Compute
bucket = hash(user_id, route_salt) mod 10000for sticky assignment, so a user does not flip variants mid-conversation. - Resolve
bundle_idlocally and stamp it on the request context. - Run retrieve, render, generate, guardrails.
- Emit a structured trace event to Kafka asynchronously, so logging never blocks the response.
Trace pipeline: Kafka, then a PII redaction stream processor, then metadata into ClickHouse/BigQuery and payloads into object storage. A streaming job computes per-bundle refusal rate, p50/p99 latency, tokens and cost. An async LLM-judge worker scores 1-2% of traffic per bundle for faithfulness and relevance.
3. Staged rollout
- Offline gate. Run a golden set and an adversarial set (including borderline requests that should not be refused) in CI. Block on regressions.
- Shadow mode. Mirror 1-5% of requests to the candidate and discard the output. Reuse the same retrieved context to isolate the prompt change, disable side effects (tools, memory writes), and cap spend with a token budget.
- Canary 1% to 5% to 25% to 100%. Compare canary with control over the same time window to cancel time-of-day and traffic-mix effects. Track refusal rate, faithfulness, p99 latency, tokens and cost per request, thumbs-down rate and error rate. Use sequential testing (SPRT or mSPRT) so early stopping does not inflate false positives. Each metric has a guardrail; a breach triggers automatic rollback. Require a bake time between steps.
- Promotion. A bundle becomes
last_known_goodonly after a full bake at 100% (for example 24 h).
Trade-off: slower metrics (judge scores, user feedback) lag, so fast proxies (refusal classifier, length, errors) gate early steps while slow ones gate promotion.
4. Observability and attribution
Log a structured record per request, not free text:
request_id, ts, route_rev, bundle_id, user_bucket
input: redacted_query, conversation turn ids
context: index_snapshot_id, [chunk_id, chunk_version, score, rank]
prompt: template_version, rendered_prompt_hash, token counts per section
model: endpoint, requested_version, provider fingerprint, seed, params
output: redacted_response, finish_reason, refusal_flag, guardrail verdicts
timing/cost: retrieval_ms, ttft_ms, total_ms, cost_usd
To debug a hallucination: look up the request_id, fetch the bundle by hash, fetch the exact chunks from the immutable index snapshot (retain snapshots about 30 days), re-render the prompt and check it against rendered_prompt_hash, and optionally replay with the same model version and seed. If the needed fact was absent from context, it is a retrieval bug; if present and contradicted, it is a prompt or generation bug.
Privacy. Redact PII (regex plus NER) in the stream processor before anything is persisted, tokenize identifiers with a keyed hash where joins are needed, encrypt payloads, apply short retention to raw text and longer retention to metadata, restrict payload access with audited, role-based reads, and support deletion by user ID.
5. Incident response
- Each route stores
last_known_good_bundle_id. Rollback is a single pointer change: set the allocation to 100% on that bundle, creating a new audited revision. - Snapshot propagation delivers it to all pods in seconds; no code deploy.
- Automatic rollback fires from the rollout controller on guardrail breaches. A manual "big red button" CLI exists for humans.
- Pods must handle a missing bundle gracefully by using the disk-cached snapshot, so rollback works even during partial outages.
- Alert on behavioral metrics per bundle (refusal rate, empty-answer rate, cost per request), not only on errors and latency. This is what would have caught the 24-hour incident in minutes.
6. Availability and failure modes
- Control plane down: data plane serves cached snapshots; rollouts freeze.
- Bad snapshot: validate before publishing, version snapshots, and have pods reject snapshots that fail schema checks and keep the previous one.
- Model provider outage: bundles can declare a fallback bundle or model, with circuit breakers.
- Trace pipeline backlog: drop payloads before metadata, and never block requests.
Common mistakes
- Editing prompts in place or storing them only in application code.
- Fetching config over the network on every request.
- Randomizing per request rather than per user, which breaks conversations and muddies metrics.
- Watching only latency and error rate, not behavioral metrics.
- Logging raw PII, or forgetting to version the retrieval index so chunk IDs stop resolving.
- Treating a model alias such as "latest" as a pin, which allows silent provider-side changes.