TRAIL Search keeps all of its state in MongoDB, modelled with Beanie documents. The schema is shaped by one question asked of every collection: what must never be true of this data, and what in the database stops it? Application code that promises to check first is not an answer, because two processes can both check and both proceed.

Collections

Diagram of MongoDB collections in three zones. Tenancy: workspaces with workspace_id unique, users with email unique, workspace_members unique on workspace and email, api_keys storing only a hash with scope and expires_at. Measurement: brands with a revision for optimistic locking, tracked_prompts with one live prompt per key, tracking_schedules with one schedule per brand, run_batches with a unique request key and a unique schedule claim, engine_runs with one row per attempt and raw answers that expire after 90 days, mentions with entity, rank and cited, sov_snapshots written only by the lease owner, and serp_result_cache that expires after 2 days. Billing: credit_accounts with one balance row per workspace, credit_transactions with one refund row per reference, billing_payments with order_id unique, billing_subscriptions with one per workspace, billing_daily_runs with a unique job so it runs once a day. An arrow from run_batches to credit_transactions is labelled charge and refund reference equals batch id. A note says every document carries workspace_id, taken from the session or the API key, never from the request body.
Figure 1. The main collections in three groups. Under each name is the rule that protects it. Arrows follow one run from a brand's prompts to its stored answers and its charge.
AreaCollectionWhat it holds
Tenancyworkspaces, users, workspace_membersthe tenant, its people and their roles
Tenancyapi_keysa key’s hash, scope, expiry and revocation time
Measurementbrandsa brand, its markets and observed engines, with a revision counter
Measurementtracked_prompts, prompt_setsthe questions asked for a brand; the second mirrors the first for older readers
Measurementtracking_schedulescadence, repeats, the next due time
Measurementrun_batchesone run: status, plan, idempotency keys, lease, counts, settlement
Measurementengine_runsone attempt for one cell: answer text, citations, observation axes
Measurementmentionsan entity named in an answer, with rank and whether it was cited
Measurementsov_snapshotsper-entity rates for one run, with sample and integrity fields
Billingcredit_accounts, credit_transactionsthe stored balance and the append-only ledger
Billingbilling_payments, billing_payment_methods, billing_subscriptionscard payments, the saved card reference, the plan state
Billingbilling_daily_runs, billing_free_usesonce-a-day job gates and free allowances
Auditssite_audits, audit_reportsa crawl-and-score job and its result

Every document carries a workspace_id. Routes take it from the session or from the API key and never from the request body, so a caller cannot name someone else’s workspace in a payload.

Tenancy and roles

A workspace id is derived from its owner’s user id, so the owner needs no membership row. Other people join through workspace_members with the role editor or viewer. The active workspace comes from a request header, and a header that names a workspace where the caller has no active seat falls back to the caller’s own workspace instead of failing, so a stale browser tab cannot lock a person out or let them into someone else’s data.

Routes declare the access they need through one of three dependencies.

DependencyRoles allowedUsed for
get_workspace_idowner, editor, viewerreads
require_write_workspace_idowner, editoranything that changes data or spends credits
require_owner_workspace_idownercard, subscribe, cancel, resume and top-up

Billing is owner-only at the route, not in the interface. An editor who calls a billing route directly gets a 403 that says the action needs the owner. One test lists every route with the gate it is expected to carry, and a second fails when a route that is not a GET is added without a gate or a written excuse, so a new endpoint cannot ship ungated by accident.

Indexes that enforce a rule

An index in this schema is rarely about speed. Most of them exist so that the database refuses a write the application must never make.

IndexTypeThe rule it enforces
batch_request_key_unique on (workspace_id, idempotency.request_key)unique, partial: only where the key is a stringone run per client request
batch_schedule_claim_unique on idempotency.schedule_claimunique, partial: only where the claim is a stringone run per schedule, slot and settings version
batch_lease_expiry on (status, lease.expires_at)compoundlets the reaper find expired runs without scanning
tracked_prompt_live_key on (workspace_id, brand_id, norm_key)unique, partial: only where archived_at is nullno duplicate live prompt, while an archived one can be added again
brand_unique on tracking_schedules.brand_iduniqueone schedule per brand
ws_unique on credit_accounts.workspace_iduniqueone balance per workspace
refund_ref_unique on (ref, workspace_id, kind)unique, partial: only where kind is refund and ref is not emptyone refund row per charge
order_unique on billing_payments.order_iduniquea payment row is reserved before the charge, so the same order cannot be charged twice
free_use_unique on (workspace_id, action, subject)uniquea free allowance cannot be claimed twice
job on billing_daily_runsuniquea daily job is claimed once per day
key_hash on api_keysuniquelookup by hash; the plaintext is not stored
ws_email_unique on workspace_membersuniqueone seat per person per workspace

Partial unique indexes carry most of the weight. A plain unique index on an optional field treats every missing value as the same value, so the second document without a request key would be rejected. The partial filter restricts the rule to documents that have the field, which is exactly the set the rule is about.

The in-memory database used by most tests ignores partial filters. The test configuration patches it to honour them, and a separate set of tests runs against a real MongoDB to confirm the indexes exist and behave as the code assumes. Without the patch the idempotency tests would pass against a database that enforces nothing.

Data that expires

IndexLifetimeWhy
runs_ttl_90d on engine_runs.fetched_at90 daysraw answers are large and age out; the mentions and snapshots derived from them stay
serp_cache_ttl_2d2 dayscached search result pages, kept only briefly because the pages change
expires_at_ttl on one-time codes and login hand-offsat the stored timesecrets that must not outlive their purpose

The 90-day expiry is a product decision as much as a storage one. The derived numbers are what customers compare over months. The raw text is what lets a result be re-checked, and after a quarter the engines have changed enough that a re-check would not reproduce it anyway.

Compare-and-set

Where a unique index cannot express the rule, a conditional update does. The filter states what the writer believes is true, and the write happens only if it is.

WhereConditionWhat it prevents
start on a runstatus is queuedstarting a run twice
heartbeat, finishstatus is running and the lease owner is this processa worker that lost its lease writing a result
claim_interruptstatus is active and the lease expiredthe reaper closing a live run, or two reapers closing one
claim_settlingnot yet settled and no live settlement claimtwo refunds for one run
chargeeach credit bucket holds at least what is takena balance below zero
refundthe marker for this reference is not yet appliedcrediting a refund twice
daily gatethe stored day is not todaya daily job running twice
audit finalizestatus is not already ready or errora reaped audit being overwritten by its late worker
brand fields, topicsrevision equals the revision the editor reada background re-read overwriting a value a person just corrected

The last row is optimistic locking. A brand’s fields can be edited by a person in the dashboard and refreshed by a background job that re-reads the brand’s site. Both read a revision number and write with that number in the filter. The loser gets a conflict and the route answers 409. A person’s correction therefore survives a refresh that started before it.

One primitive for existing documents

The ODM’s save() writes the whole document and inserts it if the id is missing. For a background job that is the wrong default twice over. It can overwrite fields that changed while the job ran, and it can bring back a document that was deleted while the job ran.

All such writes go through save_existing, which lives in its own shared package. It updates by id, accepts extra guard fields, and never inserts. If the document is gone, the write matches nothing and the job learns that from the return value. An import-linter contract keeps that package free of any domain import, so every domain can depend on it without creating a cycle.

What I would change

The balance is stored on the account and the ledger is the explanation. A nightly job that recomputes each balance from the ledger and reports any difference would turn “the two agree by construction” into “the two were checked last night”. The data to do it is already there.