# Fine-Tuning vs. RAG: Cost and Architecture Trade-offs for SaaS

URL: https://byshahid.com/engineering/fine-tuning-vs-rag-cost-saas/
Author: Muhammad Shahid, Senior AI Software Engineer & Full Stack Developer (https://byshahid.com/)
Published: 2026-11-12

**Quick answer:** RAG changes what the model reads: it retrieves your documents at question time, so it suits facts that change, need sources or differ per customer. Fine-tuning changes the model: it suits a fixed format, tone or narrow task. On cost, RAG has low fixed costs and pays per request; a self-hosted fine-tuned model pays mostly for hosting. In a worked example with current Claude prices, a fine-tuned model only became cheaper at about 144,000 requests a month against RAG on Sonnet 5.5, and about 2.8 million against RAG on Haiku 5.5.

- **RAG is for:** Knowledge: changing facts, citations, per-customer data
- **Fine-tuning is for:** Behaviour: format, tone, a narrow repeated task
- **RAG cost shape:** Small fixed cost plus a cost per request
- **Fine-tuning cost shape:** Training runs plus hosting that rises in steps
- **Worked example:** Claude list prices; hosting and training are stated assumptions

"Should we fine-tune or use RAG?" is one of the first architecture questions a SaaS team asks when it adds AI. The answer depends less on taste than on two things you can write down: what is wrong with the model's answers today, and how much traffic you will serve. This article explains what each approach really changes, breaks down the **cost of fine-tuning vs RAG for a SaaS product**, and gives you a small cost model in TypeScript, tested and run, with a worked example that uses current Claude API list prices.

## Fine-tuning or RAG: which one does a SaaS product need?

Most SaaS products should start with **RAG on a general API model** and consider fine-tuning only later, for a specific behaviour or for cost at high volume. The reason is that the most common problem, "the model does not know our data", is a knowledge problem, and RAG solves knowledge problems without training anything. Fine-tuning solves behaviour problems: a model that will not stick to your output format or tone even when the prompt shows it how. Many products end up using both: retrieval for facts, a tuned or smaller model for a narrow, high-volume step.

## What is RAG, and what is fine-tuning?

![Side-by-side architecture: RAG searches your documents and adds the top chunks to the prompt of a general API model; fine-tuning trains a model on example pairs and then answers with a short prompt](https://byshahid.com/blog/img/engineering/fine-tuning-vs-rag-cost-saas/architecture.svg)

*RAG changes what the model reads. Fine-tuning changes the model.*

**Retrieval-augmented generation (RAG)** finds the passages from your own data that are relevant to a question and puts them in the prompt, so a general model answers from them. The model itself does not change. **Fine-tuning** continues training a model on hundreds or thousands of example inputs and outputs, so its weights change and it produces that kind of output without being shown how each time.

One practical note for teams on Claude: Anthropic's API pricing page lists no fine-tuning for the current Claude models, so teams that fine-tune usually train an open-weight model they host themselves or use a provider that offers fine-tuning. That makes "fine-tune" for many teams also mean "run your own model", which is where much of its cost comes from.

## What each one actually changes

|  | RAG | Fine-tuning |
| --- | --- | --- |
| Fixes | Missing or outdated knowledge | Inconsistent format, tone or task behaviour |
| New information | Re-index the document; live in minutes | Retrain; live after a training run and checks |
| Citations | Natural: you know which chunks were used | Not available: knowledge is inside the weights |
| Per-customer data | Filter retrieval by tenant | Impractical: one model per customer |
| Deleting data | Delete the rows | Retrain without it |
| Prompt size | Larger: retrieved text in every request | Smaller: behaviour is learned |
| Hallucination on facts | Reduced, when retrieval finds the right passage | Not reliably reduced |

## Architecture of a RAG feature in a SaaS

A RAG feature has an ingestion path and a question path. Ingestion splits documents into chunks, embeds them and stores them with tenant IDs in a vector index, often in the database you already run. The question path embeds the question, retrieves the top chunks for that tenant, and sends them with stable instructions to an API model, usually streaming the answer. Everything is a normal web service: no GPUs, no training jobs. The [Next.js and pgvector RAG tutorial](/engineering/nextjs-rag-pipeline-pgvector/) on this site builds one end to end, and the [MongoDB vs pgvector benchmark](/engineering/mongodb-atlas-vector-search-vs-pgvector/) covers the search part.

## Architecture of a fine-tuned model in a SaaS

A fine-tuned setup adds a training pipeline and, if you host the model, an inference service. The pipeline collects and cleans example pairs, runs training, evaluates the result against the current model, and promotes it only if it wins. The inference service runs on GPU instances sized for peak traffic, with autoscaling, health checks and a rollback path to the previous model. When knowledge changes, the cycle runs again. It is a machine learning platform, and someone has to own it.

## How much does RAG cost?

RAG's cost is mostly per request. Each request pays for:

- **Input tokens:** instructions, retrieved chunks and the question. Stable instructions can be served from the prompt cache at a fraction of the input price; retrieved chunks differ per question and usually cannot.

- **Output tokens:** the answer, which costs several times more per token than input.

- **Embedding the question** and the vector search, both small per request.

On top sits a fixed monthly cost for the vector store, ingestion jobs and monitoring, plus re-embedding when documents change. Model choice dominates: Claude Sonnet 5.5 lists $2 per million input tokens and $10 per million output tokens, Claude Haiku 5.5 lists $0.10 and $0.50 (for prompts up to 100,000 tokens), and cache hits cost $0.10 and $0.01 per million respectively. The same RAG request is about 19 times cheaper on Haiku 5.5 than on Sonnet 5.5, if quality holds for your task.

## How much does fine-tuning cost?

Fine-tuning moves cost from each request to fixed blocks:

- **Data:** collecting, cleaning and labelling example pairs, often the biggest cost because it is people's time.

- **Training runs:** each run costs compute, and you usually need several to get one worth shipping.

- **Retraining:** whenever knowledge or requirements change, if the model carries knowledge.

- **Hosting:** GPU instances that cost the same whether they serve one request or a million, and a new instance whenever traffic exceeds the capacity of the current ones.

- **Operations:** deployment, monitoring, scaling and on-call for the model service.

Per request, a hosted fine-tuned model can be very cheap once traffic fills the GPUs, and its prompts are shorter. The question is whether your traffic is high enough to pay for the fixed part.

## A cost model you can run

```ts
// Monthly cost of answering questions with RAG on an API model vs a fine-tuned model you host.
// Every price is an input: pass your provider's current prices, never hard-code them in your app.

export interface TokenPrices {
  inputPerMTok: number; // uncached input, USD per million tokens
  cachedInputPerMTok: number; // cache hits, USD per million tokens
  outputPerMTok: number;
}

export interface RagSetup {
  prices: TokenPrices;
  systemTokens: number; // stable instructions, cached across requests
  retrievedTokens: number; // chunks added per question (k x chunk size)
  questionTokens: number;
  outputTokens: number;
  embedPerQuery: number; // USD to embed one question
  fixedPerMonth: number; // vector database, ingestion jobs, monitoring
}

export interface FineTuneSetup {
  trainingPerRun: number; // data preparation and one training run, USD
  runsPerMonth: number; // how often new knowledge forces a retrain
  hostingPerHour: number; // dedicated GPU instance, USD
  instances: number;
  maxRequestsPerMonthPerInstance: number; // capacity: more traffic needs more instances
}

const perToken = (usdPerMTok: number) => usdPerMTok / 1_000_000;

export function ragCostPerRequest(s: RagSetup): number {
  const p = s.prices;
  return (
    s.systemTokens * perToken(p.cachedInputPerMTok) +
    (s.retrievedTokens + s.questionTokens) * perToken(p.inputPerMTok) +
    s.outputTokens * perToken(p.outputPerMTok) +
    s.embedPerQuery
  );
}

export function ragMonthly(s: RagSetup, requests: number): number {
  return s.fixedPerMonth + requests * ragCostPerRequest(s);
}

export function fineTuneMonthly(s: FineTuneSetup, requests: number): number {
  const instances = Math.max(s.instances, Math.ceil(requests / s.maxRequestsPerMonthPerInstance));
  return s.trainingPerRun * s.runsPerMonth + instances * s.hostingPerHour * 730; // ~730 hours a month
}

// The smallest monthly volume at which hosting the fine-tuned model costs no more than RAG, or null.
// Hosting cost rises in steps (one more instance per block of capacity) while RAG rises in a straight
// line, so check each step's range instead of assuming one crossing.
export function breakEven(rag: RagSetup, ft: FineTuneSetup, limit = 1e9): number | null {
  const perRequest = ragCostPerRequest(rag);
  const capacity = ft.maxRequestsPerMonthPerInstance;
  for (let instances = ft.instances; (instances - 1) * capacity < limit; instances++) {
    const from = instances === ft.instances ? 0 : (instances - 1) * capacity + 1;
    const to = Math.min(instances * capacity, limit);
    const hosting = fineTuneMonthly(ft, to);
    if (perRequest <= 0) return rag.fixedPerMonth >= hosting ? from : null;
    const n = Math.max(from, Math.ceil((hosting - rag.fixedPerMonth) / perRequest));
    if (n <= to) return n;
  }
  return null;
}
```

The model keeps every price as an input, so it stays correct when prices change. `ragCostPerRequest` charges cached instructions at the cache-hit price and retrieved chunks and the question at the full input price, plus output and the embedding. `fineTuneMonthly` adds training runs and hosting, and adds an instance for each block of capacity, which is why hosting cost rises in steps rather than a line. `breakEven` finds the smallest traffic at which the fine-tuned setup costs no more than RAG. Because hosting rises in steps, it checks each step's range: an early version that assumed a single crossing returned the wrong answer, and the test now covers that case.

```ts
import assert from "node:assert/strict";
import { breakEven, fineTuneMonthly, ragCostPerRequest, ragMonthly } from "./cost";

const rag = { prices: { inputPerMTok: 2, cachedInputPerMTok: 0.1, outputPerMTok: 10 }, systemTokens: 1_000_000, retrievedTokens: 0, questionTokens: 1_000_000, outputTokens: 1_000_000, embedPerQuery: 0, fixedPerMonth: 0 };
assert.equal(ragCostPerRequest(rag), 0.1 + 2 + 10); // one million tokens of each kind
assert.equal(ragMonthly({ ...rag, fixedPerMonth: 5 }, 2), 5 + 2 * 12.1);
const ft = { trainingPerRun: 100, runsPerMonth: 2, hostingPerHour: 1, instances: 1, maxRequestsPerMonthPerInstance: 10 };
assert.equal(fineTuneMonthly(ft, 5), 200 + 730);
assert.equal(fineTuneMonthly(ft, 25), 200 + 3 * 730); // 25 requests need 3 instances of 10
const cheap = { ...rag, prices: { inputPerMTok: 0, cachedInputPerMTok: 0, outputPerMTok: 0 }, embedPerQuery: 0.001, systemTokens: 0, questionTokens: 0, outputTokens: 0 };
const big = { trainingPerRun: 0, runsPerMonth: 0, hostingPerHour: 1, instances: 1, maxRequestsPerMonthPerInstance: 1e12 };
assert.equal(breakEven(cheap, big), 730_000); // $730 a month equals 730,000 requests at $0.001
assert.equal(breakEven({ ...cheap, embedPerQuery: 0 }, big), null);
// Step costs: one instance covers 100 requests; RAG crosses inside the first step, so that is the answer.
const steps = { trainingPerRun: 0, runsPerMonth: 0, hostingPerHour: 0.1, instances: 1, maxRequestsPerMonthPerInstance: 100 };
assert.equal(breakEven({ ...cheap, embedPerQuery: 1 }, steps), 73); // $73 of hosting = 73 requests at $1
console.log("cost tests pass");
```

```bash
npm install -D typescript tsx @types/node
npx tsx src/cost.test.ts   # checks the formulas, including the step costs
npx tsx src/example.ts     # prints the table below
```

## Worked example: three setups at five traffic levels

```ts
import { breakEven, fineTuneMonthly, ragCostPerRequest, ragMonthly, type FineTuneSetup, type RagSetup } from "./cost";

// Claude API list prices from Anthropic's pricing page (USD per million tokens, November 2026).
const SONNET = { inputPerMTok: 2, cachedInputPerMTok: 0.1, outputPerMTok: 10 };
const HAIKU = { inputPerMTok: 0.1, cachedInputPerMTok: 0.01, outputPerMTok: 0.5 };

// A support assistant: 1,500 cached instruction tokens, 6 chunks of 400 tokens, 100-token
// questions, 350-token answers. Embedding and fixed costs are example assumptions.
const base = { systemTokens: 1500, retrievedTokens: 2400, questionTokens: 100, outputTokens: 350, embedPerQuery: 0.00001, fixedPerMonth: 50 };
const ragSonnet: RagSetup = { ...base, prices: SONNET };
const ragHaiku: RagSetup = { ...base, prices: HAIKU };

// A self-hosted fine-tuned open-weight model. All numbers are example assumptions: one GPU
// instance at $1.50 an hour, a $200 training run each month, 3 million requests per instance.
const selfHosted: FineTuneSetup = { trainingPerRun: 200, runsPerMonth: 1, hostingPerHour: 1.5, instances: 1, maxRequestsPerMonthPerInstance: 3_000_000 };

const usd = (n: number) => "$" + n.toLocaleString("en-US", { maximumFractionDigits: n < 1 ? 5 : 0 });
console.log("RAG per request  Sonnet 5.5:", usd(ragCostPerRequest(ragSonnet)), " Haiku 5.5:", usd(ragCostPerRequest(ragHaiku)));
for (const n of [10_000, 100_000, 1_000_000, 5_000_000, 10_000_000]) {
  console.log(String(n).padStart(10), "RAG Sonnet", usd(ragMonthly(ragSonnet, n)).padStart(9), " RAG Haiku", usd(ragMonthly(ragHaiku, n)).padStart(8), " fine-tuned", usd(fineTuneMonthly(selfHosted, n)).padStart(8));
}
console.log("break-even vs Sonnet RAG:", breakEven(ragSonnet, selfHosted)?.toLocaleString("en-US"), "requests/month");
console.log("break-even vs Haiku RAG:", breakEven(ragHaiku, selfHosted)?.toLocaleString("en-US") ?? "none", "requests/month");
```

The example is a support assistant: 1,500 tokens of cached instructions, six retrieved chunks of 400 tokens, a 100-token question and a 350-token answer. RAG uses Claude list prices. The fine-tuned setup is an open-weight model on one GPU instance at an assumed $1.50 an hour, with an assumed $200 training run each month and an assumed capacity of 3 million requests per instance. These three numbers are examples, not quotes: replace them with your provider's prices and your own load tests. The output:

```text
RAG per request  Sonnet 5.5: $0.00866  Haiku 5.5: $0.00045
     10000 RAG Sonnet      $137  RAG Haiku      $55  fine-tuned   $1,295
    100000 RAG Sonnet      $916  RAG Haiku      $95  fine-tuned   $1,295
   1000000 RAG Sonnet    $8,710  RAG Haiku     $500  fine-tuned   $1,295
   5000000 RAG Sonnet   $43,350  RAG Haiku   $2,300  fine-tuned   $2,390
  10000000 RAG Sonnet   $86,650  RAG Haiku   $4,550  fine-tuned   $4,580
break-even vs Sonnet RAG: 143,765 requests/month
break-even vs Haiku RAG: 2,766,667 requests/month
```

![Line chart of monthly cost against requests per month on log scales: RAG on Claude Sonnet 5.5 rises steeply, RAG on Claude Haiku 5.5 rises slowly, the self-hosted fine-tuned model is flat at about 1,300 dollars and then steps up; break-even points near 144 thousand and 2.8 million requests](https://byshahid.com/blog/img/engineering/fine-tuning-vs-rag-cost-saas/cost-chart.svg)

*Fine-tuning pays off only above a traffic threshold, and that threshold depends on which model RAG uses.*

## What the break-even numbers say

- **The model inside RAG matters more than RAG vs fine-tuning.** Against RAG on Sonnet 5.5, the fine-tuned setup broke even at about 144,000 requests a month. Against RAG on Haiku 5.5 it took about 2.8 million. Before you fine-tune to save money, test whether a smaller API model already gives the quality you need.

- **Below the threshold, fine-tuning costs more, not less.** At 10,000 requests a month the fine-tuned setup cost $1,295 against $55 to $137 for RAG, because the GPU costs the same idle or busy.

- **Steps matter.** Just past 3 million requests the fine-tuned setup needs a second GPU, its cost jumps to $2,390, and RAG on Haiku becomes cheaper again until about 5.2 million. Real capacity numbers from a load test decide where those steps fall.

- **Output length is a big lever** for RAG: answers are the most expensive tokens. Shorter answers and the prompt cache cut RAG costs before any architecture change.

The free [AI API cost calculator](/tools/ai-api-cost-calculator/) on this site does the per-request part in the browser if you want to try your own token counts.

## When fine-tuning is the right call

- The task is narrow and repeated, such as classifying tickets, extracting fields or rewriting in a house style, and prompting with examples still misses too often.

- You need a compact output format the model keeps breaking, and structured outputs or tool schemas do not solve it.

- Traffic is high and stable enough that a smaller tuned model on your own hardware beats API prices, as measured above, and quality holds on your evaluation set.

- Latency or data-residency rules require a model running in your own environment.

## When RAG is the right call

- Answers depend on facts that change: docs, policies, product data, tickets.

- Users need sources they can check, or you need to show where an answer came from.

- Each customer has private data that only they may see.

- You need to delete data on request and prove it is gone.

- Traffic is low or uneven, so paying per request beats paying for idle GPUs.

## Combining both

The approaches stack. A common pattern is RAG for knowledge with a fine-tuned or smaller model for a narrow step around it: a cheap classifier that routes questions, a tuned extractor that turns retrieved text into structured fields, or a model tuned to write in your format from retrieved facts. Keep knowledge in retrieval even when you fine-tune, so updates stay fast and answers stay traceable.

## Multi-tenant SaaS considerations

Multi-tenancy pushes strongly toward RAG. With RAG, every chunk carries a tenant ID and retrieval filters on it, ideally enforced by the database with row-level security, so one customer's data can never appear in another's answer. With fine-tuning, anything in the training data can come out in any answer, so you cannot train one shared model on several customers' private data, and one model per customer multiplies training and hosting costs. If customers want the model to follow their own style, put the style in per-tenant instructions or examples in the prompt first.

## Quality and evaluation

Decide with numbers, not demos. Build an evaluation set of real questions with good answers, and score every option against it: the current prompt, prompt plus RAG, a smaller model, a fine-tuned model. Track the failures by type: missing knowledge points to retrieval, wrong format points to prompting or tuning, wrong reasoning points to a stronger model. Fine-tuning that improves format can quietly hurt general reasoning, so the evaluation must cover more than the behaviour you trained for.

## Security and compliance

- **Training data is hard to take back.** If personal or customer data goes into training, removing it means retraining, and models can repeat training data. Keep personal data out of fine-tuning sets, or document why it is there.

- **RAG keeps data where your access controls are.** Deleting a document deletes it from answers after re-indexing.

- **Treat retrieved text as untrusted.** Documents can contain prompt-injection text; mark it as data in the prompt and do not give the answering model tools that change things.

- **Know where requests go.** API requests leave your environment; a self-hosted model keeps them inside, which some customers require.

## Latency and operations

RAG adds an embedding call and a search before the model starts, usually tens of milliseconds, and its longer prompts take a little longer to read. A smaller fine-tuned model on dedicated hardware can answer faster, but you own its uptime, scaling and upgrades. For a small team, the operational cost of running GPUs and a training pipeline is often larger than the bill difference; count engineer time in the comparison.

## Common mistakes and how to fix them

| Mistake | What happens | Fix |
| --- | --- | --- |
| Fine-tuning to teach the model your documents | Stale answers, no sources, retraining for every update | Use RAG for knowledge |
| Comparing a fine-tuned model with RAG on the most expensive model only | Fine-tuning looks cheaper than it is | Price RAG on a smaller model too |
| Ignoring idle GPU time | Hosting cost at low traffic far above RAG | Model hosting as a fixed monthly cost |
| Assuming cost rises in a straight line | Break-even point is wrong | Model capacity steps from a load test |
| One shared model trained on customers' private data | Data can leak between customers | Per-tenant retrieval with access control |
| No evaluation set | Decisions made on a few good demos | Score every option on the same real questions |
| Long answers by default | Output tokens dominate the bill | Ask for concise answers; cache stable instructions |

## Decision checklist

![Decision flow: start with a good prompt on a strong API model; add RAG if it lacks facts; consider fine-tuning if it fails on format or a narrow task; try a smaller API model and then a tuned one if volume is high; otherwise keep the simpler system](https://byshahid.com/blog/img/engineering/fine-tuning-vs-rag-cost-saas/decision.svg)

*Move down only when measurements say the current step is not enough.*

- Write down the failures you see today and sort them into knowledge, format and reasoning.

- Fix knowledge with RAG, format with better prompts or structured outputs, reasoning with a stronger model.

- Measure quality on an evaluation set and cost with the model above, using your real token counts.

- Consider fine-tuning only for a narrow behaviour the prompt cannot fix, or for cost at traffic above your measured break-even.

- Keep the simpler system unless the numbers say otherwise.

## Summary

RAG and fine-tuning answer different questions. RAG gives a model your knowledge, with sources, per-customer filtering and cheap updates, and costs mostly per request. Fine-tuning gives a model a behaviour, and costs mostly in training and hosting, which only pays back at high, steady traffic. In the worked example, the model choice inside RAG moved the break-even point from about 144,000 to about 2.8 million requests a month, so test a smaller API model before you fine-tune to save money. Start with RAG, measure, and let the numbers move you.

## Frequently asked questions

### What is the difference between RAG and fine-tuning?

RAG retrieves relevant passages from your data at question time and adds them to the prompt; the model does not change. Fine-tuning trains the model on example inputs and outputs, so its behaviour changes.

### Is fine-tuning cheaper than RAG?

Only at high, steady traffic. A hosted fine-tuned model pays mostly fixed hosting and training costs, so it costs more than RAG at low volume and can cost less above a break-even point you can calculate.

### Can fine-tuning teach a model my company documents?

It can absorb some facts, but it is a poor way to add knowledge: answers go stale, there are no sources, and every update needs retraining. Use RAG for knowledge.

### When should a SaaS product fine-tune?

For a narrow, repeated behaviour that prompting and structured outputs cannot fix, or when traffic is high enough that a smaller tuned model beats API prices with the same quality.

### Can I fine-tune Claude?

Anthropic's API pricing page lists no fine-tuning for the current Claude models. Teams that fine-tune usually use an open-weight model they host or a provider that offers fine-tuning.

### How do I calculate RAG cost per request?

Add cached instruction tokens at the cache price, retrieved chunks and the question at the input price, the answer at the output price, and the embedding of the question.

### What drives RAG cost the most?

The model choice and the answer length. In the worked example, the same request was about 19 times cheaper on Claude Haiku 5.5 than on Claude Sonnet 5.5.

### Is RAG or fine-tuning better for multi-tenant SaaS?

RAG. Retrieval can be filtered per tenant and enforced by the database, while a shared fine-tuned model can repeat any customer's training data to anyone.

### Can I use RAG and fine-tuning together?

Yes. Keep knowledge in retrieval and use a tuned or smaller model for a narrow step, such as routing questions or extracting fields from retrieved text.

### Does fine-tuning reduce hallucinations?

Not reliably on facts. RAG with good retrieval and an instruction to answer only from sources does more for factual accuracy.

### How do I delete customer data from an AI feature?

With RAG, delete the documents and re-index. With fine-tuning, the data is in the weights, so removing it means retraining without it.

### How should I decide between RAG and fine-tuning?

Sort today's failures into knowledge, format and reasoning, fix each with the matching tool, and measure quality on an evaluation set and cost with your real token counts and traffic.

## Sources

- [Anthropic Docs: Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing)
- [Anthropic Docs: Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
- [Anthropic Docs: Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
- [PostgreSQL Docs: Row security policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html)
- [OWASP Top 10 for LLM Applications](https://owasp.org/www-project-top-10-for-large-language-model-applications/)

See the related service: https://byshahid.com/hire/ai-integration-engineer/
