Fundai
The credit lifecycle of a paid AI question
A paid AI question in Fundai is a state machine with money at every step. A sweep for stuck questions and one refund make each end in an answer or a refund.
In short
Treat a paid AI question as a state machine where every path ends in an answer or a refund. Taking the question locks the wallet and spends the credit in one transaction, and the worker is queued only after commit. A sweep every minute fails questions that can no longer finish, conditional updates stop the worker and the sweep acting on the same question, and the refund checks the ledger so it pays back exactly once, for free questions as well as paid ones.
Fundai is a fundamental-analysis platform for the Tehran Stock Exchange, which I co-founded in 2023. Its AI assistant answers questions about listed companies using Fundai's own data, and everyone gets one free question a day, after which each question costs a credit.
I came across a question still marked "queued" long after its task had expired. No worker had picked it up in the two minutes it was allowed, so it was never going to run, yet the reader had paid a credit for it and their page was still checking for an answer that wasn't coming. A worker killed mid-answer by a deploy left the same mess behind, only stuck at "running" instead.
Going through the refund paths afterwards, I found a quieter version. When the assistant declines a question or finds no data, paying readers get their credit back, but someone who had used their one free question of the day didn't get it back.
So a paid AI question is a small state machine with money moving at every step, and every path through it has to end in either an answer or a refund.
Taking a question
The assistant plans, pulls the numbers, writes an answer and reviews it, which takes 70 to 150 seconds, so it runs on a background worker. Accepting the question happens in a single database transaction:
with transaction.atomic():
wallet = wallet_for(profile, lock=True) # one reader at a time
admit(profile) # paused? daily cap? one in progress?
paid_with = FREE if free_left else CREDIT # no credit left: refuse
question = Question.create(..., paid_with=paid_with)
if paid_with == CREDIT: spend(wallet, question) # ledger entry, -1
on_commit(lambda: answer_question.apply_async([question.pk], expires=120))
Locking the reader's wallet turns the checks and the payment into one decision, so two taps a moment apart can't both spend the last credit. Every balance change goes into the ledger as its own entry rather than overwriting a number, which means I can always trace what happened to a credit. And because the worker is queued only after the transaction commits, it can never start on a question, or a payment, that was rolled back.
Questions that never finish
The worker's own failures were already handled: a model error or a code error marks the question failed and refunds it, and so does an answer that isn't really an answer, where the assistant declined, found no data, or its own review said the question wasn't answered.
What nothing handled was a question no worker would ever finish. If no worker picked a task up within 120 seconds, Celery dropped it and the question stayed queued forever, and if a deploy killed a worker mid-answer, it stayed running forever. Either way the credit was spent, and the reader was left watching a page that would never change.
A sweep, and exactly one refund
Now a small task runs every minute and fails anything that can no longer finish. A question queued for more than 150 seconds never ran, because its task expired at 120. One running for more than 390 seconds has lost its worker, since that's the 120-second queue limit plus the 240-second hard limit on the task, plus a margin. The sweep marks both kinds failed and refunds them.
Two details keep the sweep from causing a bug of its own. The worker claims a question with a conditional update, so queued becomes running only if it's still queued, and the sweep fails a question the same way, only if its status hasn't changed since it looked, which means the two can never both act on the same question.
The refund also pays out only once. It locks the wallet, checks whether this question already has a refund entry, and only then gives the credit back, so the worker, a declined answer and the sweep can all call it any number of times and the reader still gets exactly one credit.
The same rule for free questions
The free-question gap had one cause: refunds only knew about credits. A declined free question still used up the reader's free question for the day, while the same answer on a credit was refunded.
A refund now marks the question as refunded, whether it was free or paid. The free allowance ignores refunded questions, so the reader gets today's question back, while the overall daily limit still counts it, because the model calls were made and paid for either way.
Testing it
The tests run the real worker and the real sweep:
- the sweep fails a question that expired in the queue and refunds it once, even when it runs twice;
- a question already claimed or failed is never answered;
- refunding a credit question twice gives back one credit;
- a declined free question returns the day's free question but still counts toward the daily limit.
That last test fails on the old code and passes now, along with the assistant's other tests.
Where it stands
Every paid question now ends in an answer or a refund. The reader never pays for a declined question or a crashed worker, never watches a question that will never finish, and gets exactly one refund however many paths try to give it, and free and paid questions finally follow the same rule.
Further reading
- Celery task expirationdocs.celeryq.dev
- Django select_for_updatedocs.djangoproject.com
- Idempotent requests in Stripe's APIdocs.stripe.com
- Double-entry bookkeeping, the idea behind a ledgeren.wikipedia.org
More writing
-
Don't let the model convert the calendar: Jalali dates in an MCP server for a gold inventory
Why a gold inventory's MCP server converts Jalali dates itself, rejects days that don't exist, and returns every date in both calendars to AI agents.

-
A cold start that draws last launch: persisting the TanStack Query cache in a mobile word game
How ClueShot restores last launch's TanStack Query cache as stale, checks whose it is, and revalidates with ETags so a cold start never opens empty.

-
Two failure handlers, one refund: idempotent cleanup in an async AI image pipeline
How a BullMQ image worker, its failed event and a Telegram bot all reach one refund in MrPicasso, and how two Redis claims keep it to one credit.
