One night I finished the checkout page, opened the webhook log, and stared at it. Stripe's dashboard said "succeeded." My own database said the user had no access. The cause: one metadata key was spelled planType on one side and plan_type on the other.
The agent itself had been working for weeks by then. It still wasn't something I could sell. Between "it runs" and "it sells" sits a stack of unglamorous layers: pricing, payment, access grants, usage caps, and a way to stop.
The companion piece, Five Paths to Sell AI Agents on AgentKit 2.0, covered how to choose a channel. This one picks up from there: how to finish the product and receive the first payment in 90 days, with gates built in.
Decide when you'll stop before you decide what to build next. That one sentence is the whole plan.
Cut the 90 days into gates, not tasks
Roadmaps usually come as a dated task list. But finishing a task doesn't mean you're allowed to move on. Instead of dates, I put decision points where I either proceed, fix, or stop.
The thresholds below are my own starting draft. Change the numbers to fit your product.
| Gate | Rough timing | To pass | If not |
|---|---|---|---|
| G1 Definition | Day 15 | The five questions fit on one page; you've talked to at least one real target user | Don't start building; rewrite the definition |
| G2 Unit cost | Day 30 | You've measured the cost of one run; a usage cap is live | Rethink model choice or split the work |
| G3 Payments | Day 60 | Test payment to access grant works with signature verification; duplicate deliveries don't double-grant | Don't launch; fix the webhook |
| G4 First sale | Day 75 | At least one payment from someone who isn't a friend | Revisit the page or the price |
| G5 Exit review | Day 90 | You can state where you stand against break-even in numbers | Pivot or stop |
Gates put a brake on the thought "a few more features and it'll sell." That thought tends to arrive late at night, when it's easiest to give in to.
Phase 1 (Day 1–15): define the product before writing code
Spend the first two weeks on definition alone. Starting from the technology means hunting for a reason to buy after the fact, and that usually stalls.
Five questions on one page
- Whose problem, exactly. For example: "an online-shop owner cuts the monthly time spent translating product pages." Get that specific.
- Why not what already exists. Explain in one sentence why a general chat assistant or an existing tool isn't enough.
- What the agent does. Write out input, processing, and output.
- What happens on failure. Unexpected input, mid-run stops, external API errors, one by one.
- Where the price comes from. Work backward from time saved, what that time is worth to the buyer, your cost, and fees.
If you can't fill the page, the product simply isn't formed yet. I treat that as a signal to keep asking questions, not as a verdict.
Start with a single agent
Multi-agent setups are appealing, but debugging, explaining the product, and estimating cost all get heavier with every agent you add. Ship one role first. You can split it once you see what sells.
Phase 2 (Day 16–30): make it hard to break and cheap to stop
The theme here isn't "make it run." It's make it hard to break, and easy to stop.
An SDK-agnostic run wrapper
Keep the agent call behind a function so you can swap the SDK or model later. This thin wrapper handles only timeouts and retries.
// lib/run-with-guards.ts — the actual call (SDK or API) is injected as `call`
type AgentCall = (
input: string,
signal: AbortSignal,
) => Promise<{ text: string; tokensIn: number; tokensOut: number }>;
function isRetryable(e: unknown): boolean {
if (e instanceof DOMException && e.name === 'AbortError') return true;
const status = (e as { status?: number })?.status;
return status === 429 || (status !== undefined && status >= 500);
}
export async function runWithGuards(
call: AgentCall,
input: string,
opts: { timeoutMs?: number; maxAttempts?: number } = {},
) {
const timeoutMs = opts.timeoutMs ?? 60_000;
const maxAttempts = opts.maxAttempts ?? 3;
let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
try {
return await call(input, ctrl.signal);
} catch (e) {
lastError = e;
if (!isRetryable(e) || attempt === maxAttempts) break;
// exponential backoff + jitter so retries don't pile up
const wait = 2 ** attempt * 500 + Math.random() * 250;
await new Promise((r) => setTimeout(r, wait));
} finally {
clearTimeout(timer);
}
}
throw lastError;
}Retry count and wait time translate directly into cost and perceived speed. I go deeper on that in the retry budget design note.
Count daily usage in D1
If you offer a free tier or a monthly plan, count usage on the server. Cloudflare KV is eventually consistent, so rapid requests can slip past a limit. Use D1 and update atomically in SQL.
CREATE TABLE IF NOT EXISTS usage (
user_id TEXT NOT NULL,
day TEXT NOT NULL,
runs INTEGER NOT NULL,
PRIMARY KEY (user_id, day)
);// Returns true and increments if under the limit; false if the limit is reached
export async function consumeQuota(
db: D1Database,
userId: string,
dailyLimit: number,
): Promise<boolean> {
const day = new Date().toISOString().slice(0, 10);
const row = await db
.prepare(
`INSERT INTO usage (user_id, day, runs) VALUES (?1, ?2, 1)
ON CONFLICT(user_id, day) DO UPDATE SET runs = runs + 1
WHERE runs < ?3
RETURNING runs`,
)
.bind(userId, day, dailyLimit)
.first<{ runs: number }>();
return row !== null;
}When the WHERE on DO UPDATE is false, no update happens and RETURNING yields no row. I use that missing row as the "limit reached" signal.
Counting before the run has one hole I overlooked, though: when the agent fails, that run is still consumed. From the user's side it reads as "it failed and I lost a use," which is exactly the kind of thing that turns into a support email. Once a failure is confirmed, give the run back.
// call only when the run ended in failure; MAX keeps the count from going below 0
export async function refundQuota(db: D1Database, userId: string) {
const day = new Date().toISOString().slice(0, 10);
await db
.prepare('UPDATE usage SET runs = MAX(runs - 1, 0) WHERE user_id = ?1 AND day = ?2')
.bind(userId, day)
.run();
}A run that straddles the UTC date change refunds into the wrong day. If that matters to you, keep the day you counted under and pass it in.
Measure cost per run
Model names and prices change often, so I don't pin numbers here. Log input and output tokens on every run, then compute per-run cost from the current price sheet of the model you actually use. That number feeds the break-even formula later.
Routing simple inputs to a cheaper model and only complex ones to a stronger model works. Input length alone is a weak rule, though, so keep the model IDs in environment variables and tune against quality.
const MODEL_LIGHT = process.env.MODEL_LIGHT!; // cheap, fast model ID
const MODEL_HEAVY = process.env.MODEL_HEAVY!; // quality-first model ID
export function pickModel(input: string, needsReasoning: boolean) {
if (needsReasoning || input.length > 5000) return MODEL_HEAVY;
return MODEL_LIGHT;
}For running agents in parallel under a shared limit, see the parallel quota budget design.
Phase 3 (Day 31–45): narrow the entrance
Out of the five channels, pick one or two first. My suggestion is direct sales on your own site as the spine, with a marketplace as one extra door. The reason is plain: your own site is the only place where you decide the price, own the customer relationship, and handle refunds yourself.
Marketplaces differ widely in fees, review, pricing freedom, and customer data. Check the current terms and fee tables yourself before listing. This article doesn't assume the terms of any specific marketplace.
A product page needs at least these five things:
- A hero line stating whose problem it solves
- A 30-second demo of the agent actually running
- Three steps: input, run, result
- A price table where the plan differences are obvious
- One or two FAQ entries, limited to where you yourself got stuck
If you price differently across your site and a marketplace, make sure one doesn't cannibalize the other: lower price at the entrance, ongoing features on your own monthly plan.
Phase 4 (Day 46–60): Stripe payments and access grants
This is the layer that tripped me up. Create a Checkout session, receive completion via webhook, and grant access.
Match plans to how the agent is used
Agents often feel like "run once, get a result," so a one-time purchase alongside a monthly plan can be easier to choose. Work backward from your cost and fees, then try something like this:
| Plan | Who it's for | How to set the price |
|---|---|---|
| One-shot | Someone testing, or a single task | A few times your unit cost; still profitable after fees |
| Monthly | Regular individual users | Derived from the worst-month cost at your daily cap |
| Lifetime | People who avoid subscriptions | Set only after stating the usage cap and update policy |
Creating the Checkout session
// app/api/checkout/route.ts
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const PLANS = {
oneshot: { mode: 'payment', amount: 480, name: 'One-shot' },
monthly: { mode: 'subscription', amount: 980, name: 'Monthly Pro' },
lifetime: { mode: 'payment', amount: 4800, name: 'Lifetime' },
} as const;
export async function createCheckout(
plan: keyof typeof PLANS,
userId: string,
agentId: string,
origin: string,
) {
const p = PLANS[plan];
return stripe.checkout.sessions.create({
mode: p.mode,
line_items: [
{
quantity: 1,
price_data: {
currency: 'jpy', // JPY has no minor unit: 480 means 480 yen
unit_amount: p.amount,
product_data: { name: p.name },
...(p.mode === 'subscription'
? { recurring: { interval: 'month' as const } }
: {}),
},
},
],
client_reference_id: userId,
metadata: { plan, agent_id: agentId }, // keep these keys identical to the webhook side
success_url: `${origin}/agent/${agentId}?checkout=success`,
cancel_url: `${origin}/agent/${agentId}`,
});
}The user ID goes in client_reference_id; plan and product go in metadata. Make the key names constants that both sides import, and the mismatch from my opening story can't happen.
A webhook that verifies signatures and survives duplicates
If you accept webhooks without verifying signatures, anyone can fake a "payment completed." Stripe can also deliver the same event more than once, so grants must be idempotent.
// app/api/stripe/webhook/route.ts
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: Request) {
const body = await req.text(); // signature verification needs the raw body
const sig = req.headers.get('stripe-signature');
if (!sig) return new Response('missing signature', { status: 400 });
let event: Stripe.Event;
try {
// On Workers / edge runtimes, use constructEventAsync
event = await stripe.webhooks.constructEventAsync(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch {
return new Response('invalid signature', { status: 400 });
}
if (event.type === 'checkout.session.completed') {
const s = event.data.object as Stripe.Checkout.Session;
const userId = s.client_reference_id;
const plan = s.metadata?.plan;
const agentId = s.metadata?.agent_id;
if (!userId || !plan || !agentId) {
console.error('webhook metadata missing', event.id);
return new Response('missing metadata', { status: 400 }); // let it redeliver so you notice
}
if (s.payment_status !== 'paid') {
return new Response('not paid yet', { status: 200 }); // async methods are granted on a later event
}
// INSERT event.id into a processed-events table; do nothing on duplicate
await grantOnce(db, { eventId: event.id, userId, agentId, plan }); // db is your D1 binding
}
return new Response('ok', { status: 200 });
}grantOnce puts the processed-event record and the access grant into one batch, so one can never succeed without the other. D1's batch() runs as a single transaction: if something dies midway, you don't end up with "recorded as processed, but no access."
CREATE TABLE IF NOT EXISTS processed_events (
event_id TEXT PRIMARY KEY,
processed_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS entitlements (
user_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
plan TEXT NOT NULL,
granted_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (user_id, agent_id)
);export async function grantOnce(
db: D1Database, // pass the D1 binding in from the caller
p: { eventId: string; userId: string; agentId: string; plan: string },
) {
await db.batch([
db.prepare('INSERT OR IGNORE INTO processed_events (event_id) VALUES (?1)').bind(p.eventId),
// grant access only if the INSERT above actually added a row (changes() is 0 on a duplicate)
db
.prepare(
`INSERT INTO entitlements (user_id, agent_id, plan)
SELECT ?1, ?2, ?3 WHERE changes() > 0
ON CONFLICT(user_id, agent_id) DO UPDATE SET plan = excluded.plan`,
)
.bind(p.userId, p.agentId, p.plan),
]);
}changes() is the SQLite function that returns how many rows the previous statement modified. When the same event.id arrives twice, it is 1 the first time and 0 the second, so the second grant does nothing. I ran the same SQL twice against a local SQLite and confirmed the access row didn't multiply. D1 is SQLite-based, but I'd still run the same check in your own environment once.
When billed totals drift, the metering ledger and Stripe drift notes cover how I trace it. For the wider payment architecture, see the SaaS Stripe full-stack guide.
Reproduce a duplicate delivery yourself before launch
At first I treated webhook redelivery as something that rarely happens. In practice, Stripe resends an event whenever your endpoint returns anything other than a 2xx. Returning a 500 for a few seconds during a deploy is enough.
So reproduce it by hand before G3. The Stripe CLI can forward signed events locally and resend them.
# 1) Forward events to your local server (set the printed whsec_ as STRIPE_WEBHOOK_SECRET)
stripe listen --forward-to localhost:3000/api/stripe/webhook
# 2) In a second terminal, fire a test event
stripe trigger checkout.session.completed
# 3) Resend the same event using the evt_ ID from the output
stripe events resend evt_XXXXXXXXThe test session that stripe trigger creates carries no metadata, so the handler above returns a 400 missing metadata. That is the expected behavior, and it confirms the failure path works. For the success path, pay in test mode through your own product page, then check two things:
- There is exactly one
processed_eventsrow for that event. - However many times you resend the
evt_, theentitlementstable doesn't gain rows.
Only when both hold can you honestly say G3's "duplicate deliveries don't double-grant."
Phase 5 (Day 61–75): pre-launch checks
Clear these one at a time before going public:
- The product page opens with the user's problem
- The demo runs about 30 seconds and shows the value
- A small live-mode payment went through, with the refund confirmed
- A cancel path exists, and what happens to access afterward is explained
- Emails arrive for payment, cancellation, and errors
- Run logs are stored and users can view their history
- Contact information is stated
- Legal pages required in your jurisdiction (commercial-transactions notice, privacy policy, terms) are published
Announce from where you already post: a social post, a technical write-up, a note to existing followers. Ordering the post as "what I got stuck on, what's different about doing this solo, why I chose this price" makes it easier for readers to map onto their own situation. Day-one reaction is mostly luck, so don't judge by it. Judge by the G4 criterion.
Phase 6 (Day 76–90): operate, and keep the exit line
Three numbers to watch daily
- New users, logged separately for your site and outside channels
- Conversion: the share of visitors who pay
- Error rate: the share of runs that didn't finish as intended
Decide each alarm line before launch and write it down. If the line can move afterward, a bad day will talk you into a convenient reading.
Hold break-even as a formula
Turn the exit line from a feeling into arithmetic. Two figures give you break-even headcount: monthly gross margin per user and monthly fixed cost.
Gross margin per user per month = monthly price × (1 − payment fee rate) − average monthly runs × cost per run
Break-even users = monthly fixed cost ÷ gross margin (rounded up)
The sample below states its assumptions: a ¥980 monthly plan, a 4% payment fee, ¥4 per run, and ¥3,000 a month in fixed cost (hosting, domain, monitoring). These are placeholders for illustration; use the figures from your own invoices.
| Usage profile | Runs per month | Gross margin per user | Break-even users |
|---|---|---|---|
| Light | 20 | about ¥861 | 4 |
| Typical | 40 | about ¥781 | 4 |
| Heavy | 150 | about ¥341 | 9 |
Heavy users more than double the headcount you need. That is why I put a daily cap on the monthly plan: it fixes the worst month in advance, so even at the thinnest margin you can calculate the size of the loss before it happens.
My exit conditions
I stop when any one of these holds for three months:
- Monthly net profit stays below fixed cost
- Operations keep squeezing the time I need for my day job or creative work
- Progress against break-even headcount is still under half after three months
Writing the numbers down is how I avoid being dragged along by sunk cost. Stopping isn't failure; it hands that time to the next product.
Three things to revisit after launch
- Keep it explainable. Name, description, and price should land in three seconds. Use multi-agent structure inside, but show users one role.
- Keep a place to talk with users. Email or a small community will do. When a general-purpose agent eventually competes with yours, what holds up is less the feature gap than the record of problems you've listened to.
- Review model choices on a schedule. New models can change cost and quality. Let your invoices tell you how often to look.
Ninety days is one example of the shortest route. If you have a day job, doubling the span is perfectly fine.
Tonight, write the five questions on one page. Then read that page once against the G1 criterion, and see where it still feels thin.