# Service Interaction Patterns

This guide captures how Lilith services communicate and how the BFF orchestrates
requests.

## Synchronous pattern (default)

- Clients talk only to the BFF.
- BFF calls downstream services over REST (OpenAPI-covered).
- Responses are adapted by the BFF for each channel (web/mobile/voice).

```mermaid
sequenceDiagram
  participant Client
  participant BFF
  participant Auth
  participant Conversation
  participant AI

  Client->>BFF: POST /v1/chat (token)
  BFF->>Auth: GET /v1/auth/introspect
  Auth-->>BFF: user + scopes
  BFF->>Conversation: POST /v1/conversations
  Conversation-->>BFF: conversationId
  BFF->>AI: POST /v1/ai/chat {conversationId, prompt}
  AI-->>BFF: ChatResponse
  BFF-->>Client: Channel-shaped reply (web/mobile/voice)
```

## Async side-effects (non-critical)

- Background jobs (notifications, analytics, cache invalidation) are emitted to
  queues/streams.
- Core flows do **not** depend on eventual events; they complete synchronously.

```mermaid
sequenceDiagram
  participant BFF
  participant Notification
  participant Analytics

  BFF-->>Notification: emit "message.sent" event
  BFF-->>Analytics: emit "chat.turn" event
  Note over Notification,Analytics: Delivery is best-effort; core response already returned.
```

## Testing and local validation

- Prefer `app.inject()` with Fastify to exercise routes without opening ports.
- Avoid cross-service imports; use shared libraries (`services/lib`,
  `services/common`, token/meditation/transaction cores).

## Anti-patterns to avoid

- Direct client → core service calls (bypass BFF).
- Cross-service DB access or in-process imports.
- Event-only implementations for core read/write flows where determinism is
  required.

## Related ADRs

- ADR-0001 (microservices architecture)
- ADR-0007 (service interaction patterns and BFF role)
