Rainbow Bookshop and Sunset Bookshop both pay $9 a month for the Bookshop assistant. Rainbow's AI cost is only $0.87, while Sunset's is $6.76. Both are customers, yet Sunset uses up almost your whole margin (the part of the revenue left after the AI cost). That's one of the problems that appear once the assistant is sold as AI SaaS: an AI product sold as a subscription service to many customers at once. Each paying customer is called a tenant. In this lesson the Bookshop assistant is sold to many shops: Rainbow Bookshop in one city, Sunset Bookshop in another, and so on.
Picture the manager of an apartment building. One building, many units. Unit A's key doesn't open unit B. Each unit has its own electricity meter, so its bill follows its use. The manager pays the power company, then bills the residents at a price that includes the management fee. And each unit's power is capped, so one unit can't cut the power to the whole building. In this lesson, you are the manager: the building is your app and its database, and each unit is one shop. A unit's key is each shop's API key, the meter is the record of each shop's tokens, and the power company is a provider such as OpenAI. The management fee is your margin, and the power cap is the quota and the per-user limit.
One app, many shops: keep their data apart
Multi-tenant means one app and one database serve many tenants, and every row records which shop it belongs to. Every table has a shop_id column. The shop_id used in each query comes from the verified API key, not from the request body, which anyone can fill in. The code below uses req.shop.id, which middleware (code that runs before the handler) sets from the API key, in three places: the stock query, the vector search and the cache key. ILIKE matches text without caring about upper or lower case:
// req.shop is set by middleware from the API key (next section)
const stock = await db.query(
"SELECT title, price, stock FROM books WHERE shop_id = $1 AND title ILIKE $2",
[req.shop.id, `%${title}%`],
);
const similar = await db.query(
"SELECT title, synopsis FROM books WHERE shop_id = $1 ORDER BY embedding <=> $2 LIMIT 5",
[req.shop.id, questionVector],
);
const cacheKey = `shop:${req.shop.id}:v${stockVersion}:${normalize(question)}`;
- SQL and vector search are both filtered. RAG that forgets the filter takes another shop's synopses and stock. In pgvector, give
shop_ida B-tree index, so Postgres picks that shop's rows first. If the filter runs only after an approximate index, it can return fewer rows than theLIMIT(the Vector Databases lesson). In Pinecone, use one namespace (a separate data space) per shop. - The answer cache is per shop too. The cache key from the Cost Optimization & Caching lesson (question + stock version) gets
shop_idas well. Without it, an answer cached for Rainbow is handed to Sunset's customers. - In Laravel, a global scope on the
Bookmodel addswhere shop_idto every query, so nobody forgets.
Now guess. Sunset Bookshop doesn't sell The Rainbow Troops, while Rainbow Bookshop has 12. A Sunset customer asks "Do you have The Rainbow Troops?", and the catalogue query forgot WHERE shop_id = ?. What does the assistant answer?
Without the filter, the assistant answers "Yes! The Rainbow Troops, 12 in stock, $18". That's Rainbow Bookshop's stock. The answer is wrong for a Sunset customer, and another shop's data leaks. With the filter: "The Rainbow Troops isn't in Sunset Bookshop's catalogue yet." Add this case to the eval set so a leak is found before release.
An API key per shop, stored as a hash
Each shop calls your API with its own key. Your OpenAI key stays one key, in the server's .env (the file that holds the server's secrets), and no shop ever sees it. The code below creates a new key for one shop, then finds the shop from the key sent in the Authorization header:
import { randomBytes, createHash } from "node:crypto";
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
async function createKey(shopId) {
const key = "tb_live_" + randomBytes(24).toString("base64url"); // 32 random characters
await db.insert("api_keys", { shop_id: shopId, prefix: key.slice(0, 12), hash: sha256(key), revoked: false });
return key; // shown ONCE to the shop owner, then forgotten
}
async function shopFromKey(req) {
const key = (req.headers.authorization ?? "").replace("Bearer ", "");
const row = await db.first("SELECT shop_id FROM api_keys WHERE hash = $1 AND revoked = false", [sha256(key)]);
return row?.shop_id ?? null; // null: answer 401, the model isn't called
}
- The database only stores the SHA-256 hash. If the database leaks, a hash can't be used to call your API. In the Lab,
tb_live_A6NXXnvt...has the hash411fbfb7d7c3a497.... - SHA-256 is enough because the key is 24 random bytes (192 bits), so it can't be guessed one by one. Passwords are different: made by people and short, so they need bcrypt or Argon2 (ways of hashing that are slow on purpose).
- The
prefix(the key's first 12 characters,tb_live_A6NX) shows on the dashboard (the shop owner's summary page), so the owner knows which key is in use. If a key leaks, make a new one and revoke the old one.
Streaming through your backend, reading the meter
The customer's browser never talks to OpenAI directly. The server forwards the stream as in the Streaming Responses lesson. The last event, response.completed, carries usage (how many tokens were used). That number is recorded as the meter. Each question gets one row in the usage_log table, with its shop_id and its kind (stock or recommendation):
await readSSE(upstream.body, async (event) => {
if (event.type === "response.output_text.delta") res.write(`data: ${JSON.stringify({ text: event.delta })}\n\n`);
if (event.type === "response.completed") {
const u = event.response.usage;
await db.insert("usage_log", {
shop_id: req.shop.id, model: event.response.model, kind: questionKind,
input_tokens: u.input_tokens, cached_tokens: u.input_tokens_details.cached_tokens, output_tokens: u.output_tokens,
});
}
});
Watch out: readSSE calls your callback without await. If db.insert fails (the database connection is down, say), its promise is rejected with nothing to catch it. Node 24 then stops the process with exit code 1, so every other shop's stream is cut too. So first put the response in the finished variable, then record the meter after readSSE returns, inside try/catch:
let finished = null; // the response.completed event's response
await readSSE(upstream.body, (event) => {
if (event.type === "response.output_text.delta") res.write(`data: ${JSON.stringify({ text: event.delta })}\n\n`);
if (event.type === "response.completed") finished = event.response;
});
if (finished) {
const u = finished.usage;
try {
await db.insert("usage_log", {
shop_id: req.shop.id, model: finished.model, kind: questionKind,
input_tokens: u.input_tokens, cached_tokens: u.input_tokens_details.cached_tokens, output_tokens: u.output_tokens,
});
} catch (err) {
console.error("meter not recorded:", req.shop.id, err.message); // reconcile with the provider's dashboard
}
}
If db.insert fails here, catch only logs the error, and the process keeps running. Cost is computed from the usage_log table and the price list. A stream cut before response.completed brings no usage, so reconcile your meter with the provider's usage dashboard every month.
Tokens become cost, cost becomes price
Assumptions from the Cost Optimization & Caching lesson: each question is 1,200 input tokens (1,100 of them a cached prefix), with 40 output tokens for stock and 200 for a recommendation. In each sum below, 100 input tokens pay the normal price, 1,100 tokens pay the cache read price, then the output tokens are added:
- stock,
gpt-6-luna: (100 × $0.10 + 1,100 × $0.01 + 40 × $0.50) / 1,000,000 = $0.000041 - recommendation,
gpt-6.1-sol: (100 × $2 + 1,100 × $0.10 + 200 × $10) / 1,000,000 = $0.00231, 56 times as much
October's meter:
| Shop | Stock | Recommendations | AI cost |
|---|---|---|---|
| Rainbow | 4,200 | 300 | $0.87 |
| Sunset (book club) | 1,500 | 2,900 | $6.76 |
Say the Shop plan (the subscription plan for shops) has a flat price, one fixed price: $9 for 5,000 questions of any kind. Rainbow's margin is 90.4% (from its cost before rounding, $0.8652), but Sunset's is only 24.9%. If one shop spends its 5,000 questions on recommendations, its cost is $11.55: a loss. This is the biggest business challenge of an AI SaaS product: managing AI cost per user while keeping the margin. The AI cost grows with use, unlike ordinary SaaS where the cost per user is almost fixed. (Margin = (revenue - AI cost) / revenue; servers, the payment gateway and taxes aren't counted yet.)
The way out is usage-based pricing with tiers and a credit system, the most common way to price AI SaaS. Usage-based means the price follows use, a tier is a plan level (Free, Shop), and a credit is a unit of use. A stock question = 1 credit, a recommendation = 50 credits, roughly following their cost ratio (56 times). The Shop plan's $9 holds 50,000 credits, and more costs $0.18 per 1,000 credits. 1,000 of the most expensive credits (recommendation credits) cost $0.046 in AI and sell for $0.18, so every credit sold has a margin of at least 74%. Sunset uses 146,500 credits, 96,500 more than the plan holds: $9 + 96.5 × $0.18 = $26.37, a 74.4% margin. Rainbow stays at $9 (19,200 credits).
- The quota is checked before the model is called. The quota is the plan's allowance of credits. Out of credits on the Free plan? Refuse with "this month's quota is used up" and an upgrade link.
- The free tier is capped per shop, not per account. The free tier (the Free plan) has 1,000 credits, at most $0.046 of AI cost per shop. A shop that makes 40 free accounts gets 40,000 credits. Prevent that in three ways: verify a WhatsApp number or domain per shop, stop the Free plan at 1,000 credits, and keep the limit of 20 questions per 10 minutes per user from the AI Safety & Content Filtering lesson.
Observability: a cost dashboard per shop and eval regressions
Observability means you can see what happens in your app from the data you record:
- A dashboard per shop per day: requests, tokens, cost, credits left, margin. Set an alert (an automatic warning) for when one shop's daily cost is more than 3 times its 7-day average. Such a jump is a sign of abuse, an agent loop, or a bug.
- Per question type and per model: when recommendations suddenly climb, you know where the bill comes from.
- Quality regressions: the 12 eval cases (the Evaluating AI Output lesson) plus a "no other shop leaks" case run in CI every time the prompt, model or data changes. Watch the clicks on the "Report this answer" button per shop too.
Law and trust: the basics you must have
- The provider's data terms (checked October 2026): OpenAI doesn't train on API data unless you opt in. Abuse monitoring logs are kept for up to 30 days, and the Responses API stores responses for 30 days unless you send
store: false. At Anthropic, retained data is never used for training without your express permission, and the Fable and Mythos models require 30-day retention (keeping the data for 30 days). OpenAI and Anthropic both have a Data Processing Addendum (DPA), an agreement on how the provider processes data, for business customers. - Your own terms with the shops: terms of service and a privacy policy that names the subprocessors (other companies that also process the data: OpenAI, Anthropic, hosting). Sign a DPA with each shop too, because you process their customers' data. And follow a data protection law such as the GDPR.
- Say that it's AI. Anthropic's Usage Policy (in force from 12 November 2026) requires chatbots that talk to external users to tell them they're talking to AI. The notice must be there at least at the start of each chat session, or in the interface. OpenAI requires telling people that a TTS (text-to-speech) voice is AI-generated. An example label for the chat widget on the shop's site: "Sunset Bookshop's AI assistant · answers can be wrong, the exact price is on the book's page".
The pre-launch checklist
Each line names one earlier lesson, and what must already be in place before the assistant is sold:
- The AI Landscape for Web Developers: a task that plain code can do doesn't call a model; the API key lives only on the server.
- Machine Learning 101: everyone on the team knows the model guesses tokens, so its answers can differ and can be wrong.
- Prompt Engineering Fundamentals: rules in
instructions, customer text in an escaped<question>. - OpenAI API & SDK: timeouts, retries,
max_output_tokens,401and429handled. - Streaming Responses: the server forwards the stream, cancels it when the browser leaves, and records
usage. - Embedding & Vector Search: books embedded once, questions embedded with the same model.
- RAG: a source threshold, "I don't know" when there's no source, stock from SQL.
- Function Calling & Tool Use: arguments validated, rounds capped.
- Building a Chat UI: Stop, Try again,
aria-live, model text never rendered as raw HTML. - LangChain / Vercel AI SDK: a framework doesn't replace validation, permissions and the key on the server.
- Semantic Search Implementation: hybrid BM25 + vectors with RRF, measured with precision and recall.
- Image Generation API: images stored once in your storage and checked before they go live.
- AI-Powered Forms & Content: AI suggests, a person saves, the server validates.
- Fine-tuning vs Prompting: instructions, examples and RAG first; fine-tuning only when evals still fail.
- Vector Databases: the
shop_idfilter doesn't cut results below theLIMIT. - AI Agent Patterns:
MAX_STEPS, and write tools wait for confirmation. - Evaluating AI Output: the eval set runs in CI, cross-shop cases included.
- Cost Optimization & Caching: routing, prompt caching, an answer cache keyed with
shop_idand the stock version. - Self-hosted Models (Ollama): the maths of when self-hosting is cheaper, and an option for shops whose data must not leave.
- AI Safety & Content Filtering: per-user limits, moderation, personal data removed,
safety_identifier. - Multi-modal AI in Web Apps: photos shrunk, EXIF stripped, upload size capped.
⚠️ Data leaking between shops, and margins that vanish
shop_idtaken from the request body. Anyone can send another shop'sshop_id. Take it from the verified API key.- An answer cache without
shop_id. One shop's stock answer is handed to another shop's customers. - A flat price for costs 56 times apart. The shop that uses the expensive model most uses up the margin. Count credits from the real cost.
- Tenant API keys stored as they are, or the provider key shared with shops. Store only the hash. The provider key never leaves the server.
- A free plan per account and without limits. Quotas per shop, a stop at the limit, and verified sign-ups.
TL;DR: An AI SaaS sells the assistant as a subscription service to many tenants (the shops that pay). All shops share one database, so keep their data apart with a shop_id from the verified API key, in SQL, vector search and the cache key. Without it, a Sunset Bookshop customer can get Rainbow Bookshop's stock. A per-shop API key is random (tb_live_ + 24 bytes), shown once, then stored as a SHA-256 hash. The provider key stays one key on the server. Stream through your backend, and record usage (the token counts) from the response.completed event for each shop. Cost per question: stock $0.000041, recommendation $0.00231 (56 times). The biggest business challenge is managing AI cost per user while keeping the margin (the part of the revenue left after the AI cost). A flat price (one fixed price) leaves Sunset, which asks for many recommendations, at only a 24.9% margin. Usage-based pricing (the price follows use) with tiers (plan levels) and credits (units of use) keeps the margin above 74%. Stock is 1 credit, a recommendation 50, $9 buys 50,000 credits, and extra credits cost $0.18 per 1,000. Cap the free tier (the Free plan) per shop. Watch cost and evals per shop. Use store: false so OpenAI doesn't store responses, and read the provider's DPA (data processing agreement). Follow data protection law such as the GDPR, and tell users they're talking to AI.
⚡ Each shop's data stays apart
Write:
"SELECT title, price, stock FROM books WHERE shop_id = $1 AND title ILIKE $2"
Guess first: all shops share one books table, and each row has a shop_id. Sunset Bookshop doesn't sell The Rainbow Troops, while Rainbow Bookshop has 12. The catalogue query forgot shop_id. What does a Sunset customer get?
"Yes! The Rainbow Troops, 12 in stock, $18". That's Rainbow Bookshop's stock, so the answer is wrong and another shop's data leaks.
Meaning: $1 is filled with the shop_id, and $2 with the title searched for (ILIKE ignores upper and lower case). The shop_id comes from the verified API key, not from the request body, and it's used in SQL, vector search and the cache key.
⚡ API keys stored as a hash
Meaning: Each shop calls your API with its own random API key. The key is shown once to the shop owner, then the database only stores its SHA-256 hash (a one-way calculation). If the database leaks, a hash can't be used to call your API.
⚡ AI cost follows use
Meaning: The AI cost grows with use, and one recommendation costs 56 times as much as one stock question. AI SaaS is an AI product sold as a subscription. Its biggest business challenge is managing AI cost per user while keeping the margin (the part of the revenue left after the AI cost). Sunset Bookshop asks for many recommendations. At a flat price (one fixed price) of $9 a month, Sunset's margin is only 24.9%. With credits (units of use: stock 1, recommendation 50, $9 for 50,000 credits, $0.18 per 1,000 beyond that), Sunset's bill is $26.37, a 74.4% margin.