Every paid action in TRAIL Search is metered in credits, and credits are bought with real card payments through Toss Payments. Two separate things can go wrong with money: the internal balance can drift from the work that was done, and the external charge can happen twice or not at all. Each has its own mechanism.
The problem
A workspace can start several runs at once, and each run charges before it executes. Two charges that both read a balance of 100, both subtract 60 and both write the result would leave 40 and deliver 120 credits of work. Refunds have the mirror problem: a refund that is retried after a timeout must not pay twice, and the retry is not optional because the first attempt may have succeeded or failed.
On the payment side the risk is asymmetric. Charging a card twice is the worst outcome. Failing to charge is recoverable. So wherever the result of a charge is unknown, the system asks the payment provider what happened before it does anything else.
A stored balance and a ledger
There are two collections. credit_accounts holds one row per workspace with the current balance. credit_transactions is append-only and holds one row per change: the signed amount, a kind, a reason, a reference and the balance after the change.
The balance is stored, not derived by summing the ledger. I chose a stored balance because a charge has to answer “is there enough?” and act on the answer in one step, and a conditional update on one row does that. The ledger explains the balance and lets every change be traced to the run or payment that caused it.
The account has two buckets. Plan credits arrive with the subscription each month. Top-up credits are bought separately. A charge spends plan credits first and takes only the shortfall from top-ups.

The charge computes how much to take from each bucket, then issues one update whose filter requires both amounts to be available.
flt: dict = {"workspace_id": workspace_id}
if take_p:
flt["balance"] = {"$gte": take_p}
if take_t:
flt["topup_balance"] = {"$gte": take_t}
doc = await coll.find_one_and_update(
flt,
{"$inc": {"balance": -take_p, "topup_balance": -take_t},
"$set": {"updated_at": utc_now()}},
return_document=ReturnDocument.AFTER,
)
If another charge changed the buckets in between, the filter misses. The function re-reads the account, recomputes the split and tries again, up to 8 times. If the total is too small or the retries run out, it returns False with nothing deducted, and the route answers 402.
Refunds that apply at most once
A refund is identified by the reference of the charge it reverses. For a run, that reference is the run batch id. Deduplication happens in two places because the refund is two writes.
On the balance. The account row keeps a list of applied markers. The refund is one update that requires the marker to be absent, adds the credit and pushes the marker.
marker = f"refund:{ref}"
doc = await _coll().find_one_and_update(
{"workspace_id": workspace_id, "applied_credits": {"$ne": marker}},
{"$inc": {"balance": plan, "topup_balance": topup}, "$set": {"updated_at": now},
"$push": {"applied_credits": marker}},
)
On the ledger. A partial unique index covers (ref, workspace_id, kind) for rows whose kind is refund. A second insert raises a duplicate-key error, which the code treats as “already recorded”.
The two guards cover each other’s gap. If the process dies after the balance update and before the ledger insert, the retry finds the marker and adds nothing, then writes the missing row. If it dies before the balance update, the retry does both. Credit returns to the bucket it came from, which the charge row records in topup_part.
A full refund uses this path directly. A partial refund, for a run where some cells failed, is a grant of kind refund that is checked against the ledger first, inside a settlement claim that only one caller can hold.
Order ids the client cannot forge

Every payment is a row in billing_payments with a unique index on order_id. The row is inserted before the charge, so a second attempt with the same id is refused by the database, and the same id is sent to Toss as the idempotency key.
A renewal id is built from the workspace and the period end date. That makes it deterministic, which is the point: the renewal job on any day computes the same id, so it cannot renew the same period twice. It also makes the id guessable. Top-ups go through a payment widget in the browser, where the client proposes the order id. A client that proposed next month’s renewal id for a small top-up would create a row with that id, and the renewal job would later read “already paid” and skip the charge.
The fix is a namespace check. reserve_widget_payment refuses any client id that starts with sub_, ren_ or top_, and the route answers 400 before capture. As a second defence, the reservation refuses an id that belongs to a row from another workspace or of another payment type.
When the charge result is unknown
The Toss adapter sorts failures into two kinds.
| Kind | Examples | What happens next |
|---|---|---|
| Definite decline | a known decline code from the provider | counts toward dunning; a retry may use a new order id |
| Uncertain | any HTTP status of 500 or above, a network error, a timeout | never re-charged under a new id; the next attempt first asks Toss for the order’s status |
A 5xx is never treated as a decline, even when it carries a code that looks like one. After an uncertain failure the next tick looks the order up. If Toss reports it approved, the payment is recorded as reconciled and no second charge is made. If Toss reports it unpaid, the row is marked as confirmed unpaid and only then may a retry row be created. Reservation rows left in created for more than 10 minutes are reconciled the same way. Errors that are the company’s fault, such as a misconfigured merchant setting, are logged as errors and do not count against the customer.
Renewals and dunning
Renewals run from the scheduler loop behind a once-a-day gate. Three definite declines, or no card on the due date, move a subscription to past_due. The owner is emailed at most once a day, and only an email that was actually sent counts as notice.
There is no automatic downgrade. After a grace period the subscription is queued for review, and a person approves the downgrade. The approval re-checks the payment state and refuses if any payment is approved or still unconfirmed, because a payment that lands during the review must win. A circuit breaker holds dunning when one failure code dominates a day’s batch, since that pattern points at the provider or at the merchant setup and not at the customers.
On renewal the balance is reset and unused credits do not carry over. The reset writes its own ledger rows, so the history shows what expired and what was granted.
Failure modes
| What goes wrong | What the system does | Regression test |
|---|---|---|
| Two charges race on one balance | One conditional update loses and retries; the balance never goes negative | test_concurrent_charges_never_overdraw |
| Charges and top-ups interleave | Credit is conserved, on a real MongoDB | test_concurrent_charges_and_topups_conserve_credit |
| Not enough credit | Nothing is taken from either bucket | test_insufficient_total_takes_nothing |
| A refund is retried | Balance changes once | test_refund_is_idempotent |
| Crash after the balance update, before the ledger row | Retry adds no credit and writes the row | test_refund_balance_idempotent_even_when_ledger_write_crashes |
| Concurrent refunds for one reference | One ledger row | test_concurrent_refunds_write_one_ledger_row |
| Client sends a server-prefixed order id | 400 before capture | test_server_order_namespace_is_rejected_before_capture |
| Widget row tries to shadow a renewal | The renewal still charges | test_widget_confirm_cannot_make_renewal_skip_charging |
| Provider answers 5xx with a decline code | Treated as uncertain | test_5xx_is_never_terminal_even_with_a_known_code |
| Uncertain failure, next tick | No second charge | test_uncertain_failure_is_not_recharged_on_the_next_tick |
| Confirm times out but the card was captured | Credits are granted after lookup | test_widget_confirm_timeout_but_captured_is_credited |
| A payment lands during downgrade review | The payment wins | test_payment_landing_mid_approval_wins |
What is not there
There is no webhook receiver. Every uncertain state is resolved by asking the provider, on the next tick or on the next request. That is slower than a webhook by up to a minute and it removes a public endpoint that would need its own signature checks and replay protection. If payment volume grows I would add the webhook as a faster path and keep the lookup as the source of truth.
