pattern/api/bff
- AbortSignal
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- node-postgres
- Docker
Um backend por tipo de cliente: numa chamada, consulta os serviços em paralelo e devolve só o que a tela usa.
pattern/api/bff
Cenário
Home do app com primeiro nome, saldo disponível, três últimos lançamentos e próxima fatura, vindos do core e de cartões.
Planta
Sequência5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Um backend por tipo de cliente consulta os serviços em paralelo e devolve só o que a tela usa
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Promise.allSettled com timeout por chamada
Falha vira null e entra em unavailable
Sem a conta, 502
Projeção cortada para o canal; saldo disponível vem do core
Trade-offs
O que se ganha, o que se paga
Vantagens
Uma chamada por tela, payload enxuto
Serviço fora deixa a tela parcial
Custos
Um serviço por canal
Regra pode migrar para o BFF
Código
pattern/api/bff
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec bff-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f bff-dbSaída: 200 com firstName Maria, availableCents 375000, os 3 lançamentos mais recentes, fatura de 250000 com vencimento 2026-10-10 e unavailable vazio.
Código
src/demo.ts// Demo: the mobile BFF builds the app home in one call — core banking and cards in parallel, projected to what the screen uses.
import { Elysia } from "elysia";
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.BFF_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/bff_db" });
const CORE_URL = Bun.env.BFF_CORE_URL ?? "http://localhost:4031";
const CARDS_URL = Bun.env.BFF_CARDS_URL ?? "http://localhost:4033";
const DOWNSTREAM_TIMEOUT_MS = 800;
type CoreAccount = { number: string; holderName: string; branch: string; availableCents: string };
type CoreStatementEntry = { description: string; amountCents: string; bookedAt: string };
type CardsCard = { lastDigits: string; brand: string; invoiceCents: string; invoiceDueOn: string };
// Downstream domain services: they know nothing about screens and expose their full records.
const core = new Elysia()
.get("/accounts/:number", async ({ params }) => (await pool.query<CoreAccount>(`SELECT number, holder_name AS "holderName", branch, balance_cents - blocked_cents AS "availableCents" FROM accounts WHERE number = $1`, [params.number])).rows[0])
.get("/accounts/:number/statement", async ({ params }) => (await pool.query<CoreStatementEntry>(`SELECT description, amount_cents AS "amountCents", booked_at AS "bookedAt" FROM statement_entries WHERE account_number = $1 ORDER BY booked_at DESC LIMIT 3`, [params.number])).rows)
.listen(new URL(CORE_URL).port);
const cards = new Elysia().get("/accounts/:number/cards", async ({ params }) => (await pool.query<CardsCard>(`SELECT last_digits AS "lastDigits", brand, invoice_cents AS "invoiceCents", to_char(invoice_due_on, 'YYYY-MM-DD') AS "invoiceDueOn" FROM cards WHERE account_number = $1`, [params.number])).rows).listen(new URL(CARDS_URL).port);
// Each call has its own timeout; a failed one becomes null and the screen comes out partial instead of failing.
const downstreamGet = async <T>(url: string): Promise<T> => {
const response = await fetch(url, { signal: AbortSignal.timeout(DOWNSTREAM_TIMEOUT_MS) });
if (!response.ok) throw new Error(`downstream answered ${response.status}`);
return (await response.json()) as T;
};
const settled = <T>(result: PromiseSettledResult<T>) => (result.status === "fulfilled" ? result.value : null);
// The mobile BFF: first name, what can be spent, three latest entries and the next invoice — nothing else.
const bffMobile = new Elysia().get("/home/:accountNumber", async ({ params, status }) => {
const [accountResult, statementResult, cardsResult] = await Promise.allSettled([
downstreamGet<CoreAccount>(`${CORE_URL}/accounts/${params.accountNumber}`),
downstreamGet<CoreStatementEntry[]>(`${CORE_URL}/accounts/${params.accountNumber}/statement`),
downstreamGet<CardsCard[]>(`${CARDS_URL}/accounts/${params.accountNumber}/cards`),
]);
const [account, statement, cardList] = [settled(accountResult), settled(statementResult), settled(cardsResult)];
if (!account) return status(502, { error: "account-unavailable" });
return {
firstName: account.holderName.split(" ")[0],
availableCents: Number(account.availableCents),
recent: (statement ?? []).map((entry) => ({ description: entry.description, amountCents: Number(entry.amountCents) })),
invoice: cardList?.[0] ? { amountCents: Number(cardList[0].invoiceCents), dueOn: cardList[0].invoiceDueOn } : null,
unavailable: [statement ? null : "statement", cardList ? null : "cards"].filter(Boolean),
};
});
await pool.query("TRUNCATE cards, statement_entries, accounts");
await pool.query("INSERT INTO accounts (number, holder_name, branch, balance_cents, blocked_cents) VALUES ('0042-1', 'Maria Silva Souza', '0042', 425000, 50000)");
await pool.query("INSERT INTO statement_entries (account_number, description, amount_cents, booked_at) VALUES ('0042-1', 'PIX recebido', 50000, '2026-09-28'), ('0042-1', 'Supermercado', -12050, '2026-09-27'), ('0042-1', 'Salario', 500000, '2026-09-26'), ('0042-1', 'Aluguel', -180000, '2026-09-25')");
await pool.query("INSERT INTO cards (account_number, last_digits, brand, invoice_cents, invoice_due_on) VALUES ('0042-1', '4521', 'Visa', 250000, '2026-10-10')");
const response = await bffMobile.handle(new Request("http://localhost/home/0042-1"));
const text = await response.text();
console.log(` [APP] GET /home/0042-1 → ${response.status} (${text.length} bytes) ${text}`);
await Promise.all([core.stop(true), cards.stop(true)]);
await pool.end();
Nível
intermediário
6/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Backend for Frontend?
BFFs atrás do gateway. Abrir API Gateway
Seu progresso
0/157 estudados
Fica salvo só neste navegador.