# Filter chain

The fixed order in which a capability's checks and wrappers run around your pipeline:
`.error()`, `.authorize()`, the source's parse, `.input()`, `.throttle()`,
`.circuitBreaker()`, `.retry()`, `.timeout()` and `.concurrency()`, then the
`.cache()` check before your steps and the cache store after them.

Routecraft runs a **fixed ordered chain** of framework filters
around every exchange before and after your user pipeline. The
chain order is the framework's call: the order you happen to
type `.authorize()`, `.input()`, or `.cache()` on the builder does
not change runtime behaviour. This is the same idea as Spring's
`FilterChainProxy` or ASP.NET middleware: the framework picks the
order; you opt in by declaring which filters you want.

## The chain

Outside in (position 1 wraps everything below):

| # | Filter | Opts in via | Throws on rejection | Reads / produces |
|---|---|---|---|---|
| 1 | `error` | `.error(handler)` | - | catches throws from everything below |
| 2 | `authorize` (stacks) | `.authorize({ roles, scopes, predicate })` | `RC5012` / `RC5015` / `RC5023` / `RC5020`; delegation `RC5034`-`RC5038` | principal on `exchange.headers` |
| 3 | `parse` | source adapter (HTTP, mail, CSV, ...) | `RC5016` | raw body bytes → typed body |
| 4 | `input` | `.input(schema)` | `RC5065` | typed body / headers |
| 5 | `throttle` | `.throttle({ rate, per, mode })` | `RC5013` (`mode: 'reject'` only; default `'delay'` paces) | rate limit on the route (delay or reject) |
| 6 | `circuitBreaker` | `.circuitBreaker({...})` | `RC5025` (fast-fail when open) | failure stats; fast-fails when open |
| 7 | `retry` | `.retry({...})` | final attempt's throw | re-runs everything below on failure |
| 8 | `timeout` | `.timeout(ms)` | `RC5011` | per-attempt deadline |
| 8.5 | `concurrency` | `.concurrency({ max })` | `RC5026` (`mode: 'reject'` or full `maxQueue`; default `'queue'` paces) | bulkhead; bounds simultaneous in-flight (innermost resilience, so a slot is held per attempt) |
| 9 | `cacheCheck` | `.cache({...})` | `RC5028` / `RC5029` | route id, pipeline fingerprint, principal, validated body → cache key |
| - | **your pipeline** | `.transform()`, `.to()`, `.process()`, ... | - | the work |
| 10 | `cacheStore` | `.cache({...})` | swallows (`route:cache:failed phase:"set"`) | terminal body, written best-effort |

> **Note: Position #4 (`input`) is a real chain step**
>
> `.input()` validation runs inside the chain at position #4: after auth and parse, before any resilience wrapper, `cacheCheck`, or user step. When the source attaches a parser, the validator runs inside the parse step (input validates the parsed body); otherwise it runs as a standalone synthetic `input` step. Either way a failure throws `RC5065` through the chain's catch boundary, so `.error()` can observe and recover it exactly like an `authorize` or `parse` rejection. An unrecovered failure takes the normal error path (`route:error`, `context:error`, `route:exchange:failed`); it is not a drop.

## What this means in practice

### The chain runs in this order regardless of how you typed it

These three routes behave identically:

```ts
craft()
  .id('list-employees')
  .authorize({ roles: ['hr'] })
  .input(schema)
  .cache({ ttl: 60_000, key: e => String(e.headers[HeadersKeys.ROUTE_ID]) })
  .from(http({ path: '/employees' }))
  .enrich(loadEmployees)
  .to(noop())

craft()
  .id('list-employees')
  .cache({ ttl: 60_000, key: e => String(e.headers[HeadersKeys.ROUTE_ID]) })
  .input(schema)
  .authorize({ roles: ['hr'] })
  .from(http({ path: '/employees' }))
  .enrich(loadEmployees)
  .to(noop())

craft()
  .id('list-employees')
  .input(schema)
  .cache({ ttl: 60_000, key: e => String(e.headers[HeadersKeys.ROUTE_ID]) })
  .authorize({ roles: ['hr'] })
  .from(http({ path: '/employees' }))
  .enrich(loadEmployees)
  .to(noop())
```

All three run `error` → `authorize` → `parse` → `input` →
`cacheCheck` → `enrich` → `to` → `cacheStore`. The DSL is
declarative; you state which filters apply, not what order they
run in.

The examples pass a custom `key`, which `cacheCheck` uses verbatim: the route id, pipeline fingerprint and principal from the table above are added only to the default key. A key of the route id alone is right here only because every caller who passes `.authorize()` sees the same employee list. When the answer depends on the caller or the request, use the default key, or a custom key that includes the principal and the request's params and query (a bodiless GET like this one needs the custom key, because the default fails with `RC5029`).

Because `cacheCheck` runs before your pipeline, a route-scope `.cache()` on a route whose pipeline contains `.authenticate()` is refused at build with `RC5003`: a hit would skip authentication.

### Each filter throws on rejection; `.error()` decides what to recover

Filters 2-9 propagate failures upward by throwing. `.error()` is
the outermost catch:

```ts
.error((err) => {
  // Deterministic rejections: re-throw so the source can translate
  // (e.g. HTTP returns 401, 403, or 400). Do not collapse the authorize
  // codes: each one tells the client something different (see the
  // authorize() reference).
  if ([
    'RC5012', 'RC5015', 'RC5023', 'RC5020',
    'RC5034', 'RC5035', 'RC5036', 'RC5037', 'RC5038',
    'RC5065', 'RC5016',
  ].includes(err.rc)) throw err

  // Backpressure: re-throw so the caller sees it.
  if (err.rc === 'RC5013') throw err

  // Operational failures: recover with a fallback.
  if (err.rc === 'RC5011') return { fallback: 'timeout', data: stale }
  if (err.rc === 'RC5028') return { fallback: 'cache-down', data: stale }

  throw err
})
```

Without `.error()`, every throw goes to the route's default error
path (`route:error` + `context:error` + `route:exchange:failed`).
The route is **not** stopped: the next exchange processes
normally.

### A resumed exchange re-enters partway down the chain

When a route [defers](/docs/reference/operations/defer) and is later resumed, execution two runs the continuation only: the steps after the defer point. It is the same exchange (same id, same correlation id) in the same route, but it did not enter the route again, so the positions that describe an arrival do not re-run.

Nothing is left standing to fall back into: execution one unwound its chain when it deferred. The framework builds a **fresh chain** for execution two out of the positions declared to survive, keeping their relative order, and runs the continuation inside it. That nesting is why `timeout` still wraps `concurrency` on a resume.

Every position states its own answer. This is a declaration in the framework, not a side effect of how a continuation happens to be executed, so a position cannot quietly stop applying.

| # | Filter | Execution two | Why |
|---|--------|---------------|-----|
| 1 | `error` | **runs** | The route still owns the exchange, and a revival failure has nowhere else to go: only this route can notify and re-ask |
| 2 | `authorize` | does not run | The principal came back from the store marked restored, so it would fail `RC5043` rather than admit anything. Authorize the ANSWER on the resume ingress route, where a live principal exists |
| 3 | `parse` | does not run | The body was parsed on execution one and stored parsed |
| 4 | `input` | does not run | `.input()` validates the shape arriving at the route, and execution two starts mid-pipeline with a body earlier steps already transformed. The ANSWER is validated instead, against the deferring step's `expect` |
| 5 | `throttle` | does not run | It admits new work into the route, and this exchange was admitted on execution one. Answer arrival is governed by the resume ingress route's own `throttle` |
| 6 | `circuitBreaker` | does not run | By the time a continuation runs, the resume has already claimed the deferral, so fast-failing here would record a failed continuation result and spend the approval. Put the breaker on the resume ingress route, whose chain wraps `.resume()` and so refuses subsequent answers before they are claimed |
| 7 | `retry` | **runs** | Attempts happen before any continuation result is recorded, so a retried continuation never spends the approval it was answering |
| 8 | `timeout` | **runs** | Bounds execution two. Distinct from `ttl`, which is a store-side expiry on the deferral rather than a per-attempt deadline in this process. It wraps the bulkhead below it, so on a route that also declares `.concurrency()` the deadline covers the wait for a slot as well as the work. Route-scope `.retry()` mitigates this in practice, because it re-attempts before any continuation result is recorded; closing it properly means moving admission above the claim ([#598](https://github.com/routecraftjs/routecraft/issues/598)) |
| 8.5 | `concurrency` | **runs**, in waiting form | Ingress executions and resumed continuations compete for the same limiter, because a bulkhead bounds work against a downstream and a continuation is that work. A continuation only ever **queues** for a slot: `mode: 'reject'` and `maxQueue` do not apply to it, because refusing below the claim would spend an approval on work that never ran. That wait has no deadline of its own, so size `max` for the answer rate you expect |
| 9 / 10 | `cache` | refused at build | Both filters wrap the user pipeline, which a deferral exits and a resume re-enters partway down, so neither would ever run (`RC5003`) |
| - | **your continuation** | runs | Steps after the defer, with their own step-scope wrappers |
| - | `.output()` | runs | Execution two produces the route's real output |

> **Warning: Route-scope `.retry()` re-runs continuation steps**
>
> A route-scope `.retry()` applies to execution two, so the steps after a `.defer()` are at-least-once on failure, the same as the steps before it. If your continuation does something a downstream cannot absorb twice (issuing a payment, sending a message), make it idempotent or move it behind a step-scope wrapper you control.

Inside the continuation, step-scope wrappers work normally, and because a wrapper wraps the immediately following step, a nesting operation groups a whole block under one:

```ts
.defer({ schema: Approval, ttl: '72h' })
.retry({ maxAttempts: 3 })
.choice(otherwise((b) => b
  .transform(executePayout)
  .to(ledger())
))
```

When you want the positions that stay off, hand the continuation to a route that has them:

```ts
.defer({ schema: Approval, ttl: '72h' })
.to(direct('execute-payout'))

craft()
  .id('execute-payout')
  .authorize({ scopes: ['payouts:execute'] })
  .circuitBreaker({ failureThreshold: 5 })
  .retry({ maxAttempts: 3 })
  .from(direct())
  .transform(executePayout)
  .to(ledger())
```

That route is an ordinary route, so every position of the chain applies to it, and it is authorized on its own terms rather than on a principal read back from disk. This is the recommended shape when the work after an approval needs `authorize` or a circuit breaker.

A `.debounce()` release re-enters partway down too, and answers these questions differently: it is work the route held back and never admitted, so it keeps `error` and nothing else. The two are separate declarations rather than one shared rule.

## Why this order

### Top half (1-4): deterministic gates

These are guards, not work. They're cheap, deterministic, and run
once per request. Retrying them is pointless.

- **`error` outermost.** Conceptually filter #1: its try/catch
  wraps the rest. Same shape as Spring's
  `ExceptionTranslationFilter`.
- **`authorize` before `parse`.** Authorize reads the principal
  from headers; it doesn't need a parsed body. Running it first
  means an unauthenticated caller gets a clean `401` / `403`
  without the framework leaking schema information via a `400`.
- **`parse` before `input`.** Input validates the parsed shape, not
  raw bytes.
- **`input` before resilience wrappers.** A request that fails
  schema is never going to succeed on retry. Reject early.

### Middle (5-8.5): resilience wrappers

These DO retry / time out / fail fast. Standard outside-in
following Resilience4J conventions.

- **`throttle` outside `circuitBreaker`.** A throttled request
  shouldn't count as a breaker failure (the inner operation didn't
  even run).
- **`circuitBreaker` outside `retry`.** When the breaker is open,
  fast-fail. Retries happen *within* one breaker call.
- **`retry` outside `timeout`.** Each retry attempt gets its own
  deadline; per-attempt timeout is more useful than a shared budget.
- **`concurrency` innermost (inside `timeout`).** A bulkhead slot is
  held only for the duration of one attempt: it is acquired at the
  start of each attempt and released the moment the attempt settles,
  so a `retry` backoff sleep holds no slot. An outer `.retry()` can
  also re-acquire a slot after a `reject`-mode `RC5026` ejection.
  Contrast `.throttle()` (#5, outermost): a throttle rejection is
  outside retry and can only be caught by `.error()`, never retried.

### Bottom (9-10): cache

Innermost. The pipeline's surface.

- **`cacheCheck` just above the pipeline.** A hit short-circuits
  the pipeline without triggering retry / breaker / timeout (a hit
  is a successful zero-cost call from those layers' perspective).
- **`cacheStore` just below the pipeline.** Runs only on
  miss-success. Cache write errors are swallowed (the result is
  already computed); they emit `route:cache:failed phase:"set"` for
  observability but don't fail the exchange.

## Combined scenarios

### Authorize fails

```
error
  └─ authorize throws RC5012  (no principal) or RC5015 (forbidden)
       └─ everything below is skipped
```

`.error()` catches. If your handler re-throws auth errors (the
default for most apps), the source translates: HTTP returns 401 /
403, MCP returns an auth error.

### Cache hit

```
error
  └─ authorize  PASS
       └─ parse  PASS
            └─ input  PASS
                 └─ cacheCheck  HIT  → cached body returned, pipeline skipped
```

The pipeline (including `cacheStore`) never runs. Filters 2-4 still
ran, so an unauthorized caller never sees a hit.

### Pipeline throws

```
error
  └─ authorize  PASS
       └─ parse  PASS
            └─ input  PASS
                 └─ cacheCheck  MISS
                      └─ pipeline  THROWS
                           └─ cacheStore  SKIPPED  (only runs on success)
```

The throw propagates up through `cacheCheck` (already passed; just
re-throws), out to `.error()`. Nothing is cached. Next request with
the same body re-runs the pipeline.

### Retry outside timeout

With route-scope `.retry()` and `.timeout()` declared on the route:

```
error
  └─ authorize  PASS
       └─ parse  PASS
            └─ input  PASS
                 └─ retry  attempt 1
                      └─ timeout  hits 5s deadline → throws RC5011
                 ←  retry catches RC5011, attempt 2
                 └─ timeout  pipeline returns in 800ms → SUCCESS
                      └─ cacheStore  writes result
```

Per-attempt deadlines. Retry sees individual failures and decides
whether to re-attempt.

## What the chain commits the framework to

- **No reorder API.** You opt filters in by declaring them; the
  order is the framework's call. If a future use case really needs
  a different order, it's an explicit RFC, not a per-route knob.
- **All wrappers throw on rejection.** `.error()` is the universal
  catch; recovery is opt-in per RC code in the handler.
- **Deterministic gates above resilience wrappers.** Auth, parse,
  input run once; they're not retried.
- **Cache is below resilience wrappers.** A timeout / retry /
  breaker around cache means the framework retries pipeline calls
  that exceeded their deadline; cache hits short-circuit without
  triggering them.

---

## Related

- [Operations](/docs/introduction/operations#wrappers) -- The same wrappers after .from(), where each one covers a single step.
- [authorize](/docs/reference/operations/authorize) -- Roles, scopes, subject and actor rules, and the code each refusal throws.
- [cache](/docs/reference/operations/cache) -- Cache keys, TTLs and providers, at route scope and at step scope.
- [Errors](/docs/reference/errors) -- Every RC code the chain throws, with what it means and how to fix it.
