# Apollo Federation Patterns

## Architecture

- **Router**: Apollo Router 2.12 (Rust) at `graphql-router`
- **Federation**: Version 2.0.3
- **Subgraphs**: 17 services (5 in this workspace + 12 external)
- **Composition**: Via `rover supergraph compose`

## Subgraph Requirements

Each subgraph must:
1. Expose a valid Apollo Federation schema
2. Support `_service` SDL query (Apollo Server handles this automatically)
3. Define `@key` directives on entity types
4. Handle reference resolution for federated entities

## Entity Definition

```graphql
type Product @key(fields: "id") {
    id: ID!
    name: String!
    # ... fields owned by this subgraph
}
```

## Extending Types Across Subgraphs

```graphql
# In graphql-product
type Product @key(fields: "id") {
    id: ID!
    name: String!
}

# In graphql-analytics (extending Product with analytics)
type Product @key(fields: "id") {
    id: ID! @external
    streamCount: Long
}
```

## Schema Changes

### Safe Changes (No Coordination Needed)
- Adding new fields to existing types
- Adding new types
- Adding new enum values
- Adding optional arguments to existing fields

### Breaking Changes (Require Coordination)
- Removing fields → deprecate first, then remove after consumers migrate
- Renaming fields → add new field, deprecate old, remove after migration
- Changing field types → generally not safe
- Removing enum values → breaking for clients using them

## Supergraph Composition

```bash
cd graphql-router
make supergraph  # Introspects all subgraphs + composes
```

If composition fails:
1. Check `scripts/generate-supergraph.sh` for subgraph URLs
2. Ensure all subgraphs are running (or use QA URLs)
3. Look for conflicting type definitions
4. Check `@shareable`, `@external`, `@requires` directives

## Header Propagation

The router propagates all headers to subgraphs except `x-datadog-*` (stripped). Key headers:
- `Apollographql-Client-Name` — required by router plugin
- `Authorization` — Bearer JWT or HMAC token
- Grass headers — account context for authorization

## Traffic Shaping

- Router timeout: 65 seconds
- Per-subgraph timeout: 65 seconds
- Query plan cache: 1024 entries (in-memory)
