Prompt Engineering That Survives Production
By the Katkat team · Updated · 9 min read
Quick overview
Learn how to write system prompts, choose few-shot examples, decompose tasks, version prompts and test them like code so LLM features hold up in production.
After this lesson you will be able to explain why a prompt in production is an artefact to be designed, versioned and tested, not a string someone tweaked until the demo worked. You will be able to describe what belongs in a system prompt, when few-shot examples help and when they hurt, how to split a task into steps, and how to build a regression suite so a prompt change cannot silently break the product.
What a production prompt is
A prompt is the input to a probabilistic function. The model reads the whole prompt as one token sequence and predicts a continuation. Nothing in the model "executes" your instructions. It conditions on them, so they raise the probability of some outputs and lower others, and they are never guaranteed.
That framing explains most production behaviour:
- The same prompt can give different outputs, especially at non-zero temperature (see Decoding: Greedy, Temperature, Top-k and Top-p).
- A small wording change can shift behaviour on inputs you did not look at.
- A model upgrade is effectively a prompt change, because the same text is interpreted by different weights.
In production, then, prompt engineering means making behaviour predictable across many inputs and across time. A prompt that works on five hand-picked examples has not been validated.
System prompts: structure and responsibilities
The system prompt carries the instructions that stay constant across requests. A useful way to organise one is by responsibility:
| Section | What it holds | Example |
|---|---|---|
| Role and goal | Who the model is acting as and what success means | "You answer billing questions for a SaaS product." |
| Rules and constraints | What to do and not do, with priorities | "Never promise refunds. If unsure, hand off." |
| Context and knowledge | Stable facts, policies, glossary | Plan names, refund window |
| Output contract | Format, fields, length, tone | "Return JSON with keys answer, confidence." |
| Handling of edge cases | What to do when input is off-topic, ambiguous or hostile | "If the question is not about billing, say so briefly." |
Some practical rules:
- Be specific and testable. "Be concise" is vague. "Answer in at most three sentences" can be checked by a script.
- Say what to do, not only what to avoid. A list of prohibitions leaves the model guessing about the allowed behaviour.
- Explain the reason when a rule is non-obvious. Models generalise better from "do not quote prices because they change daily" than from a bare ban.
- Separate instructions from data. Put user text or retrieved documents in clearly delimited blocks and tell the model to treat them as data. This also helps against injection (see Prompt Injection and Guardrails).
- Keep it short enough to maintain. Every sentence is a behaviour you must test. Prompts that grow by appending a patch for each bug become contradictory.
The system prompt is not a security boundary. Anything in it can be leaked or overridden by a determined user, so never put secrets in it.
Few-shot examples
Few-shot prompting means including input-output examples in the prompt so the model infers the pattern. The idea is established in the GPT-3 paper, "Language Models are Few-Shot Learners".
Examples are best at conveying things that are hard to describe in words: a labelling convention, an unusual output format, a tone, or how to handle a borderline case.
How to choose them:
- Cover the distribution and the edges. Include a typical case, a tricky case and a case where the right answer is "none of the above" or "refuse".
- Make them consistent. If two examples label similar inputs differently, the model will pick up the noise.
- Vary surface form. If every example starts the same way, the model may copy that phrasing.
- Mind the order and balance. Models can be biased toward the label that appears most often or most recently, so balance classes and check whether reordering changes results.
- Use the exact output format you want. The model will imitate it, including mistakes.
Trade-offs:
- Examples cost tokens on every request (worked example below).
- They can narrow behaviour: the model copies the examples instead of reasoning about the new input.
- Fixed examples go stale when policy changes. Dynamic selection, where you retrieve the most similar examples for each input, adapts better but adds a retrieval step and makes tests harder to reproduce.
If you need many examples to get acceptable quality, compare with fine-tuning (see Fine-Tuning, RAG or Prompting: How to Choose).
Worked example: what a fixed prefix costs
Suppose a classifier has a 1,200-token system prompt and 4 few-shot examples of about 150 tokens each.
- Fixed prefix per request: 1,200 + 4 × 150 = 1,800 tokens.
- At 500,000 requests per day: 1,800 × 500,000 = 900,000,000 input tokens per day.
- At an illustrative price of $3 per million input tokens: 900 × $3 = $2,700 per day, before counting the user's input or any output.
Now compare two changes:
- Cut from 4 examples to 2: the prefix becomes 1,500 tokens, so 750 million tokens per day, or $2,250. That saves $450 per day, but only if your eval suite shows quality is unchanged.
- Use prefix caching. If cached input tokens are billed at a tenth of the normal price (this varies by vendor and has conditions, so check yours), the prefix cost is roughly $270 per day. This only works if the stable content comes first and the variable content comes last, so keep the prompt in that order. See Prefix Caching.
Prices here are illustrative, but the method is what interviewers want: tokens per request × requests × price.
Decomposition: splitting one prompt into steps
A single prompt that classifies, retrieves facts, drafts a reply, checks tone and formats JSON is hard to debug, because you cannot tell which part failed. Decomposition splits it into smaller calls, each with one job.
Common shapes:
| Pattern | How it works | Good for | Cost |
|---|---|---|---|
| Single prompt | One call does everything | Simple tasks, prototypes | Cheapest, hardest to debug |
| Chain | Output of step A feeds step B | Extract, then reason, then format | Latency adds up per step |
| Router | A cheap classifier picks a specialised prompt or model | Mixed workloads with different needs | Extra call, routing errors |
| Draft and check | One call produces, another verifies against rules | High-stakes output | Roughly double the calls |
Benefits: each step can be tested alone, uses a shorter prompt, can run on a smaller model, and can have a strict output format. Steps that do not depend on each other can run in parallel.
Costs: more latency, more places to fail, and errors compound. If three sequential steps are each 95% correct and failures are independent, the end-to-end rate is about 0.95 × 0.95 × 0.95 ≈ 0.857, or 85.7%. Decompose when it improves each step's accuracy by more than the compounding loses, and validate that with measurements, not intuition.
Asking the model to reason step by step inside one prompt is a related but different technique, described in "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models". Decomposition splits the work across calls, whereas chain-of-thought keeps it in one. For machine-readable outputs between steps, use structured output so a downstream step never parses free text (see Getting Reliable JSON and Structured Output).
Versioning prompts
A prompt is code that changes behaviour, so treat it as such:
- Store prompts in version control, as files or a registry, not inline strings scattered through the codebase or edited in a dashboard with no history.
- Give every prompt a version identifier and log it with each request, along with the model name and key parameters such as temperature. When a user complains, you need to know which prompt produced the answer.
- Pin the model version. Moving aliases like "latest" can change behaviour without any change on your side.
- Template with care. Keep variables explicit and escape or delimit untrusted values.
- Roll out gradually. Ship to a small share of traffic, compare metrics, then expand, with a fast rollback path.
The version is really the tuple of prompt text, model, parameters and any retrieved or few-shot content. Changing any one is a new version. The rollout side is covered in Versioning and Rolling Out Prompts and Models and How Do You Ship a Prompt Change Safely?.
Testing prompts like code
You cannot unit-test a probabilistic system with a single assertion, but you can measure it. Build layers:
| Layer | What it checks | How |
|---|---|---|
| Deterministic checks | Valid JSON, required fields, length limits, banned phrases | Plain code assertions |
| Golden set | Correct answers on curated cases | Exact match, regex, or reference comparison |
| Rubric or judge | Tone, helpfulness, faithfulness to sources | LLM-as-a-judge with a written rubric, spot-checked by humans |
| Adversarial set | Injection attempts, off-topic, empty and very long inputs | Pass if the model refuses or degrades safely |
| Production sampling | Real traffic drift | Sample logs, review, add failures to the suite |
Practical points:
- Start from real inputs. Seed the suite from logs and support tickets, and add every production bug as a permanent case.
- Run it on every change to the prompt, model, parameters or retrieval setup, ideally in CI.
- Control randomness. Use low temperature for tests, and for borderline cases run several samples and track the pass rate.
- Mind sample size. Say prompt v1 passes 172 of 200 cases (86%) and v2 passes 180 (90%). The 95% interval for 86% on 200 cases is about ±1.96 × √(0.86 × 0.14 / 200) ≈ ±4.8 points. A 4-point gap is inside that noise, so you need more cases, a paired comparison on the same inputs, or a larger effect before claiming improvement.
- Track slices, not only the average. A change that lifts the overall score while breaking one customer segment is a regression.
For judge-based scoring and its biases, see LLM Evaluation and LLM-as-a-Judge.
How does this come up in interviews?
1. "Your prompt works in the demo but fails on real users. What do you do?" Say the demo is a tiny, biased sample. Collect real inputs from logs, build a labelled eval set, find the failure categories, then fix them one at a time while re-running the whole suite to catch regressions. Mention adding every fixed bug as a permanent test.
2. "When would you use few-shot examples instead of fine-tuning?" Few-shot is the first choice when you have a handful of examples, need to iterate fast, or the pattern changes often. Fine-tuning becomes attractive when you need many examples to reach quality, the per-request token cost of examples is high, or latency matters. Back this with a token-cost calculation and an eval comparison.
3. "How would you break a complex task into prompts, and what are the risks?" Split by distinct responsibilities, give each step a strict structured output, and use smaller models where possible. Then note the risks: added latency, compounding errors (three 95% steps give about 86%), and more surface to monitor. Say you would measure end-to-end quality against the single-prompt baseline.
4. "How do you version and roll out a prompt change?" Keep prompts in version control, log the version with each request, pin the model, run the eval suite in CI, then canary to a small traffic share and compare online metrics before full rollout. Keep rollback to a one-step action.
5. "How do you know a new prompt is actually better?" Compare on the same fixed test set, ideally paired, and consider the sample size and confidence interval before trusting a small difference. Check slices and cost and latency as well as accuracy, and confirm online with an A/B test if the stakes justify it.
Common mistakes
- Editing prompts directly in production or a dashboard with no history, review or rollback.
- Judging a change by trying a few examples by hand instead of running a suite.
- Piling on patch instructions until rules contradict each other.
- Using vague instructions ("be helpful and accurate") that cannot be tested.
- Putting secrets or sensitive policy in a system prompt and assuming it is hidden.
- Mixing untrusted user or document text into instructions without delimiting it.
- Using unrepresentative or inconsistent few-shot examples, or never refreshing them when policy changes.
- Ignoring token cost of fixed prefixes, or putting variable content before stable content so caching cannot help.
- Decomposing into many steps without measuring whether compounding errors and latency outweigh the gains.
- Treating a 2–4 point gain on a small test set as a real improvement.
- Forgetting that a model version change is also a prompt change that needs re-testing.