TRAIL Search runs as two processes on one host with one MongoDB database. There is no queue, no worker fleet and no cache tier. The interesting part of the architecture is what replaces them: a run document that any process can reason about, and package boundaries that are checked on every commit.
System

| Component | Technology | Responsibility |
|---|---|---|
search-web | Next.js 15, React 19, App Router, Tailwind, Recharts | the dashboard, onboarding, billing screens, and the public marketing and blog pages |
| REST routes | FastAPI on uvicorn, Python | every read and write; workspace resolution, role gates, credit charging |
/mcp | FastMCP over streamable HTTP, mounted in the API app | tools for customer agents, each one a call to an existing REST route |
| Domain packages | Python packages in an Nx workspace, managed with uv | the business logic, one package per domain |
| MongoDB | Motor driver, Beanie document models | all state: runs, answers, credits, payments, tenants, keys |
| Scheduler loop | asyncio task in the API process | due tracking schedules, daily renewal, other daily jobs |
| Reapers | asyncio tasks in the API process | close runs and audits whose owner stopped, and refund them |
| Answer engines | LLM APIs and search pages with AI answers, behind one adapter interface | the thing being measured; each call is paid |
| Toss Payments | billing key charges, widget confirm, order lookup | card payments for plans and top-ups |
The product has four surfaces that customers see: a site and brand audit, question discovery, share of voice against competitors, and the brand’s own visibility over time. The last two run on the same measurement engine. The fourth is a read view over what the third produces.
The life of a run

In the web app, the run dialog first asks the API for a cost preview, then posts the run, then polls the run’s status. On the server the route does its work in a fixed order: resolve the scope, compute the cost, plan the cells, check for a replayed request key, save the run as queued, charge, and start the background task. The task runs the fan-out, stores every attempt, extracts mentions, writes the snapshot if it still owns the run, settles any refund and marks the run finished.
Scheduled runs enter the same path one step later: the scheduler loop creates the run with a claim key and calls the same execution function. Recovery enters at the end: the reaper claims an expired run and calls the same settlement function. Each of these has its own page under deep dives.
Packages and layers
The backend is a set of Python packages, one per domain, plus a few shared ones. Each domain package has four layers, api, usecases, adapters and model, and a layer may import only the layers below it.
| Package | Responsibility |
|---|---|
domain-engine | fan-out to engines, mention extraction, share of voice, run batches, prompt health |
domain-audit | scoring a URL or a brand for AI search, site audits, prescriptions |
domain-keywords | deriving the questions customers ask, mapped to an awareness funnel |
domain-brand | a thin read view over the engine’s results for one brand |
domain-billing | credit ledger, top-ups, subscriptions, dunning |
domain-workspace | tenants, users, members, API keys, sign-in |
domain-metrics | GA4 and Search Console joins, AI-referral traffic |
domain-content, domain-channels | article lifecycle and publishing to connected sites |
shared-persistence | one primitive: a conditional write that never upserts |
shared-utils | pure helpers with no external dependencies |
shared-integrations | vendor wrappers for LLMs, search, storage, email |
The rules are enforced by tools. Python imports are checked by import-linter contracts and TypeScript imports by the Nx module-boundary lint rule. Three contracts show the style.
- The app is on top. No domain or shared package may import the application package.
- Billing is isolated. The billing package may not import any other domain, so no domain’s logic can creep into how money is counted.
- Persistence is a leaf. The shared persistence package may not import any domain.
One contract is strict on purpose in a way that shaped the code. The channels package may not import the audit package, so the check that verifies a customer owns a site before publishing to it had to be composed in the application layer, where both are visible, instead of inside either domain.
The isolation contracts for the engine and audit packages are still marked as deferred. The engine’s run route imports the billing package directly to charge and refund. I know where that line should be, in the application layer, and have not moved it yet.
Processes and deployment
Two processes run under pm2 in fork mode, one instance each: the API and the Next.js server. The API restarts if it passes its memory limit. Everything that runs in the background is an asyncio task started in the API’s lifespan hook: the audit reaper, the run reaper, the scheduler loop and, when the MCP transport is on, its session manager. Measurement runs are tasks created by request handlers.
The flags that can spend money are pinned in the pm2 configuration file, which is in version control, not in the server’s environment file. The scheduler is on, blog automation is off, paid MCP tools are off. A value set in the process configuration cannot be overridden by an environment file that someone edited on the server.
A deploy is one script run from a developer machine.
- Pre-checks: the right rsync, no local dev server running from this repository, the expected Node major version.
- Load the public build-time environment and abort if the code reads a public variable that is not pinned.
- Build the Next.js app locally and record the build id.
- Transfer with rsync, excluding secrets, virtual environments and caches.
- Compare the build id on the server with the local one and abort before any reload if they differ.
- On the server: sync Python dependencies, install Node dependencies from the lockfile, test and reload the proxy configuration, reload both processes.
- Health-check the API and the web server, retrying for half a minute.
There is no automatic rollback. An abort before the reload leaves the running processes untouched. After the reload, rollback is a redeploy of the previous commit.
Design decisions
One process runs everything, and the run document makes that safe. I chose in-process asyncio tasks over a queue with workers because the product runs on one host and a queue would be a second system to operate. The cost is that a deploy kills runs in flight. The lease and reaper turn that from a silent loss into a refunded, visible interruption. If the load outgrows one process, the lease already identifies owners by process, so moving runs to separate workers changes where tasks start and not how they are claimed.
State changes are conditional updates, never a loaded document saved back. The ODM’s save() is an upsert by id. A background job that loads a document, works for a minute and saves it can recreate a row that was deleted in the meantime. I confirmed against a real MongoDB that a purged account or brand could come back this way. The fix was a single shared primitive, save_existing, that matches the id plus optional guard fields and never inserts, applied at every call site that had used save() on a document it did not just create.
REST is the source of truth and MCP is an adapter. MCP tools call the REST routes in-process. Workspace scoping, role gates and credit charging exist once. The alternative, tools calling use cases directly, would have duplicated those checks in a second place with no test forcing the two to agree.
Things that spend money default to off, and the switch lives in version control. The scheduler, blog automation and paid MCP tools are each behind a flag. The MCP transport itself is on by default because it needs a key and spends nothing.
The frontend is built on the developer machine and shipped as files. The host shares its memory with other applications, and a Next.js build on the server could push the running API over its limit. Building locally costs a build-id check to prove the server is serving what was built.
Scores are versioned in the data. The metric definitions, the mention classifier and the context format each carry a version constant that is part of every comparison key. Changing how something is scored breaks comparability on purpose, and the dashboard says so, instead of producing a step in a chart that looks like a change in the customer’s visibility.
What this shape cannot do
It cannot survive the loss of the host, since the database and both processes share it. It cannot run two API instances without moving two things first: the in-memory rate limit for MCP keys and the assumption, in a few daily jobs, that one process is ticking. Both are known and written down next to the code that makes the assumption.
