"Exactly once" is not a property a system has in general. It is a short list of specific actions that must not repeat, each protected by a key that the database refuses to store twice. In TRAIL Search the list has five entries, and each one was added after working out who could do the action a second time.

What must happen once

ActionWho could repeat itThe keyEnforced by
Measure a due scheduletwo processes during a reloadschedule_claimunique partial index on run_batches
Start a run for one clicka client retry, a double submitrequest_keyunique partial index, scoped to the workspace
Settle a finished runthe run’s worker and the reapersettlement.settlingconditional update
Refund one chargeany retry of settlementrefund:<ref>marker on the account, unique index on the ledger
Run the daily renewal joba restart, a second workerjob + dayconditional upsert against a unique key

Scheduled runs during a reload

Tracking schedules are checked by a loop that ticks every 60 seconds inside the API process. On each tick it selects schedules that are enabled and whose next_run_at has passed. During a deploy the old process and the new process are both alive for a short time, both tick, and both read the same due row.

Sequence diagram with three lifelines: process A, the old one still draining; the run_batches collection with a unique partial index on schedule_claim; and process B, newly started. Both scheduler loops tick with the same due row. Step 1, process A inserts a RunBatch with a schedule_claim. Step 2, process B inserts a RunBatch with the same schedule_claim. Step 3, the database answers process A that the row was inserted. Step 4, the database answers process B with DuplicateKeyError. Step 5, process A executes the batch and measures once. Step 6, process B only reschedules and does not measure.
Figure 1. Two processes read the same due schedule during a reload. Both try to insert a run with the same claim key. The index accepts one insert, and the loser only reschedules.

Both processes compute the claim key from the row they read.

def schedule_claim_key(schedule: Any) -> str:
    def ms(dt: datetime | None) -> int:
        a = as_utc(dt)
        return int(a.timestamp() * 1000) if a is not None else 0

    return f"sched:{schedule.id}:{ms(schedule.next_run_at)}:{ms(schedule.updated_at)}"

The key has three parts and each one is there for a reason.

  • The schedule id separates one brand’s schedule from another’s.
  • next_run_at is the slot. The next slot produces a different key, so the schedule can run again tomorrow.
  • updated_at is the settings version. If the customer edits the schedule, the same slot under new settings is a different run.

Times are reduced to epoch milliseconds because MongoDB stores dates at millisecond precision. Without that, a row read twice could format two different strings for the same instant.

create_batch inserts the run with this key and catches DuplicateKeyError, returning None.

batch = await create_batch(
    workspace_id=brand.workspace_id, brand_id=str(brand.id), draft=draft,
    kind="scheduled", schedule_claim=schedule_claim_key(s),
)
if batch is None:
    return "duplicate"

The process that lost does one more careful thing. It advances next_run_at so the row stops being due, but it does not overwrite last_status or last_run_at. Those belong to the process that is measuring, and a loser that wrote them would record a run that it never made.

The index is partial. It applies only to documents where idempotency.schedule_claim is a string, so the many manual runs that have no claim do not collide with each other on a missing value.

One run per click

Manual runs use the same idea with a different key. The web client can send a request key. A sibling index on (workspace_id, idempotency.request_key) makes a second insert with the same key fail, and the handler then looks the first run up and returns it. The handler also stores a hash of the request, so a retry with the same key and a different body is answered with a conflict instead of silently returning a run that does not match what was asked.

Settling a run once

A finished run owes the customer either nothing or a refund. Two parties can reach that conclusion at the same time: the worker closing its own run and the reaper closing a run it believes is dead. The amount moves through the credit ledger, so settling twice would pay twice.

Flow diagram. settle_run is called by the worker and by the reaper. It calls claim_settling, which matches only if settled_at is null and there is no live claim. If the filter misses, the claim is lost because another caller is settling. If the claim is won, _refund_once runs: a full refund is idempotent by reference and a partial refund is guarded by a check. When the refund is done, finalize_settlement sets settled_at. If the refund raises, release_settling clears the claim and leaves settled_at null, and the re-settle sweep, which runs every 60 seconds over interrupted or failed runs that are unsettled with credits reserved, picks the run up again. A note says a claim older than 300 seconds counts as abandoned.
Figure 2. Settlement. A caller must win a claim before it may refund. The settled mark is written only after the refund succeeded, so a failed refund leaves the run open for the next attempt.

claim_settling is the gate. Its docstring, translated, says the settled mark is not written here and is written only after the refund succeeds.

res = await _coll().update_one(
    {"_id": batch_id, "settlement.settled_at": None,
     "$or": [{"settlement.settling": None},
             {"settlement.settling.at": {"$lt": cutoff}}]},
    {"$set": {"settlement.settling": {"owner": owner, "at": now}}},
)
return bool(res.modified_count)

The first version of this code wrote settled_at as the claim. A review pointed out the hole: a process that claimed and then crashed before refunding would leave a run marked settled with the refund never paid. Splitting the claim from the completion fixed it. The claim is a lease of its own, with a 300-second grace, and three outcomes are possible after it.

  • The refund succeeds, finalize_settlement sets settled_at, and the run never matches the filter again.
  • The refund raises, release_settling clears the claim immediately, and the next caller may try.
  • The process dies holding the claim, the claim ages past the grace, and the re-settle sweep picks the run up.

The sweep runs with the reaper every 60 seconds. It looks for runs that are interrupted or failed, have no settled_at and have credits reserved. execute_batch settles before it calls finish, so a run is never visible as finished while its refund is still pending.

Refunding a reused result

Brand audits include a visibility score that needs answers from the engines. If the workspace already tracked the same prompts recently, asking again would buy the same information twice. The audit therefore looks for stored answers no older than 14 days that match its prompts and engines, and reuses them if they cover enough distinct prompts. Reused batches are weighted by age with a seven-day half-life, so a result from yesterday counts for more than one from two weeks ago.

The audit is charged up front under two references, one for the audit and one for the visibility part. When the reuse path is taken no new calls are made, and the second reference is refunded. That refund goes through the same idempotent path as every other refund, so an audit that is retried or reaped after reusing results still leaves one refund row.

Once a day

Subscription renewals run from the same scheduler loop but must happen at most once per day, across restarts. A restart in the middle of the day must not charge a failing card a second time or count two failed attempts.

res = await coll.update_one(
    {"job": job, "day": {"$ne": day}},
    {"$set": {"day": day, "claimed_at": utc_now()}},
    upsert=True,
)

job has a unique index. If the row for this job already holds today’s date, the filter does not match, the upsert tries to insert a second row for the same job, and the unique index refuses it. The duplicate-key error is the answer “already claimed today”. If the day’s batch raises, the gate is released so the next tick can try again.

Failure modes

What goes wrongWhat the system doesRegression test
Two processes tick on the same due slotOne run is insertedtest_same_slot_twice_makes_one_batch
A tick finds its slot already claimedReschedules, does not measure, leaves the last status alonetest_due_tick_with_claimed_slot_reschedules_without_measuring
The same request key arrives concurrentlyOne run is createdtest_concurrent_same_key_creates_one_batch
A run is settled twiceOne refundtest_queued_running_failed_refunds_once_even_if_settled_twice
A full refund fails midwaysettled_at stays null, the retry pays oncetest_full_refund_failure_leaves_settled_null_and_retries_paying_once
A partial refund fails midwaySame, for the proportional pathtest_partial_refund_failure_leaves_settled_null_and_retries_paying_once
Ten workers claim the daily gate togetherExactly one wins, on a real MongoDBtest_daily_gate_claim_is_atomic_on_real_driver
The process restarts after claiming the dayThe gate is still heldtest_gate_survives_a_process_restart

What I would watch

Every mechanism on this page depends on an index existing in production with the right partial filter. The in-memory database used by most tests ignores partial filters, so the test suite patches it to behave like the real one, and a small set of tests runs against a real MongoDB to confirm the index is present and does what the code assumes. An index that was dropped by hand would turn each of these keys back into a suggestion.