How to Lock an Exchange Rate at Checkout: Quote Expiry Done Right

6 min read

How to Lock an Exchange Rate at Checkout: Quote Expiry Done Right

To lock an exchange rate at checkout, turn the rate into a quote: a stored record with the rate, the amounts, the time the rate was observed and an expiry time. The customer pays the amount on the quote, not a freshly calculated one. When the quote expires, you create a new one and show the customer the new price.

That is the whole idea, but the details decide whether you get angry support tickets or clean books. This article covers what a quote should contain, how long it should live, what to do when the rate behind it is stale, and a working Python example built on live rates.

Why you need to lock an exchange rate

Exchange rates move constantly. A checkout page is not instant: the customer reads the price, picks a payment method, maybe goes to find their card. If you recalculate the converted amount on every request, three things can go wrong:

  • The price on the confirmation button differs from the amount charged by a few cents.
  • The customer reloads the page and sees a different total than a minute ago.
  • Your records cannot prove which rate produced the amount, so refunds and disputes turn into guesswork.

Locking the rate fixes all three. The customer sees one number, pays that number, and you can explain it later. The lock is temporary on purpose: you do not want to honor a rate from yesterday, and a short expiry keeps your exposure to market movement small. How you price that exposure (a buffer in the rate, a fee, nothing at all) is a business decision, and this article does not make it for you.

What a quote record should contain

Store everything needed to reproduce the amount without calling any API again:

FieldExampleWhy
quote_idq_8f3a...Unique reference passed to the payment step
price_amount, price_currency49.00, EURThe original catalog price
pay_currencyUSDWhat the customer is charged in
rate"1.0842"Stored as a string or decimal, never a float
rate_as_of2026-01-02T10:00:00ZWhen the market observation was made
rate_typedirect or derivedUseful when debugging odd pairs
pay_amount53.13The rounded amount the customer will be charged
created_at, expires_attimestampsDrives the expiry logic

Note the difference between rate_as_of and created_at. The first is when the rate was observed, the second is when you made the quote. Keeping both lets you see how old the underlying data was when the customer agreed to it.

Keep the unrounded intermediate result out of the record if you like, but keep the rounding rule. See Currency Conversion Rounding: How to Convert Money Without Floating-Point Errors for how to round money correctly, including currencies with zero or three decimal places.

How long should a quote last?

There is no universal answer, but the trade-off is simple. A longer lifetime is friendlier to slow customers and bank redirects (3-D Secure, wallet apps). A shorter lifetime limits how far the market can drift away from the rate you promised.

Common patterns:

  • 10 to 30 minutes for a normal card checkout. Long enough to finish a form, short enough to be safe for major fiat pairs.
  • Shorter, such as 1 to 5 minutes, for volatile assets like crypto, where prices refresh every few seconds.
  • Extend on activity only if you want to, and only by creating a new quote, never by silently editing the old one.

Whatever you choose, show a visible countdown or a clear message such as "This price is held until 14:32." Customers accept a re-quote far better when they were told it might happen.

Check freshness before you create the quote

A quote is only as good as the rate under it. GetRatesAPI returns an as_of timestamp and a status on every rate: fresh or stale. Crypto becomes stale after 1 minute, fiat after 5 minutes. Stale rates are flagged, not withheld, so your code decides what to do with them.

For a quote, a sensible policy is:

  1. If status is fresh, create the quote.
  2. If status is stale, retry once after a short pause. If it is still stale, either refuse to quote in that currency or fall back to charging in the base currency.
  3. Never extend an existing quote's expiry because the new rate looks stale.

For derived pairs (no market quotes them directly), the response says "type": "derived" and as_of is the oldest of its inputs, so the freshness check stays honest for pairs like NOK to THB. The details are in Cross Rates Explained.

A working example in Python

This example creates a quote for a 49.00 EUR item charged in USD. It uses Decimal throughout and reads the key from an environment variable. The response format is described in the current rate documentation.

import os
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal, ROUND_HALF_UP

import requests

API = "https://api.getratesapi.com"
HEADERS = {"Authorization": f"ApiKey {os.environ['GETRATESAPI_KEY']}"}
QUOTE_TTL = timedelta(minutes=15)
MINOR_UNITS = {"USD": 2, "EUR": 2, "GBP": 2, "JPY": 0}


class QuoteError(Exception):
    pass


@dataclass(frozen=True)
class Quote:
    quote_id: str
    price_amount: Decimal
    price_currency: str
    pay_currency: str
    rate: Decimal
    rate_as_of: datetime
    rate_type: str
    pay_amount: Decimal
    created_at: datetime
    expires_at: datetime

    def is_valid(self, now=None):
        return (now or datetime.now(timezone.utc)) < self.expires_at


def fetch_rate(base, quote):
    resp = requests.get(f"{API}/v1/rates/{base}/{quote}", headers=HEADERS, timeout=5)
    if resp.status_code != 200:
        code = resp.json().get("code", "unknown")
        raise QuoteError(f"rate lookup failed: {code}")
    return resp.json()


def create_quote(price, price_currency, pay_currency):
    data = fetch_rate(price_currency, pay_currency)
    if data["status"] != "fresh":
        raise QuoteError("rate is stale, not issuing a quote")

    rate = Decimal(data["rate"])
    places = Decimal(1).scaleb(-MINOR_UNITS[pay_currency])
    pay_amount = (Decimal(price) * rate).quantize(places, rounding=ROUND_HALF_UP)

    now = datetime.now(timezone.utc)
    return Quote(
        quote_id=f"q_{uuid.uuid4().hex}",
        price_amount=Decimal(price),
        price_currency=price_currency,
        pay_currency=pay_currency,
        rate=rate,
        rate_as_of=datetime.fromisoformat(data["as_of"].replace("Z", "+00:00")),
        rate_type=data["type"],
        pay_amount=pay_amount,
        created_at=now,
        expires_at=now + QUOTE_TTL,
    )


quote = create_quote("49.00", "EUR", "USD")
print(quote.pay_amount, quote.expires_at)

With the example response {"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}, 49.00 EUR becomes 53.1258, which rounds to 53.13 USD. The rate is a string in the JSON and goes straight into Decimal, so no float ever touches the money.

Persist the Quote in your database and pass only the quote_id to the payment step.

The payment step: honor, or re-quote

When the customer clicks Pay, load the quote by ID and branch:

def start_payment(quote):
    if not quote.is_valid():
        new_quote = create_quote(
            quote.price_amount, quote.price_currency, quote.pay_currency
        )
        return {"action": "reprice", "quote": new_quote}
    return {"action": "charge", "amount": quote.pay_amount, "currency": quote.pay_currency}

Two rules keep this robust:

  • Do not call the rate API at payment time for a valid quote. The amount is already decided. This also saves request units and keeps payments working if your rate lookup has a hiccup.
  • A re-quote needs explicit consent. Return the new price to the UI and make the customer confirm. Never charge a new amount the customer has not seen.

Also make payment creation idempotent on quote_id, so a double click cannot charge the same quote twice.

Handling failures when creating a quote

Quote creation is the one place a live call is on the critical path, so handle errors deliberately. Match on the code field only. unsupported_pair or invalid_asset_symbol mean you should not offer that currency. rate_limit_exceeded includes retry_after_seconds, and temporarily_unavailable is worth a short retry. If all fails, fall back to charging in your base currency instead of guessing. The full list is in Exchange Rate API Error Handling, and rate limit handling covers retries.

If many shoppers quote the same pair at once, you do not need one API call per cart. A short shared cache of a few seconds is fine as long as you apply the freshness check to the cached as_of, not to the time you cached it. How to Cache Exchange Rates Without Showing Stale Prices explains how.

Checklist before you ship

  • The quote stores rate, as_of, amounts, rounding rule and expiry.
  • Amounts are Decimal or integer minor units, never floats.
  • Stale rates never produce a quote.
  • Expired quotes are re-issued with visible customer consent.
  • The payment step uses the stored amount and is idempotent.
  • Refunds reference the original quote, not today's rate.

For the broader catalog-pricing picture, read Multi-Currency Pricing for E-commerce.

Try it with live rates

GetRatesAPI gives you exact decimal rates with as_of and status on every response, which is what a quote needs. Create a free key at the sign-up page (no credit card), try the call in the dashboard playground, and read the authentication guide to wire the key into your backend. If you outgrow the free tier, compare plans on the pricing page.

All articles →
Lock Exchange Rate at Checkout: Quote Expiry Guide — GetRatesAPI