# Architecture

> Services, request paths, storage and the delivery guarantees the bridge makes.

URL: https://chatwork.io/en/docs/architecture
Section: Platform

## Services

```
chatwork.io ──► Caddy ──► site (static)          apps/web
                 ├──► bridge (FastAPI, :8090)     apps/bridge
                 └──► chatwoot-rails (:3000) + chatwoot-sidekiq
                          │
            postgres (pgvector/pg16) ── databases: chatwoot, dot_bridge
            redis 7 ── chatwork jobs + bridge counters, locks, control state
```

The bridge is one process with router auto-discovery (`routes/*.py`), two background workers (the X poller and the outbox drain) and no ORM: hand-written SQL migrations in `migrations/NNN_*.sql`, applied by `python -m storage.migrate` under an advisory lock.

## The webhook path (one customer message)

1. **Auth and shape.** The inbox engine (chatwork) does not sign webhooks, so the agent-bot URL carries a secret. Non-`message_created`, private notes and empty content are ignored.
2. **Dedup, then store.** `SET NX` on `(account, conversation, message)`, then the event is written to the inbox as `received` before anything else happens.
3. **Routing to a tenant.** The exact `(account, inbox)` pair must match one active tenant's match set; zero or two matches are quarantined. No reply, no usage.
4. **Guards.** The bot's own echoes, mirrored `/inbound` conversations and conversations a human already owns are skipped.
5. **Pipeline.** `can_ai_reply → begin_ai_reply (generation) → usage.reserve → LLM → may_dispatch(generation) → deliver`. Inside the LLM step Chatwork Router routes the message to an agent and grounds it ([details](/en/docs/router)).
6. **Delivery.** The reply is posted to the inbox with the tenant's bot token; on X conversations it is enqueued to the outbox, which re-checks ownership after the human delay and right before the send.
7. **Handoff.** A keyword, a model tag or an agent policy opens (or reuses) the conversation's ticket, posts a private note and sets the conversation to `open`.
8. **Settle.** Usage is settled with real token counts; the event ends `processed` or `failed(error)`, retryable by an admin.

## Storage

- **PostgreSQL** is authoritative for tenants, usage ledger, invoices, payments, subscriptions, connections (encrypted secrets), members and sessions, tickets, commerce, events, audit, quarantine and Chatwork Router (agents, intents, sources, chunks, routing log).
- **Redis** keeps rate limits, usage reservations, conversation control (owner + generation), MCP tool cache, X dedup/cursor, short-lived sessions and locks (`SET NX PX`, token-checked release).
- **The inbox** (chatwork's database) keeps conversations, messages, contacts, assignment and labels.

`DOT_STORAGE_BACKEND=redis` (the historical default) keeps bridge records in Redis with the same code paths; `postgres` makes PostgreSQL authoritative with a Redis mirror. Chatwork Router always uses PostgreSQL when `DOT_DATABASE_URL` is set, independent of that flag.

## Guarantees

- **At least once.** Every accepted webhook is persisted before processing; every X send goes through the outbox with backoff (60 s → 5 min → 30 min → 2 h) and a dead state after `outbox_max_attempts`.
- **Late AI replies never win.** The control generation is re-checked immediately before every send; a human takeover in between drops the AI reply.
- **No customer-facing text on provider errors.** A failing LLM produces a private note and a handoff, never an invented answer.
- **Quota before cost.** Usage is reserved before the model is called and released on failure.
