"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
| Action | Who could repeat it | The key | Enforced by |
|---|---|---|---|
| Measure a due schedule | two processes during a reload | schedule_claim | unique partial index on run_batches |
| Start a run for one click | a client retry, a double submit | request_key | unique partial index, scoped to the workspace |
| Settle a finished run | the run’s worker and the reaper | settlement.settling | conditional update |
| Refund one charge | any retry of settlement | refund:<ref> | marker on the account, unique index on the ledger |
| Run the daily renewal job | a restart, a second worker | job + day | conditional 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.

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_atis the slot. The next slot produces a different key, so the schedule can run again tomorrow.updated_atis 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.

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_settlementsetssettled_at, and the run never matches the filter again. - The refund raises,
release_settlingclears 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 wrong | What the system does | Regression test |
|---|---|---|
| Two processes tick on the same due slot | One run is inserted | test_same_slot_twice_makes_one_batch |
| A tick finds its slot already claimed | Reschedules, does not measure, leaves the last status alone | test_due_tick_with_claimed_slot_reschedules_without_measuring |
| The same request key arrives concurrently | One run is created | test_concurrent_same_key_creates_one_batch |
| A run is settled twice | One refund | test_queued_running_failed_refunds_once_even_if_settled_twice |
| A full refund fails midway | settled_at stays null, the retry pays once | test_full_refund_failure_leaves_settled_null_and_retries_paying_once |
| A partial refund fails midway | Same, for the proportional path | test_partial_refund_failure_leaves_settled_null_and_retries_paying_once |
| Ten workers claim the daily gate together | Exactly one wins, on a real MongoDB | test_daily_gate_claim_is_atomic_on_real_driver |
| The process restarts after claiming the day | The gate is still held | test_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.
