Skip to content

BACEN Service

The exchange service of exercise 8, ready to run: Python with FastAPI, backed by the PTAX of the Central Bank of Brazil (BCB, Banco Central do Brasil). PTAX is a public API, with no key and no sign-up, that quotes every major currency in Brazilian reals (BRL). Some free exchange-rate APIs block requests that come from cloud providers; PTAX is the default here because it does not need an account, but it is still a provider you do not own, and the exercise is about living with that.

Learning objectives

After this page you should be able to:

  • Read a small service that calls an external provider through a cache, a timeout and a stale fallback.
  • Explain how a cross rate (USD → EUR) comes out of quotes that are all in BRL.
  • Run the service with uv and read the X-Cache header of each answer.

How it works

The service asks PTAX for the latest quote of each currency in BRL (the last 7 days, since weekends and holidays have no quote), keeps it in memory for CACHE_SECONDS and divides one by the other. Only one request per currency refreshes the cache at a time; the others wait for it instead of all calling the BCB together. When PTAX fails and an old rate is in memory, the service answers with it and tries again only after RETRY_SECONDS.

sequenceDiagram
    participant G as gateway
    participant E as exchange
    participant P as PTAX (BCB)
    G->>E: GET /exchange/USD/EUR
    E->>P: CotacaoMoedaPeriodo USD, last 7 days
    P-->>E: buy/sell in BRL, every bulletin
    E->>P: CotacaoMoedaPeriodo EUR, last 7 days
    P-->>E: buy/sell in BRL, every bulletin
    E->>E: cross rate through BRL, keep both quotes
    E-->>G: 200 rate, X-Cache miss
    G->>E: GET /exchange/USD/EUR (within CACHE_SECONDS)
    E-->>G: 200 rate, X-Cache hit (PTAX not called)

PTAX only quotes against the real, so USD → EUR goes through BRL. With \(c\) (buy) and \(v\) (sell) the PTAX quotes in BRL:

\[ \text{buy} = \frac{c_\text{USD}}{v_\text{EUR}} \qquad\qquad \text{sell} = \frac{v_\text{USD}}{c_\text{EUR}} \]

buy is what the market pays for 1 USD, in euros (it buys your dollars and sells you euros); sell is what it charges. BRL itself counts as 1, so GET /exchange/USD/BRL is the PTAX quote of the dollar.

Piece What it protects
Cache of CACHE_SECONDS (300) per currency PTAX publishes a few bulletins a day: thousands of fans asking the rate cost a handful of calls
One refresh per currency at a time (asyncio.Lock) A cold or expired cache under load does not become a burst of identical calls to the provider
Timeout of PTAX_TIMEOUT (3 s) A slow provider cannot hold a request for longer than a fan would wait
Stale rate for RETRY_SECONDS (30) after a failure The provider is down or blocking us: an old rate beats an error, and we do not retry on every request
X-Cache: miss / hit / stale You can count, from outside, how often the provider was called and how often it failed

The project

In the BoxOffice repository the service lives in services/exchange/:

services/exchange/
├── pyproject.toml
├── uv.lock          # created by uv lock: commit it
├── main.py
└── Dockerfile       # your part (exercise 8, step 2)
1
2
3
4
5
6
7
8
9
[project]
name = "exchange"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "fastapi>=0.115",
    "httpx>=0.27",
    "uvicorn[standard]>=0.30",
]
"""Exchange service: currency rates from the Central Bank of Brazil (PTAX)."""

import asyncio
import os
import time
from collections import defaultdict
from contextlib import asynccontextmanager
from datetime import date, timedelta

import httpx
from fastapi import FastAPI, HTTPException, Response

PTAX_URL = os.getenv("PTAX_URL", "https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata")
PTAX_TIMEOUT = float(os.getenv("PTAX_TIMEOUT", "3"))  # seconds: never wait longer than the caller would
CACHE_SECONDS = float(os.getenv("CACHE_SECONDS", "300"))  # PTAX publishes a few bulletins a day
RETRY_SECONDS = float(os.getenv("RETRY_SECONDS", "30"))  # after a failed refresh, serve stale this long
# currency -> (valid until, quote, how a request served from it is labelled: "hit" or "stale")
_cache: dict[str, tuple[float, dict, str]] = {}
_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with httpx.AsyncClient(timeout=PTAX_TIMEOUT) as client:
        app.state.client = client
        yield


app = FastAPI(title="exchange", lifespan=lifespan)


async def brl_quote(currency: str) -> tuple[dict, str]:
    """Latest PTAX quote of a currency in BRL ({"buy", "sell", "date"}) and where it came from."""
    if currency == "BRL":
        return {"buy": 1.0, "sell": 1.0, "date": None}, "hit"
    cached = _cache.get(currency)
    if cached and time.monotonic() < cached[0]:
        return cached[1], cached[2]
    # one refresh per currency at a time: the requests that arrive meanwhile wait for it
    # instead of all calling PTAX together (a stampede on a provider we do not own)
    async with _locks[currency]:
        cached = _cache.get(currency)
        if cached and time.monotonic() < cached[0]:
            return cached[1], cached[2]
        return await _refresh(currency, cached)


async def _refresh(currency: str, cached: tuple[float, dict, str] | None) -> tuple[dict, str]:
    # a 7-day window always holds a business day (weekends and holidays have no PTAX)
    end = date.today()
    start = end - timedelta(days=7)
    url = (
        f"{PTAX_URL}/CotacaoMoedaPeriodo(moeda=@moeda,dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)"
        f"?@moeda='{currency}'&@dataInicial='{start:%m-%d-%Y}'&@dataFinalCotacao='{end:%m-%d-%Y}'"
        "&$format=json&$select=cotacaoCompra,cotacaoVenda,dataHoraCotacao"
    )
    try:
        response = await app.state.client.get(url)
        response.raise_for_status()
        rows = response.json()["value"]
    except (httpx.HTTPError, KeyError, ValueError) as e:
        if cached:  # BCB is slow, down or blocking us: an old rate beats an error
            _cache[currency] = (time.monotonic() + RETRY_SECONDS, cached[1], "stale")
            return cached[1], "stale"
        raise HTTPException(status_code=502, detail=f"PTAX unavailable: {e!r}") from e
    if not rows:
        raise HTTPException(status_code=404, detail=f"Unknown currency: {currency}")

    last = rows[-1]  # rows come in time order: the latest bulletin is the last one
    quote = {
        "buy": last["cotacaoCompra"],
        "sell": last["cotacaoVenda"],
        "date": last["dataHoraCotacao"][:19],
    }
    _cache[currency] = (time.monotonic() + CACHE_SECONDS, quote, "hit")
    return quote, "miss"


@app.get("/exchange/{source}/{target}")
async def exchange(source: str, target: str, response: Response):
    """Rate to convert 1 unit of `source` into `target` (e.g. USD → EUR)."""
    source, target = source.upper(), target.upper()
    src, src_from = await brl_quote(source)
    tgt, tgt_from = await brl_quote(target)
    # X-Cache: miss if PTAX was called, stale if an expired rate was served, hit otherwise
    froms = {src_from, tgt_from}
    response.headers["X-Cache"] = "miss" if "miss" in froms else "stale" if "stale" in froms else "hit"
    # PTAX quotes every currency in BRL, so the cross rate goes through BRL:
    # buy  = what the market pays for 1 `source`, in `target` (it buys source, sells target)
    # sell = what the market charges for 1 `source`, in `target` (it sells source, buys target)
    return {
        "from": source,
        "to": target,
        "sell": round(src["sell"] / tgt["buy"], 6),
        "buy": round(src["buy"] / tgt["sell"], 6),
        "date": src["date"] or tgt["date"],
    }


@app.get("/exchange/currencies")
async def currencies():
    """Currencies PTAX quotes (besides BRL)."""
    try:
        response = await app.state.client.get(f"{PTAX_URL}/Moedas?$format=json&$select=simbolo,nomeFormatado")
        response.raise_for_status()
    except httpx.HTTPError as e:
        raise HTTPException(status_code=502, detail=f"PTAX unavailable: {e!r}") from e
    return [{"symbol": m["simbolo"], "name": m["nomeFormatado"]} for m in response.json()["value"]]


@app.get("/health")
async def health():
    return {"status": "ok"}
Endpoint Returns
GET /exchange/{from}/{to} the rate from one currency to another, with the header X-Cache
GET /exchange/currencies the currencies PTAX quotes, besides BRL
GET /health {"status": "ok"}, for the container health check

The settings come from environment variables, so Compose or Kubernetes changes them without a new image:

Variable Default What it sets
PTAX_URL the BCB address base URL of the PTAX API
PTAX_TIMEOUT 3 seconds to wait for PTAX
CACHE_SECONDS 300 how long a rate is reused before asking PTAX again
RETRY_SECONDS 30 after a failed call, how long the old rate is served before trying again

Run it locally

In services/exchange/:

uv lock                                   # creates uv.lock from pyproject.toml
uv run uvicorn main:app --reload --port 8000

In another terminal, twice:

curl -i localhost:8000/exchange/USD/EUR

You should see x-cache: miss on the first answer and x-cache: hit on the second, with the same body:

{"from":"USD","to":"EUR","sell":0.906885,"buy":0.9066,"date":"2026-11-13 13:03:27"}

The date is the PTAX bulletin used: on a weekend or before 10 a.m. (Brasília) it is the last business day. An unknown currency (/exchange/XYZ/BRL) answers 404; PTAX unreachable with nothing in memory answers 502.

PTAX is not yours to load test

  • Quotes only exist on business days, between about 10 a.m. and 1 p.m. (Brasília); outside that window the service returns the last bulletin.
  • PTAX is a public service of the BCB, shared by every student of the class. Never run a load test with the cache off (CACHE_SECONDS=0): a k6 run at 100 requests/s would send the BCB 200 calls per second, and a provider that sees that from one address blocks it. With the cache on, the whole run of exercise 8 costs a handful of calls.