How to quote a currency conversion, lock the rate for 30 seconds and settle it exactly once: rates stored as NUMERIC, a margin applied in the database, quotes that expire, idempotent acceptance and a clean-up job on Postgres.

A platform that lets customers hold or pay out in several currencies has to promise an exact amount, so a quote must store the rate and the converted amount, expire quickly and be accepted only once.
The failures are small and expensive: a stale rate from a feed that stopped, a float that rounds one cent the wrong way, or a retried request that converts the same quote twice.
The minor unit for each currency comes from ISO 4217, where USD and EUR have an exponent of 2 and JPY has 0. Postgres documents NUMERIC as exact for decimal arithmetic, which is why the multiplication happens in SQL rather than in application floats.
The quote takes the stored mid rate, applies the margin in basis points and rounds once, at the end, into the target currency's minor unit. converted = round(source_minor * rate * (1 - margin_bps / 10000) * 10^(target_exponent - source_exponent)) keeps the whole calculation in NUMERIC, so the same inputs give the same result in the quote, in the ledger entry later and in a support investigation a year from now.
The quote stores everything that produced the number: the mid rate, the margin, both amounts and the expiry. A later change to the margin never needs a backfill, because each quote explains itself.
Acceptance is the half that moves money, and a single statement does the work: it updates the quote from open to accepted only when it has not expired, and inserts the conversion from the row it just updated. If two requests race, only one of them updates a row, and the other finds the conversion by idempotency key and returns it unchanged. The ledger posting for the conversion then happens from that conversion row, as described in building a double-entry ledger.
Encore is a backend framework with built-in infrastructure, so the quote and accept endpoints, the Postgres database and the clean-up schedule are declared in one service and deployed to your own AWS or GCP account. Per the AWS infrastructure docs, that means RDS for the quotes and conversions, which keeps the data in an account you control. Pave Bank built a bank in 9 months with Encore.

Run in your terminal to get started locally.
The quotes folder also needs an encore.service.ts that exports new Service("quotes"). The service has four parts: a private endpoint your rate feed calls, a quote endpoint, an accept endpoint that takes an Idempotency-Key header, and a cron job that marks quotes as expired:
// quotes/quotes.ts
import { api, APIError, Header } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { CronJob } from "encore.dev/cron";
const db = new SQLDatabase("quotes", { migrations: "./migrations" });
// Called by your rate feed. The rate is a decimal string, never a float.
export const setRate = api(
{ expose: false },
async ({ base, quote, rate }: { base: string; quote: string; rate: string }): Promise<void> => {
await db.exec`
INSERT INTO rates (base, quote, rate, fetched_at)
VALUES (${base}, ${quote}, ${rate}::numeric, now())
ON CONFLICT (base, quote) DO UPDATE SET rate = EXCLUDED.rate, fetched_at = EXCLUDED.fetched_at`;
},
);
interface QuoteResponse {
id: string;
targetMinor: string;
rate: string;
expiresAt: string;
}
export const createQuote = api(
{ expose: true, method: "POST", path: "/quotes" },
async (req: { base: string; quote: string; sourceMinor: number; marginBps: number }): Promise<QuoteResponse> => {
if (!Number.isInteger(req.sourceMinor) || req.sourceMinor <= 0) {
throw APIError.invalidArgument("sourceMinor must be a positive integer");
}
if (!Number.isInteger(req.marginBps) || req.marginBps < 0 || req.marginBps > 1000) {
throw APIError.invalidArgument("marginBps must be between 0 and 1000");
}
// Rounds once, at the end, and only prices rates fetched in the last 60 seconds.
const row = await db.queryRow<{ id: string; target_minor: string; rate: string; expires_at: Date }>`
INSERT INTO quotes (base, quote, source_minor, target_minor, rate, margin_bps, expires_at)
SELECT ${req.base}::text, ${req.quote}::text, ${req.sourceMinor}::bigint,
round(${req.sourceMinor}::numeric * r.rate * (1 - ${req.marginBps}::numeric / 10000)
* power(10::numeric, cq.exponent - cb.exponent))::bigint,
r.rate, ${req.marginBps}::int, now() + interval '30 seconds'
FROM rates r
JOIN currencies cb ON cb.code = r.base
JOIN currencies cq ON cq.code = r.quote
WHERE r.base = ${req.base}::text AND r.quote = ${req.quote}::text
AND r.fetched_at > now() - interval '60 seconds'
RETURNING id, target_minor, rate, expires_at`;
if (!row) throw APIError.unavailable("no fresh rate for this currency pair");
return { id: row.id, targetMinor: row.target_minor, rate: row.rate, expiresAt: row.expires_at.toISOString() };
},
);
interface ConversionResponse {
conversionId: string;
quoteId: string;
}
export const acceptQuote = api(
{ expose: true, method: "POST", path: "/quotes/:id/accept" },
async (req: { id: string; idempotencyKey: Header<"Idempotency-Key"> }): Promise<ConversionResponse> => {
if (!req.idempotencyKey) throw APIError.invalidArgument("Idempotency-Key header is required");
const existing = () => db.queryRow<{ id: string; quote_id: string }>`
SELECT id, quote_id FROM conversions WHERE idempotency_key = ${req.idempotencyKey}`;
let done = await existing();
if (!done) {
// Only an open, unexpired quote can be accepted, and only once.
done = await db.queryRow<{ id: string; quote_id: string }>`
WITH accepted AS (
UPDATE quotes SET status = 'accepted'
WHERE id = ${req.id}::uuid AND status = 'open' AND expires_at > now()
RETURNING id
)
INSERT INTO conversions (quote_id, idempotency_key)
SELECT id, ${req.idempotencyKey} FROM accepted
RETURNING id, quote_id`;
// A concurrent request with the same key may have won the race.
done = done ?? (await existing());
}
if (!done) throw APIError.failedPrecondition("quote is expired or already used");
if (done.quote_id !== req.id) throw APIError.invalidArgument("Idempotency-Key was used for a different quote");
return { conversionId: done.id, quoteId: done.quote_id };
},
);
// Marks quotes that were never accepted. Acceptance already checks expires_at itself.
export const expireQuotes = api(
{ expose: false },
async (): Promise<{ expired: number }> => {
const row = await db.queryRow<{ n: number }>`
WITH gone AS (
UPDATE quotes SET status = 'expired'
WHERE status = 'open' AND expires_at <= now() RETURNING 1
)
SELECT count(*)::int AS n FROM gone`;
return { expired: row?.n ?? 0 };
},
);
const _ = new CronJob("expire-quotes", {
title: "Mark unaccepted quotes as expired",
every: "5m",
endpoint: expireQuotes,
});
-- quotes/migrations/1_create_fx.up.sql
CREATE TABLE currencies (
code TEXT PRIMARY KEY,
exponent INTEGER NOT NULL CHECK (exponent BETWEEN 0 AND 4)
);
INSERT INTO currencies (code, exponent) VALUES ('EUR', 2), ('USD', 2), ('GBP', 2), ('JPY', 0);
CREATE TABLE rates (
base TEXT NOT NULL REFERENCES currencies (code),
quote TEXT NOT NULL REFERENCES currencies (code),
rate NUMERIC(20, 10) NOT NULL CHECK (rate > 0),
fetched_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (base, quote)
);
CREATE TABLE quotes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
base TEXT NOT NULL,
quote TEXT NOT NULL,
source_minor BIGINT NOT NULL CHECK (source_minor > 0),
target_minor BIGINT NOT NULL CHECK (target_minor >= 0),
rate NUMERIC(20, 10) NOT NULL,
margin_bps INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'accepted', 'expired')),
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE conversions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
quote_id UUID NOT NULL UNIQUE REFERENCES quotes (id),
idempotency_key TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
encore run starts Postgres locally and applies the migration, so quotes, rate staleness and double acceptance can be tried on a laptop with curl. Cron jobs do not run locally, and expireQuotes is called from the local development dashboard. The database docs cover migrations and the cron docs cover the schedule, and deploying through Connect your cloud account creates the database in your own account. An AI coding agent adding a second currency pair or a new margin rule changes the migration and the endpoint in one diff and runs both locally before review.
Run the same accept request twice with one key and confirm that the second returns the first conversion, then two different keys against one quote and confirm that exactly one succeeds. Let a quote pass 30 seconds and confirm acceptance fails with a failed precondition, stop the rate feed for a minute and confirm quotes are refused, and compare target_minor for JPY and USD pairs against a calculation done by hand.
A rate lock is a quote that fixes the exchange rate for a short window, typically 10 to 60 seconds, so the customer sees the exact amount they will receive and the platform commits to it. The backend stores the rate, the amounts and an expiry time with the quote, and rejects acceptance after it.
No. Store rates as NUMERIC with enough decimal places, such as NUMERIC(20,10), and amounts as integers in the currency's minor unit. Floats cannot represent most decimal rates exactly, so a converted amount can be off by a unit after rounding.
Accept the quote with a single conditional UPDATE that only matches status open and an unexpired quote, and insert the conversion in the same statement with a unique constraint on the quote and on the idempotency key. A retry with the same key then returns the stored conversion instead of converting twice.
With Encore you declare the Postgres database and the clean-up cron job in the service code, and the endpoints that quote and accept are ordinary typed APIs. Deploying provisions RDS in your own AWS account, or Cloud SQL on GCP, and encore run starts Postgres locally.
Deploy to your cloud on AWS and Google Cloud without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.