# Request lifecycle

Follow authority and database lifetime from the incoming Request to the response.

## Entry and request scope [#entry-and-request-scope]

`apps/web/src/server.ts` wraps the TanStack handler in `runWithRequestRuntime`. This preserves `waitUntil` without opening a database connection for every public page. When a protected operation needs auth, `createRequestScope(request)` supplies one database and one Better Auth instance.

The scope uses AsyncLocalStorage across asynchronous continuations and a WeakMap for the same Request object. SSR prefetch and cloned Requests can reuse the current scope. A different HTTP request gets a different Worker pool because a Worker socket belongs to the invocation that opened it. Node development reuses its long-lived pool instead.

## Authentication and authorization [#authentication-and-authorization]

The oRPC context calls `getAuthorizedSession`, which bypasses cookie caching and rejects an active Ban. `orgProcedure` additionally looks up current membership in the Session's Active Organization. `adminProcedure` re-reads the authoritative Session before checking the platform role.

```ts
// Server router: orgProcedure supplies a membership-checked organizationId.
const list = orgProcedure.handler(async ({ context }) => {
  return context.db.query.todo.findMany({
    where: { organizationId: context.organizationId },
  });
});
```

Mobile requests can carry the expected user/session/organization scope. The server refuses a changed scope rather than answering a request under a new identity. Cancelling the client wait cannot undo a mutation the server already committed.

## Commit and cleanup [#commit-and-cleanup]

Audited writes enqueue an Audit Event in the same database transaction as the domain change, then attempt publication. The durable audit job recovers unpublished records. AI streams and scheduled jobs own separately bounded pools and explicitly close them when their work settles.

Do not cache a request-bound auth instance, database client or Layer at module scope. Public docs and discovery routes read compiled public content and do not require a Session.


## Key files [#key-files]

- [`packages/auth/src/request-scope.ts`](https://github.com/CarlosZiegler/doro/blob/main/packages/auth/src/request-scope.ts)
- [`packages/auth/src/server-session.ts`](https://github.com/CarlosZiegler/doro/blob/main/packages/auth/src/server-session.ts)
- [`packages/api/src/context.ts`](https://github.com/CarlosZiegler/doro/blob/main/packages/api/src/context.ts)
- [`packages/api/src/index.ts`](https://github.com/CarlosZiegler/doro/blob/main/packages/api/src/index.ts)
- [`packages/db/src/index.ts`](https://github.com/CarlosZiegler/doro/blob/main/packages/db/src/index.ts)

