Building an AI SaaS Product — AI Web

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…

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)}`;

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
}

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:

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).

Observability: a cost dashboard per shop and eval regressions

Observability means you can see what happens in your app from the data you record:

Law and trust: the basics you must have

The pre-launch checklist

Each line names one earlier lesson, and what must already be in place before the assistant is sold:

⚠️ Data leaking between shops, and margins that vanish

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.

What you will learn