# ADR-002: Data Fetching Architecture

**Status:** Accepted **Date:** 2026-02-21

## Context

The OSHUN web app fetches data from a BFF (Backend-For-Frontend) layer that
aggregates multiple backend domain services. We needed a data fetching strategy
that handles caching, error recovery, request deduplication, and works well with
React's rendering model.

## Decision

We use a **two-layer data fetching architecture**:

### Layer 1: API Client (`src/lib/api-client.ts`)

A typed HTTP client that handles transport-level concerns:

- **Request deduplication**: Identical GET requests within 5 seconds share one
  network call
- **Retry with exponential backoff**: GET requests retry up to 3 times;
  mutations do not retry
- **Token injection**: Authorization header added from auth context
- **Correlation IDs**: Every request tagged with `X-Correlation-ID` for
  distributed tracing
- **Timeout handling**: Configurable `AbortSignal`-based timeouts
- **Typed errors**: All failures throw `ApiRequestError` with status, code,
  message, and requestId

### Layer 2: React Query Hooks (`src/lib/hooks/use-bff.ts`)

Typed query and mutation hooks for each BFF endpoint:

- **Per-endpoint stale times**: Home (60s), activity (30s), notifications (15s),
  search (2min), profile (5min), entitlements (10min)
- **Automatic refetching**: On window focus and network reconnect
- **Infinite queries**: Cursor-based pagination for activity feed
- **Optimistic updates**: Notification mark-all-read updates cache before server
  confirms
- **Cache invalidation**: Mutations invalidate related queries on success

## Rationale

### Why a BFF pattern?

- Frontend makes fewer, larger requests instead of many microservice calls
- Response shapes are optimized for UI rendering
- Backend handles service orchestration, reducing frontend complexity
- Single point for rate limiting, auth, and caching

### Why a custom API client on top of fetch?

- Request deduplication prevents redundant calls from React's concurrent
  rendering (StrictMode double-effects)
- Centralized retry logic with exponential backoff
- Typed error handling consistent across all endpoints
- Token management separated from business logic

### Why per-endpoint stale times?

Different data has different freshness requirements:

- Notifications need near-real-time (15s stale, 60s refetch)
- Entitlements change rarely (10min stale)
- Home feed balances freshness with performance (60s stale)

## Consequences

- Two layers means two places where request behavior can be configured
- Deduplication window (5s) could cause stale reads in rare edge cases
- Retry logic on GETs means the user may see stale data while retries happen in
  the background
- All data flows through the BFF — no direct microservice access from the
  frontend
