Feature: Exchange rates (reference outbound integration)
The template's worked example of depending on an HTTP API you do not own (ADR-0020). It exists to be copied: the interesting part is not currency conversion, it is the wiring around the call.
Like the Invoices slice, this is reference material — delete it once a real integration replaces it.
src/
IExchangeRateProvider.GetRateAsync(baseCurrency, quoteCurrency, ct) → Result<decimal>.
Failures are split by whether waiting helps:
| Error | ErrorType |
Our API answers | Means |
|---|---|---|---|
ExchangeRateErrors. |
Unavailable |
503 | the provider is down for now: retry later |
ExchangeRateErrors. |
Failure |
500 | the provider refused our credentials, plan or URL: fix the configuration |
ExchangeRateErrors. |
Failure |
500 | an answer the adapter cannot read |
ExchangeRateErrors. |
Validation |
400 | the caller asked for a currency the feed does not publish |
Nothing the third party does reaches Application code as an exception (ADR-0004) — except the
caller's own cancellation, which propagates as OperationCanceledException. An endpoint that calls
the port declares the 503 with a bare .Produces(StatusCodes.Status503ServiceUnavailable) (ADR-0020,
amendment of 2026-10-11); none ships today. An outbox event handler that calls the port cannot
return the Result: it throws on Unavailable or Rejected, so the outbox retries it with back-off,
and logs UnknownCurrency and returns, since no retry changes the answer
(.claude/rules/application.md).
Adapter
Section titled “Adapter”src/
| File | Role |
|---|---|
ExchangeRateOptions |
BaseUrl / TimeoutSeconds / MaxRetries, annotated and validated at boot |
ExchangeRateClient |
internal sealed typed HttpClient; maps every transport and pipeline outcome to a Result |
ExchangeRateHealthCheck |
Cached TCP probe; Degraded when unreachable, Unhealthy when misconfigured |
Registered by AddOutboundIntegrations(configuration) — the API only, not AddInfrastructure.
The migration service never calls a third party, so nothing in an ExternalApis section can stop it
from running migrations. Registration alone would: the standard resilience handler validates its own
options at boot, and this client's are computed from ExchangeRateOptions.
Behavior
Section titled “Behavior”- Resilience is replaced per client, not added.
ServiceDefaultsattaches a standard resilience handler to everyHttpClient(10 s per attempt, 30 s total, 3 retries). A secondAddStandardResilienceHandler(...)on its own nests inside that one: the blanket 10 s still cancels every attempt and each outer retry reruns the client's whole retry loop. So the client first callsRemoveAllResilienceHandlers()(experimental,EXTEXP0001suppressed with the reason), then adds its own handler. Its chain holds exactly oneResilienceHandler. - The pipeline reads the options lazily.
AddStandardResilienceHandler().Configure((o, sp) => …)resolves the validatedExchangeRateOptionswhen the pipeline is built — no snapshot bound at registration time. - The total budget includes back-off. Retries wait exponentially with jitter from 2 s, each wait
capped at 5 s; the total timeout is
TimeoutSeconds × (MaxRetries + 1) + 5 s × MaxRetries(40 s on the defaults), so the total timeout never cuts off a retry the policy granted. A provider'sRetry-Afteris honoured; one longer than the remaining budget ends the call asUnavailable. - Timeouts belong to the pipeline, not the client.
HttpClient.Timeoutis set toTimeout.InfiniteTimeSpandeliberately — leaving the 100s default would cap the whole pipeline including retries and race the per-attempt timeout.MaxRetrieshas a floor of 1: the handler validatesMaxRetryAttempts >= 1and throws at first use on 0. - What the adapter catches — the pipeline's exceptions, not a bare
HttpClient's:HttpRequestException(transport), Polly'sTimeoutRejectedException(attempt timeout or total budget — notTaskCanceledException),BrokenCircuitException(open circuit, nothing sent) and any otherExecutionRejectedException(the concurrency limiter) →Unavailable;JsonException→MalformedResponse; anOperationCanceledExceptionthe caller did not cause →Unavailable. The caller's own cancellation is not caught. - An error status is mapped by this endpoint's contract, not by its class (
MapFailure; the status table under Configuration). What arrives there is final: the pipeline already retried the transient ones. The provider's error text is never copied into an error. - A 200 can still be a failure. An object body with
"success": false(providers that wrap their errors in a 200: a missing key, an exhausted plan) →Rejected, logged at Error; Frankfurter's array is read normally; any other shape — v1's object among them, or a quote without a rate — →MalformedResponse. A quote the answer does not contain (an empty array included) →UnknownCurrency. The quote is matched whatever its case: Frankfurter acceptsusdand answersUSD. - Configuration fails at boot, not on first call. A malformed
BaseUrlstops the API with a precise message instead of surfacing later as a timeout or aNullReferenceException. - The health check cannot be used as a load lever. It opens a bare TCP connection (no application
request) and caches the verdict for 30 seconds, so however often
/healthis polled the provider sees at most one connect per window. It must stay a singleton or the cache does nothing. - Degraded ≠ Unhealthy. A provider outage reports Degraded so an orchestrator does not pull a
perfectly serving instance out of rotation over someone else's problem; a malformed
BaseUrlreports Unhealthy because that is our deployment being wrong.
Configuration
Section titled “Configuration”"ExternalApis": { "ExchangeRates": { "BaseUrl": "https://api.frankfurter.dev/v2/", "TimeoutSeconds": 10, "MaxRetries": 2 }}The default provider is Frankfurter's v2 API (ECB reference rates, no access
key), read through rates?base=EUR"es=USD → [{"date":"…","base":"EUR","quote":"USD","rate":…}]:
one element per quote, no date meaning the latest rates. Frankfurter's /v1 (latest?base=&symbols= →
an object of rates) is deprecated — it answers with a Deprecation header dated 2026-05-18 and a
successor-version link to /v2/rates — so the adapter moved to v2, which serves the same use case. The
previous default before that, api.exchangerate.host, now requires an access key and answers every
keyless call with success:false at HTTP 200.
What v2 answers when it does not answer a rate was probed (2026-10-11), and the adapter maps each
status by what it means for GET rates, not by its class:
| Provider answers | Probed with | Port error | Our API answers | Logged |
|---|---|---|---|---|
422 {"status":422,"message":"invalid currency: XYZ"} (400 means the same) |
base=EUR"es=XYZ, base=XYZ, base=EU, quotes=USD,XYZ |
UnknownCurrency(base, quote): the body names one code without saying which side, so the error names the pair |
400 | Information |
200 [] |
quotes= (empty), date=1900-01-01 |
UnknownCurrency(quote) |
400 | — |
404 {"status":404,"message":"not found"} |
ratez?… |
Rejected: rates is a collection route, so a 404 is a wrong BaseUrl or a retired API version, never "no such rate" |
500 | Error, as a misconfiguration |
| 401 / 403 | not served by Frankfurter (no key) | Rejected: our key or plan was refused, never "the caller must sign in" |
500 | Error |
| 408 / 429 / 5xx after the retries | — | Unavailable |
503 | Warning |
| any other status | — | Rejected: our request no longer matches the provider's API |
500 | Error |
The live smoke tests below are what notice when the provider changes again: one asks for a rate, one for a code it does not know.
The check appears in /health as exchange-rates, tagged external. It is not tagged live, so
/alive is unaffected by a provider outage.
tests/Trellis.ApiTests/ExchangeRateProviderTests.csdrives the real registration — options binding, typed client and resilience pipeline included — with only the socket replaced, and asserts that each third-party outcome comes back as aResult— the v2 request shape (rates?base="es=) is pinned on the way: each row of the status table (Frankfurter's own 422 body included, and a refusal of our configuration logged at Error), unreadable body, a body of the wrong shape, unknown currency, a lower-case quote, transport failure,success:false, a provider slower than the attempt timeout, an open circuit (a burst of failures opens the real breaker; the next call sends nothing), 429/503 retried to success. The caller's cancellation propagates asOperationCanceledException, unretried. The probe is pinned twice: Degraded-not-Unhealthy, and the 30 s cache (a moved clock, a listener that disappears).tests/Trellis.ApiTests/ExchangeRateResilienceTests.csboots the API's real graph —AddServiceDefaults()+AddInfrastructure+AddOutboundIntegrations— and asserts exactly oneResilienceHandlerin the client's chain, a hanging provider answeredUnavailablewithin the client's own budget (two calls, under the blanket 10 s), a fail-once-then-succeed retry that waits past an attempts-only budget, and the boot split: the API rejects a malformed section, starts without one, and a migration-shaped host starts with a malformed one.tests/Trellis.ApiTests/ExchangeRateLiveSmokeTests.csmakes two real calls to the default provider, a rate and an unknown code (UnknownCurrency) — opt-in,RUN_LIVE_SMOKE_TESTS=1.
The documentation of Trellis.Templates 0.2.0 · release notes