---
url: /saas-starter/v0.10.1/guide/architecture.md
---
# Architecture

::: tip What this page covers
Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says
which options a part is for. The copy in your app's `docs/` folder has only the parts for yours.
`ApiHost` stands for your app's name.
:::

The Todo feature is a working example of each pattern. Copy it when you add your own features
(the [tutorial](./tutorial.md) builds one step by step).

## The big picture

One ASP.NET Core app serves the API, the realtime connection and the built React client, and
PostgreSQL holds both the data and Wolverine's messages, so there's no message broker to run.

```mermaid
flowchart TB
    browser["Browser: the React app"]
    subgraph host["ASP.NET Core app: one container"]
        endpoints["HTTP endpoints<br/>Features/*"]
        handlers["Message handlers<br/>run in the background"]
        hub["SignalR hub"]
        client["Built React client<br/>wwwroot"]
    end
    db[("PostgreSQL<br/>data, outbox, queues,<br/>scheduled messages")]
    storage[("File storage<br/>disk, S3 or Azure")]

    browser -- "HTTPS /api" --> endpoints
    client -- "pages and scripts" --> browser
    endpoints -- "changes and messages,<br/>in one transaction" --> db
    db -- "durable queues" --> handlers
    handlers -- "messages for browsers" --> hub
    hub -- "WebSocket" --> browser
    browser -- "uploads and downloads,<br/>signed URLs" --> storage
```

## A request, step by step

Completing a Todo shows how an endpoint, the outbox, a background handler and the realtime
connection work together:

```mermaid
sequenceDiagram
    participant B as Browser
    participant E as CompleteTodoEndpoint
    participant DB as PostgreSQL
    participant H as TodoCompletedHandler
    participant S as SignalR hub

    B->>E: POST /api/todos/{id}/complete
    Note over E: validation and loading run first
    E->>DB: the change and TodoCompleted, in one transaction
    E-->>B: 204 No Content
    DB-->>H: TodoCompleted, from a durable local queue
    Note over H: retried on failure, survives a restart
    H->>S: TodoChanged, cascaded from the handler
    S-->>B: todo-changed
    Note over B: every open tab refetches its Todos
```

If the transaction rolls back, `TodoCompleted` is never sent; if the app stops before the handler
runs, it runs after the restart.

## How messages are delivered

What happens to a message after an endpoint or a handler returns it:

```mermaid
flowchart LR
    sent["Returned by an endpoint<br/>or a handler"] -- "in the same transaction<br/>as the data" --> stored[("PostgreSQL<br/>outbox and queues")]
    stored --> handler["Its handler runs"]
    handler -- "succeeds" --> done["Done; the messages it<br/>returns go the same way"]
    handler -- "fails" --> retry["Tried again,<br/>by its retry rules"]
    retry --> handler
    retry -- "keeps failing" --> dead[("Dead letters<br/>wolverine_dead_letters")]
    dead -- "replayed" --> stored
```

* **Stored with the data.** `opts.Policies.AutoApplyTransactions()` commits each endpoint's and
  handler's changes together with the messages it sends, and `UseDurableLocalQueues()` keeps the
  queues in PostgreSQL (both in `Program.cs`). A message is never sent for a change that was
  rolled back, and never lost when the app stops: it's handled after the restart.
* **Make handlers safe to repeat.** A handler's changes to the database are committed with the
  message being marked as handled, but work outside the database, such as an email or a call to
  another service, can happen again if the app stops at the wrong moment. Check the state first,
  as `TodoReminderDueHandler` skips a Todo that was completed in the meantime.
* **One message, several handlers.** When more than one feature handles a message (such as
  `AccountDeleted`), each handler gets its own queue, transaction and retries
  (`MultipleHandlerBehavior.Separated` in `Program.cs`): one feature's failure doesn't undo or
  hold up another's. With Marten, a handler's session saves once, at the end, recording the
  message as handled; a handler that must save more than once (through a store that saves after
  each change) uses a scope of its own, like `LeaveOrganisationsOfDeletedAccountHandler`.
* **Retries.** A handler that depends on something that can be briefly unavailable says how to
  retry in a `Configure(HandlerChain)` method: `Storage/DeleteStoredFiles.cs` tries again after
  increasing delays when the file store fails.
* &#x20;**Dead letters.** A message that keeps failing is moved to the `wolverine_dead_letters` table, with the exception, and kept there. Admins see them on the back office's **Failed messages** page, and replay them once the cause is fixed, or discard them ([Accounts](./accounts.md#roles-and-the-back-office)).
* &#x20;**Dead letters.** A message that keeps failing is moved to the `wolverine_dead_letters` table, with the exception, and kept there until it's replayed or deleted.
* **Scheduled messages** are stored the same way, and are sent when they're due, even across
  restarts.
* &#x20;**The organisation travels with it.** A message sent while handling a request for an organisation carries its tenant id, so its handler's session or `DbContext` is for the same organisation, and a handler can ask for it as a `TenantId` parameter. Outside a request, say which organisation a message is for: `new DeliveryOptions { TenantId = ... }`, as `OrganisationStore` does when it publishes `OrganisationDeleted`.

::: info With organisations

## Organisations and tenancy

Data belongs to an organisation. Nothing in an endpoint filters by it: the organisation travels
from the access token to the data layer and through every message.

```mermaid
flowchart LR
    token["Access token<br/>org claim"] --> wolverine["Wolverine<br/>reads the tenant id"]
    wolverine --> endpoint["Endpoint or handler"]
    endpoint --> data["Marten or EF Core<br/>conjoined tenancy"]
    data --> db[("PostgreSQL<br/>rows tagged with the tenant")]
    endpoint -- "messages carry<br/>the tenant id" --> handler["Background handlers"]
    handler --> data
```

The access token names the organisation the user is working in (`OrganisationClaims`), checked
against their membership when it's issued. `opts.TenantId.DetectWith<TenantResolvers>()` in
`Program.cs` makes it each request's tenant id: the app's tenant resolvers are asked in turn, the
access token's first (`Organisations/TenantResolution.cs`; add your own, such as by host name,
with an `ITenantResolver`). Marten's (or Wolverine's EF Core) conjoined tenancy then adds it to
every query and every row, so a forgotten filter can't leak another organisation's data.
:::

## Backend

* **Endpoints.** Each endpoint is a static method with `[WolverineGet]` or `[WolverinePost]`.
  Wolverine finds it automatically and injects what it asks for. See `src/ApiHost/Features/Todos/`.
* **Validation.** `CreateTodoValidator` (FluentValidation) runs before the endpoint. An invalid
  request gets a 400 response with `ProblemDetails`, which the React form displays.
* **Messages and the outbox.** Completing a Todo returns a `TodoCompleted` message from the
  endpoint. Wolverine saves it in the same database transaction as the change (the transactional
  outbox) and `TodoCompletedHandler` handles it in the background, even after a restart.
* &#x20;**Event sourcing.** A Todo is a stream of events (`TodoCreated`, then `TodoCompleted`). The complete endpoint uses Wolverine's aggregate handler workflow: `[WriteAggregate]` loads the Todo from its events, and the method returns the events to append. An inline snapshot projection keeps a `Todo` document up to date for queries.
* **Scheduled messages.** "Remind me…" on a Todo calls `POST /api/todos/{id}/remind`, which
  schedules a `TodoReminderDue` message for later (`Features/Todos/RemindTodoEndpoint.cs`). Scheduled
  messages are stored in PostgreSQL, so reminders still fire after a restart. When it's due,
  `TodoReminderDueHandler` pushes a `todo-reminder` to the browser, unless the Todo was completed
  in the meantime.
* &#x20;**Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches. Updates go only to the members of the Todo's organisation.
* &#x20;**Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches. Each user only receives updates about their own Todos.
* &#x20;**Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches.
* **Code generation.** Wolverine generates code for each endpoint and handler. In Development
  it does so at runtime, so changes need no extra step; `dotnet publish` generates it ahead of
  time and Production loads it ready-made, failing at startup if any is missing.
* &#x20;**Accounts.** ASP.NET Core Identity with JWT access tokens and rotating refresh tokens; see [Accounts](./accounts.md).

## Frontend

* **Routes.** React Router in framework mode, as a single-page app with no rendering server.
  `src/Client/src/routes.ts` maps each URL to a route module in `routes/`, which default-exports
  the page. `root.tsx` is the HTML document, and `App.tsx` the frame around every page (in
  `components/Layout.tsx`: a header for public pages, and, with accounts, a sidebar for signed-in
  ones; each page inside uses `components/Page.tsx` for its heading and width). Each page's code
  loads when it's first visited,
  so the first page view downloads less JavaScript.
* **Pre-rendered public pages.** The build renders the public pages (the home page, by default)
  into real HTML, so search engines and link previews see their content without running
  JavaScript, and a CDN can cache them. The app then takes over in the browser (hydration). Every
  other page starts from a fallback page. Code that runs while a public page renders must not use
  `window` or `document`, since pre-rendering runs it in Node; use them in effects and event
  handlers.
* **Page titles and search engines.** Each route module's `handle` sets its page title and whether
  search engines may index it (`components/PageMeta.tsx`); only the home page may by default, and
  every other page gets `noindex`. `src/Client/src/pages.ts` lists every page's path and which are public:
  the build pre-renders those and writes the list into `client-routes.json`, from which the API
  answers 404 for other paths and builds `sitemap.xml`. A unit test checks it matches
  `routes.ts`. The default description and link-preview tags are in `root.tsx`: describe your
  product there.
* **Server data.** TanStack Query caches the Todo list (`features/todos/todoQueries.ts`).
  Changes and SignalR messages invalidate it, which refetches it.
* &#x20;**The API client** (`lib/api/client.ts`) is typed from the API's OpenAPI document (`lib/api/schema.d.ts`, regenerated with `npm run gen:api` while the API runs). It adds the access token to each request and, on a 401, refreshes the tokens once and retries.
* &#x20;**The API client** (`lib/api/client.ts`) is typed from the API's OpenAPI document (`lib/api/schema.d.ts`, regenerated with `npm run gen:api` while the API runs).
* **One deployable.** In development, the Vite dev server forwards `/api` (including the SignalR
  WebSocket) to the API, so the browser talks to one origin and no CORS is needed. In
  production, the API serves the built client from `wwwroot`.
