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.

Two lanes. Charge, before the run starts: charge with workspace, cost and reference takes from the plan bucket first and lets top-ups cover the shortfall; a conditional update matches only if both buckets hold what is being taken; on a match a ledger row is written with kind charge, amount, reference and balance after; if the update misses eight times the result is HTTP 402 with nothing deducted. A note says the balance is stored on credit_accounts, one row per workspace, and credit_transactions is append-only. Refund by reference: refund returns credit to the bucket it was taken from; a marker check requires that the marker refund colon reference is not yet in applied_credits, then increments the balance and pushes the marker; the first time a refund row is written, unique on reference, workspace and kind refund; a second attempt finds the marker present and adds no credit. A note says a crash between the balance update and the ledger insert is safe to retry.
Figure 1. Charging and refunding. A charge succeeds only if one conditional update finds both buckets large enough. A refund is applied to the balance once per reference and recorded once.

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

Table of payment order ids. sub underscore ids are built from workspace, plan and month by the server on subscribe and protect one subscription charge per workspace, plan and month. ren underscore ids are built from workspace and period end date by the server's renewal tick and protect one renewal per billing period; the id is predictable by design. top underscore ids are built from workspace, milliseconds and a random part by the server on top-up. Ids ending in underscore r and hex are a failed order id plus a suffix, created by the server on retry, and allow a new charge only after every earlier row is a settled failure. Anything else comes from the payment widget in the browser; a client id that starts with a server prefix is answered 400 before capture. A note explains that every payment row shares one unique index on order_id and a renewal id can be guessed.
Figure 2. Order-id namespaces. The server builds ids for subscriptions, renewals, top-ups and retries. A client-supplied id that starts with a server prefix is refused before any money is captured.

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.

KindExamplesWhat happens next
Definite declinea known decline code from the providercounts toward dunning; a retry may use a new order id
Uncertainany HTTP status of 500 or above, a network error, a timeoutnever 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 wrongWhat the system doesRegression test
Two charges race on one balanceOne conditional update loses and retries; the balance never goes negativetest_concurrent_charges_never_overdraw
Charges and top-ups interleaveCredit is conserved, on a real MongoDBtest_concurrent_charges_and_topups_conserve_credit
Not enough creditNothing is taken from either buckettest_insufficient_total_takes_nothing
A refund is retriedBalance changes oncetest_refund_is_idempotent
Crash after the balance update, before the ledger rowRetry adds no credit and writes the rowtest_refund_balance_idempotent_even_when_ledger_write_crashes
Concurrent refunds for one referenceOne ledger rowtest_concurrent_refunds_write_one_ledger_row
Client sends a server-prefixed order id400 before capturetest_server_order_namespace_is_rejected_before_capture
Widget row tries to shadow a renewalThe renewal still chargestest_widget_confirm_cannot_make_renewal_skip_charging
Provider answers 5xx with a decline codeTreated as uncertaintest_5xx_is_never_terminal_even_with_a_known_code
Uncertain failure, next tickNo second chargetest_uncertain_failure_is_not_recharged_on_the_next_tick
Confirm times out but the card was capturedCredits are granted after lookuptest_widget_confirm_timeout_but_captured_is_credited
A payment lands during downgrade reviewThe payment winstest_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.