Cross-Border Remittance Cost Comparison Engine

Medium · System Design · Staff AI-Native Engineer · Technical Screen

Prompt

International money-transfer services display side-by-side competitor price breakdowns across specific currency corridors (such as USD -> MXN or GBP -> KES) for both consumer apps and internal pricing analysts. Because remittance services charge through a mix of explicit transfer fees and implicit exchange-rate spreads against the wholesale mid-market rate, design a modular prototype and production-ready architecture that collects quotes from partner feeds, official APIs, and public web calculators, computes normalized customer cost, and serves reliable comparisons.

Your design should meet the following functional and operational specifications: - Normalized cost formula: Given (source_currency, target_currency, send_amount, delivery_method), calculate Total Cost = Upfront Fee + (Send Amount * (1 - Provider Rate / Mid-Market Rate)), surfacing legal disclaimers and tiered or promotional conditions transparently without hiding terms. - Audit lineage & partial availability: Retain the source adapter ID, fetch timestamp, expiry TTL, and a pointer to the archived raw payload on every quote. When individual sources time out, hit rate limits, or fail validation, return partial comparisons that clearly distinguish live, aged/stale, and unavailable providers rather than failing the whole query. - Plug-in extensibility: Onboarding a new competitor source or backup parser should require minimal localized code or configuration. - Scale, freshness & latency targets: Support 100 active corridors across 20 providers at 3,000 peak queries/minute, backed by wholesale mid-market reference feeds refreshing every 30 seconds. Keep P95 latency under 800 ms on pre-warmed/cached routes (< 3 s ceiling for live on-demand calls) and enforce a 5-minute maximum quote age during open FX market hours.

Scope & Expectations

  • Data & provenance schemas: Define storage layouts for standardized quotes, adapter metadata, content-addressed raw payloads, and auditable comparison responses.
  • Ingestion, worker isolation & caching: Detail the decoupled mid-market benchmark pipeline, unified adapter contract across APIs/partners/scrapers, isolated worker pools, and multi-tier cache warming.
  • Client staleness & failure states: Specify clear response semantics distinguishing live/fresh quotes, aged fallback quotes, provider outages, and unsupported corridors.
  • Production resilience & parser safety: Cover inbound/outbound rate-limit defenses, per-provider circuit breaking, observability, and automated sanity checks that quarantine broken web scrapers.

Step-by-step walkthrough

  1. Clarify requirements, money math, and prototype scope

    When someone sends money internationally—say 1,000.00 USD from the United States to MXN (Mexican Pesos) in a remittance corridor (a specific source-to-target currency route)—providers charge customers in two places: a visible upfront fee (such as $4.99) and a hidden FX spread (exchange-rate markup) baked into a worse exchange rate than the interbank mid-market rate (the wholesale midpoint between bank buy and sell rates, with zero retail markup). Our engine must expose both clearly, stay fast even when external providers are slow or broken, and preserve an audit trail for every number shown.

    Functional requirements - Accept (source_currency, target_currency, send_amount, delivery_method)—for example (USD, MXN, 1000.00, BANK_DEPOSIT)—and return normalized comparisons across competing providers. - Compute each provider's upfront fee, exchange rate, recipient payout, hidden FX markup cost, and total customer cost. - Retain full provenance (the complete audit lineage recording which adapter fetched a quote, when it was retrieved, when its TTL or Time To Live expires, and a pointer to the exact raw response bytes). - Return partial comparisons gracefully whenever a provider times out, rate-limits us, or fails validation, explicitly labeling stale or unavailable rows rather than failing the request. - Support adding a new provider or fallback parser via a small plug-in class or declarative config.

    Non-functional requirements - Latency: Cached/pre-warmed corridors under 800 ms at p95; live on-demand fetches strictly bounded under 3 seconds. - Freshness: Quotes marked current cannot be older than 5 minutes during active FX market hours; mid-market reference rates update every 30 seconds. - Compliance & transparency: Never hide provider legal disclaimers, and never blend promotional "first transfer only" teaser rates with standard recurring pricing.

    Key scoping assumptions - Amount-tiered pricing: Providers vary fees and rates by send-amount brackets (for example $1-$500, $500-$1,000, $1,000-$3,000), so our cache keys include the amount bracket (band). - Fee mode: Some providers add the fee on top ($1,000 + $4.99 = $1,004.99 charged), while others deduct it from the send amount ($1,000 charged, $996.00 converted after a $4.00 fee). We model fee_mode = ADDED | DEDUCTED explicitly. - Prototype vs. production: A day-one prototype runs as a single modular Python/Go service backed by Redis, PostgreSQL, and S3-compatible object storage across 5 corridors and 3 adapters (one REST API, one partner feed, one headless scraper), using the exact interfaces below so scaling to 100 corridors and 20 providers only splits worker pools without rewriting contracts.

  2. Estimate traffic, provider fetch load, and storage

    User read traffic
      Peak comparison volume         3,000 requests/min = 50 requests/s
      Providers per corridor         ~12 of the 20 providers support any given corridor
      Naive live fan-out at peak     50 req/s x 12 providers = 600 outbound calls/s  -> trips external rate limits!
    
    Pre-warmed cache sizing
      Corridor x delivery methods    100 corridors x ~2 methods (Bank, Cash/Wallet) = 200 routes
      Provider-route combinations    200 routes x 12 providers = 2,400 pairs
      Amount brackets (bands)        ~4 fee tiers per pair -> ~9,600 pre-warmed cache keys
      Scheduled refresh cadence      Every 4 min (240 s) -> 1-min safety buffer inside the 5-min freshness limit
      Steady outbound fetch rate     9,600 keys / 240 s = 40 fetches/s total (~2 fetches/s per provider!)
      Scraper share (assume 30%)     ~12 scrapes/s; at ~4 s per headless browser render -> ~48 concurrent browsers
      Redis memory (both tiers)      9,600 keys x ~2 KB/quote x 2 tiers ≈ 40 MB total (tiny!)
    
    Mid-market benchmark stream
      100 currency pairs x 1 tick / 30 s x 3 feeds = 10 ticks/s -> < 50 MB in RAM for 24 hours of history
    
    Audit & raw payload storage
      Daily provider fetches         40 fetches/s x 86,400 s ≈ 3.5M fetches/day
      Raw payload bytes (compressed) 70% JSON (~4 KB) + 30% HTML/DOM (~40 KB) ≈ 52 GB/day (~4.7 TB for 90 days in S3)
      Normalized quote rows          3.5M rows/day x ~600 B ≈ 2.1 GB/day in PostgreSQL
    

    Two architectural conclusions jump right out of these numbers: 1. Our internal read load is tiny (50 req/s, 40 MB cache), whereas external provider limits are tight. Pre-warming ~9,600 keys every 4 minutes holds outbound traffic at a flat ~2 calls/s per provider—15x lower than fetching per user request—and keeps cached responses well under 50 ms (comfortably inside the 800 ms p95 budget). 2. Raw HTML/JSON payloads dominate storage (~52 GB/day), so raw bytes belong in cheap content-addressed object storage (S3/GCS) while PostgreSQL stores compact metadata and hashes.

  3. Design the comparison and provenance APIs

    GET /v1/comparisons?source=USD&target=MXN&amount=1000.00&delivery_method=BANK_DEPOSIT
                       &pricing_tier=STANDARD&max_wait_ms=800
    -> 200 OK
    {
      "comparison_id": "cmp_4d7a19",
      "as_of": "2026-12-01T16:10:05Z",
      "complete": false,
      "benchmark": {
        "mid_rate": "20.0000",
        "tick_at": "2026-12-01T16:10:00Z",
        "status": "LIVE",
        "feeds_agreed": 3
      },
      "results": [
        {
          "provider_id": "alpha_pay",
          "status": "FRESH",
          "age_s": 62,
          "fee": { "amount": "4.99", "currency": "USD", "mode": "ADDED" },
          "provider_rate": "19.8500",
          "customer_pays": "1004.99",
          "recipient_gets": { "amount": "19850.00", "currency": "MXN" },
          "fx_markup_pct": "0.75",
          "fx_markup_cost": "7.50",
          "total_cost": "12.49",
          "pricing_tier": "STANDARD",
          "disclaimers": ["Rate locked for 30 minutes upon funding."],
          "quote_id": "q_51842",
          "retrieved_at": "2026-12-01T16:09:03Z",
          "fresh_until": "2026-12-01T16:14:03Z"
        },
        {
          "provider_id": "delta_wire",
          "status": "STALE",
          "age_s": 960,
          "reason": "CIRCUIT_OPEN",
          "...": "...last valid quote fields shown greyed out, excluded from #1 rank..."
        },
        {
          "provider_id": "epsilon_cash",
          "status": "UNAVAILABLE",
          "reason": "TIMEOUT",
          "last_good_at": "2026-12-01T15:18:40Z"
        }
      ]
    }
    
    GET  /v1/quotes/{quote_id}         -> Full provenance: adapter_id, parser_version, raw S3 URI, retrieved_mid_rate
    POST /v1/comparisons:refresh       -> Authenticated internal pricing tool trigger (allows max_wait_ms up to 3000)
    GET  /v1/providers/health          -> Per-adapter circuit breaker state, error rate, p95 latency, freshness SLA %
    

    Key API design choices: - Partial success returns HTTP 200 with complete: false: One hung competitor never causes a 500 page error; each row's status and reason tell the UI exactly how to render it. - Exact decimal strings, never IEEE-754 floats: All currency amounts and FX rates serialize as strings ("1004.99") backed by fixed-point Decimal math so binary float rounding (0.1 + 0.2 = 0.30000000000000004) never touches money. - Caller-controlled max_wait_ms: Public web traffic caps wait time at <= 800 ms, while internal pricing analysts can pass max_wait_ms=2800 to wait up to the 3-second ceiling for live uncached fetches.

  4. Model quotes, raw payloads, and audit schemas

    adapters           adapter_id PK, provider_id, source_type (API | PARTNER | SCRAPER),
                       priority (1 = primary API, 2 = partner, 3 = fallback scraper),
                       parser_version, config_json, timeout_ms, rate_limit_per_s, enabled
    
    corridor_coverage  provider_id, source_ccy, target_ccy, delivery_method,
                       band_edges ([0, 500, 1000, 3000, 10000]), active_market_calendar
    
    benchmark_ticks    pair (USD_MXN), tick_at, mid_rate, feeds_used, max_divergence_pct, status
    
    raw_payloads       payload_sha256 PK, content_type, byte_size, s3_uri, first_seen_at
                       (content-addressed object store pointer; deduplicates identical JSON/HTML bytes)
    
    fetch_attempts     fetch_id PK, adapter_id, query_params, fetched_at, http_status,
                       status (OK | TIMEOUT | RATE_LIMITED | BLOCKED), latency_ms, payload_sha256
    
    quotes             quote_id PK, provider_id, adapter_id, fetch_id, parser_version,
                       source_ccy, target_ccy, delivery_method, band_lo, band_hi, probe_amount,
                       fee_amount, fee_currency, fee_mode (ADDED | DEDUCTED),
                       provider_rate, receive_amount, pricing_tier (STANDARD | FIRST_TRANSFER_PROMO),
                       promo_conditions_json, disclaimers_json,
                       retrieved_at, provider_expires_at, fresh_until, retrieved_mid_rate,
                       validation_status (ACCEPTED | QUARANTINED), validation_notes
    
    comparison_audit   comparison_id PK, served_at, query_params, comparison_mid_rate, benchmark_tick_at,
                       rows_served_json ([{provider_id, quote_id, status, total_cost}])
    

    Why we separate fetch_attempts, raw_payloads, and immutable quotes: - Write raw bytes before parsing: If a competitor changes a CSS class or JSON field and our parser extracts the wrong fee, the raw response is already safely archived in S3 under payload_sha256, so we can fix parser_version and re-parse historical payloads without losing evidence. - Content-addressed storage + per-fetch timestamps: If an API returns byte-identical JSON 4 minutes later, raw_payloads stores the bytes once via payload_sha256, while fetch_attempts and quotes still record a fresh retrieved_at proving the price was re-verified just now. - Complete compliance traceability: If a regulator or competitor challenges what our comparison table displayed at 16:10:05Z, comparison_audit -> quote_id -> fetch_id -> s3_uri reproduces the exact raw payload, parser version, and mid-market tick in one join.

  5. Sketch the decoupled end-to-end architecture

    To prevent slow or failing competitors from ever stalling reference-rate updates, mid-market benchmark ingestion runs on an independent pipeline decoupled from provider quote fetching, ensuring every provider quote is normalized against one authoritative baseline:

      Public Web / App              Internal Pricing Tools
              \                            /
               v                          v
           +----------------------------------+
           | API Gateway (auth, rate limits)  |
           +----------------+-----------------+
                            |
                            v
           +------------------------------------------------------------------+
           | Comparison Service (stateless instances)                         |
           |  1. Read authoritative mid_rate from local RAM ring buffer       |
           |  2. Single Redis MGET across fresh cache keys for corridor+band  |
           |  3. On miss: check circuit breaker -> live-fetch broker / stale  |
           |  4. Normalize Total Cost in Decimal; emit async comparison_audit |
           +------+-----------------------+-----------------------+-----------+
                  |                       |                       |
                  v                       v                       v
      +----------------------+  +-------------------+   +-----------------------------+
      | Benchmark Ring Buf   |  | Two-Tier Redis    |   | Live-Fetch Broker           |
      | (in-memory, 30s push)|  | - fresh (<=5 min) |   | Single-flight lock,         |
      +-----------+----------+  | - stale (24h TTL) |   | per-adapter circuit breaker |
                  ^             +---------+---------+   +--------------+--------------+
                  |                       ^                            |
      +-----------+----------+            | accepted quotes            | on-demand miss
      | Benchmark Ingester   |  +---------+---------+                  v
      | Polls 3 FX feeds/30s |  | Validator & Store |<--- Parser <--- Raw Payload S3
      | Computes median rate |  | (Postgres + Redis)|                  ^
      +----------------------+  +-------------------+                  |
                                                                       |
      +----------------------+     due keys (4-min cycle)    +---------+--------------+
      | Pre-Warm Scheduler   |------------------------------>| Isolated Worker Pools  |
      | (hot corridors first)|                               | - Async HTTP API pool  |
      +----------------------+                               | - Partner batch loader |
                                                             | - Sandboxed Browser pool|
                                                             +------------------------+
    
  6. Deep dive 1: Normalizing upfront fees and FX markups accurately

    A beginner-friendly way to understand cross-border transfer cost is a single universal truth: Total Cost is what leaves the sender's wallet minus the true mid-market value of what arrives in the recipient's account:

    Universal formula:    Total Cost = Customer Pays - (Recipient Gets / Mid-Market Rate)
    
    Case 1: Fee ADDED on top of Send Amount S (Customer Pays = S + F, Recipient Gets = S * r)
      Total Cost = (S + F) - (S * r / mid)
                 = F + S * (1 - r / mid)              <-- matches the prompt's formula!
    
    Case 2: Fee DEDUCTED from Send Amount S (Customer Pays = S, converted principal = S - F, Recipient Gets = (S - F) * r)
      Total Cost = S - ((S - F) * r / mid)
                 = F + (S - F) * (1 - r / mid)        <-- FX markup applies to the (S - F) actually converted!
    

    Walk through a concrete $1,000.00 USD -> MXN comparison when mid = 20.0000 MXN/USD to see why showing only upfront fees misleads customers—and why Case 2 keeps every line item adding up to the exact cent:

    Provider    Fee & mode        Provider rate  Customer pays  Recipient gets   Upfront fee  FX markup cost       Total cost
    ----------  ----------------  -------------  -------------  ---------------  -----------  -------------------  ----------
    alpha_pay   $4.99 ADDED       19.8500        $1,004.99      19,850.00 MXN    $4.99        $7.50 (0.75% on S)   $12.49
    beta_remit  $0.00 ("No fee!") 19.6800        $1,000.00      19,680.00 MXN    $0.00        $16.00 (1.60% on S)  $16.00
    gamma_fx    $4.00 DEDUCTED    19.9000        $1,000.00      19,820.40 MXN    $4.00        $4.98 (0.50% on      $8.98
                                                                                              $996.00 converted)
    

    beta_remit advertises "Zero Fee!" yet is the most expensive ($16.00 hidden inside its 19.68 exchange rate), whereas gamma_fx is the best deal ($8.98 = $4.00 + $4.98).

    Which mid-market timestamp should we use—comparison time or quote retrieval time? Both, for two distinct jobs! - On the user comparison screen (comparison_mid_rate at as_of): Normalize every row in the same response against the single current mid_rate at as_of. Why? Suppose Provider X and Provider Y both charge $0 fee on $1,000, Provider X delivers 19,850 MXN (fetched 3 minutes ago), and Provider Y delivers 19,920 MXN (fetched 10 seconds ago after a market tick). Evaluating both against the same current mid_rate guarantees a vital user-trust invariant: more money delivered for the same dollars spent ALWAYS produces a lower Total Cost. - At quote ingestion & validation (retrieved_mid_rate at retrieved_at): Also save the 30-second benchmark tick from the moment each quote was fetched. Comparing provider_rate against retrieved_mid_rate isolates the provider's true pricing spread from subsequent FX market drift, preventing false validation alerts and giving internal pricing teams clean competitor-margin analytics.

    Making the 30-second benchmark resilient: Pull 3 independent financial FX feeds and take their median so one glitched feed is automatically ignored (alerting if any feed diverges by > 0.2%). If all 3 feeds stall for > 90 s during market hours, flag benchmark.status = "STALE"; if an outage exceeds 10 minutes, suppress FX markup dollars and rank providers by effective payout per dollar paid (recipient_gets / customer_pays), which requires zero external benchmark!

  7. Deep dive 2: Unified Provider Adapter contract and isolated worker pools

    Every external integration—official REST API, partner S3/SFTP feed, or headless web scraper—implements one Adapter interface (a standardized plug-in wrapper) that separates network fetching from deterministic parsing and returns health and latency metadata alongside raw bytes:

    from dataclasses import dataclass, field
    from decimal import Decimal
    from typing import List, Optional
    
    
    @dataclass
    class QuoteQuery:
        source_ccy: str
        target_ccy: str
        send_amount: Decimal
        delivery_method: str
        pricing_tier: str = "STANDARD"
    
    
    @dataclass
    class FetchResult:
        # Standardized health & transport metadata returned by every fetch attempt
        status: str                        # "OK", "TIMEOUT", "RATE_LIMITED", "BLOCKED", "HTTP_ERROR"
        raw_bytes: Optional[bytes]         # Archived to S3 before parsing so broken parsers can replay
        latency_ms: int
        http_status: Optional[int] = None
        retry_after_s: Optional[int] = None
    
    
    @dataclass
    class StandardizedQuote:
        # Canonical parsed fields before mid-market normalization
        fee_amount: Decimal
        fee_currency: str
        fee_mode: str                      # "ADDED" or "DEDUCTED"
        provider_rate: Decimal             # Always normalized to: target_ccy units per 1 source_ccy unit
        receive_amount: Decimal
        pricing_tier: str                  # "STANDARD" or "FIRST_TRANSFER_PROMO"
        promo_conditions: Optional[str] = None
        disclaimers: List[str] = field(default_factory=list)
        provider_ttl_seconds: Optional[int] = None
    
    
    class ProviderAdapter:
        """Unified plug-in contract implemented once per external source."""
    
        provider_id: str = ""
        adapter_id: str = ""
        source_type: str = ""              # "API", "PARTNER", or "SCRAPER"
        parser_version: str = "v1"
    
        def fetch(self, query: QuoteQuery, timeout_ms: int) -> FetchResult:
            """Execute network/browser call only; never parse or drop raw bytes here."""
            raise NotImplementedError
    
        def parse(self, raw_bytes: bytes, query: QuoteQuery) -> List[StandardizedQuote]:
            """Pure, side-effect-free function turning archived raw_bytes into quotes."""
            raise NotImplementedError
    

    Why this separation makes extensibility and operations effortless: - Zero boilerplate per provider: Rate limiting (token buckets in Redis that cap outbound requests/s per provider), S3 raw archiving, quote validation, caching, and circuit breaking live in the shared worker harness, outside the adapter. - Declarative scrapers + fallback chains: Simple public quote pages don't even need new Python code—a ConfigurableScraperAdapter reads URL templates and JSONPath/CSS selectors from adapters.config_json. Each provider can register an ordered fallback chain (priority 1: API -> priority 2: Partner Feed -> priority 3: Public Web Scraper) so when an API goes down, the broker fails over automatically while recording which adapter_id produced the quote. - Three isolated worker pools (bulkheads): Async HTTP API workers handle hundreds of lightweight sockets per CPU; headless Playwright/Chromium scrapers consume ~300 MB RAM each and execute untrusted third-party JS, so they run in network-sandboxed containers with separate autoscaling; partner file loaders run on bulk ingestion schedules. Giving each provider its own bounded queue (bulkhead isolation) ensures one hung provider never starves the other 19.

  8. Deep dive 3: Two-tier caching, circuit breakers, and staleness states

    We combine amount-band caching, a two-tier Redis layout, and per-adapter circuit breakers so one slow provider never drags p95 latency past 800 ms:

    Quote lifecycle for key = "alpha_pay|USD|MXN|BANK_DEPOSIT|band_500_1000|STANDARD"
    
      t = 0 min         t = 4 min (80% TTL)       t = 5 min (fresh_until)                  t = 24 hours
      |-- FRESH TIER ---|-------------------------|---------------- STALE-FALLBACK TIER ---|---> evicted
      ^                 ^                         ^
      Quote fetched     Pre-warm scheduler        Fresh key expires in Redis; if refresh
      & written to      refreshes in background   failed, requests serve STALE copy with
      BOTH Redis tiers  so fresh tier stays warm! age_s + reason (never ranked #1!)
    

    How a comparison request resolves all ~12 providers in parallel within max_wait_ms:

    def resolve_provider_quote(
        provider_id: str,
        cache_key: str,
        live_fetch_allowed: bool,
        remaining_budget_ms: int,
        cache,
        circuit_breaker,
        broker,
    ):
        """Return (quote, status, failure_reason) for one provider without blocking healthy peers."""
        # 1. Fast path (< 2 ms): pre-warmed fresh tier hit (age <= 5 min and before provider expiry)
        fresh_quote = cache.get_fresh(cache_key)
        if fresh_quote is not None:
            return fresh_quote, "FRESH", None
    
        # 2. Fresh miss: decide whether to attempt a bounded live fetch or fail fast
        if not live_fetch_allowed:
            # Anonymous public traffic never triggers synchronous outbound scrapes; queue async warm-up
            broker.enqueue_async_refresh(cache_key)
            reason = "REFRESH_QUEUED"
        elif circuit_breaker.is_open(provider_id):
            # Fail in 0 ms when all live adapters for this provider are tripping timeouts/errors
            reason = "CIRCUIT_OPEN"
        elif remaining_budget_ms < 250:
            reason = "DEADLINE_EXCEEDED"
        else:
            # Single-flight broker deduplicates concurrent misses on `cache_key` into ONE outbound call
            live_quote, err_reason = broker.fetch_single_flight(
                provider_id, cache_key, timeout_ms=remaining_budget_ms - 30
            )
            if live_quote is not None:
                return live_quote, "LIVE", None
            reason = err_reason
    
        # 3. Graceful fallback: return 24h stale-fallback quote clearly flagged, or UNAVAILABLE
        stale_quote = cache.get_stale(cache_key)
        if stale_quote is not None:
            return stale_quote, "STALE", reason
        return None, "UNAVAILABLE", reason
    

    Circuit breaker & single-flight mechanics: - Circuit breaker (an automatic safety switch that trips OPEN when an adapter hits 5 consecutive timeouts or >= 50% failures across its last 20 calls): While OPEN, user requests skip live calls in 0 ms and read the stale tier immediately. After 30 seconds, a background scheduler probe (HALF_OPEN) tests one fetch and closes the breaker on recovery. - Single-flight coalescing: If 40 users simultaneously request an uncached corridor, the broker acquires a short Redis lock on cache_key so 1 worker calls the provider while the other 39 wait on the shared result up to their deadline. Even if a caller's 800 ms deadline expires first, the background fetch finishes (<= 2.5 s) and populates Redis for the next caller.

    Clear client status semantics (5 mutually exclusive states): - LIVE / FRESH: Valid quote within 5-minute SLA; eligible for ranking and "Best Value" badges. - STALE: Older than 5 minutes (< 24 h); rendered greyed-out with "Last verified 18m ago (provider temporarily unreachable)" and excluded from top-deal ranking so stale rates never masquerade as live winners. - UNAVAILABLE: No fresh or stale quote (reason = TIMEOUT, CIRCUIT_OPEN, VALIDATION_FAILED, etc.). - NOT_OFFERED: Provider does not support this corridor, delivery method, or send amount (distinct from an outage!).

  9. Validate broken parsers, defend rate limits, and weigh trade-offs

    Five automated validation gates before any parsed quote touches Redis Web scrapers often "succeed" syntactically while extracting the wrong DOM node (such as reading a $0 promo fee while missing a $500 cap, or reading an inverted rate). Every StandardizedQuote must pass: 1. Schema & currency check: Positive provider_rate and receive_amount, expected currency codes, non-empty disclaimers when required. 2. Cross-field math check: |(send_or_converted_amount * provider_rate) - receive_amount| <= rounding_tolerance (catches misaligned CSS selectors immediately!). 3. Mid-market sanity corridor: Standard provider_rate / retrieved_mid_rate must lie inside [0.90, 1.005] and upfront fee < 15% of send_amount (FIRST_TRANSFER_PROMO allows up to 1.05 only when promo_conditions is present). 4. Historical step-change guard: If a provider's spread jumps > 1.0% vs. its 24-hour rolling median, quarantine and trigger one immediate confirmation re-fetch before publishing. 5. DOM structural fingerprinting + nightly band-edge probes: Alert when a scraped page's DOM layout hash shifts, and probe both ends of every amount band ($100 vs. $499) nightly to verify fee brackets haven't shifted. Failed quotes save with validation_status = QUARANTINED so broken parsers degrade cleanly to STALE instead of poisoning rankings.

    Inbound & outbound rate-limiting defense - Inbound anti-scraping: Anonymous web visitors can only read Redis (live_fetch_allowed = False); otherwise an attacker querying random amounts ($500.01, $500.02, ...) could weaponize our servers to exhaust our partner API quotas! - Outbound politeness: Split each provider's token-bucket quota 80% for scheduled pre-warming (hot corridors prioritized) and 20% for authenticated live misses; strictly honor HTTP 429 Retry-After.

    Summary of key trade-offs - Pre-warming amount bands vs. per-request live fetching: Pre-warming ~9,600 keys gives < 50 ms cache hits and a flat 40 fetches/s outbound load, trading background polling of quiet bands and nightly band-boundary checks against a 15x reduction in provider calls. - Two-tier STALE fallback vs. hiding failed providers: Showing explicitly aged, unranked STALE quotes preserves transparency during outages without violating the 5-minute freshness guarantee on ranked quotes. - Dual mid-market timestamps (as_of for display vs. retrieved_at for spread validation): Normalizing comparison rows against the single current as_of benchmark guarantees payout order matches cost order on screen, while storing retrieved_mid_rate isolates provider spread changes from FX market movement. - API-first + partner feeds vs. web scraping: Scraping fills coverage gaps where competitors lack public APIs, but carries higher compute cost (~48 headless browsers), legal review requirements, and UI breakage—so it sits lowest in adapter priority behind strict validation gates.

Intuition & how it works

Think of comparing international money-transfer fees like comparing airline tickets where some airlines advertise a 19 USD fare but hide a 45 USD carry-on fee in fine print: in cross-border transfers, a provider advertising a 0 USD transfer fee often hides a steeper charge inside a worse exchange rate than the interbank mid-market rate (the true wholesale midpoint exchange rate between banks, with zero retail markup). To give users an honest, sub-second comparison without hammering 20 external competitors on every page load, our system runs a steady background price ticker that refreshes popular transfer routes every 4 minutes into a two-tier cache (a fast 5-minute fresh cache backed by a 24-hour fallback cache), while an independent 30-second financial feed updates the mid-market yardstick used to compute every provider's hidden exchange-rate cost.

The naive approach—calling all 12 providers for a remittance corridor (a currency route like USD -> MXN) live on every user request and sorting by upfront fee—fails on both math and reliability. At 3,000 peak requests per minute (50 req/s), live fan-out would fire 600 outbound API and headless-browser calls per second, immediately tripping competitor rate limits and dragging response latency to the slowest hung scraper (> 3 seconds), while sorting by upfront fee would rank a 0 USD fee provider with a poor exchange rate above a 4.00 USD fee provider that puts more Mexican pesos into the recipient's bank account.

Walk through a concrete $1,000.00 USD -> MXN comparison when our 30-second mid-market benchmark reads 20.00 MXN/USD: 1. Normalized cost calculation: alpha_pay charges $4.99 on top ($1,004.99 paid) and converts $1,000 at 19.85 (19,850 MXN delivered), losing $1,000 x (1 - 19.85 / 20.00) = $7.50 to FX spread (exchange-rate markup) for a Total Cost of $12.49. beta_remit charges $0.00 fee ($1,000.00 paid) at 19.68 (19,680 MXN delivered), losing $16.00 in hidden FX markup—making "Zero Fee" beta_remit more expensive than alpha_pay! gamma_fx deducts $4.00 from $1,000.00 and converts the remaining $996.00 at 19.90 (19,820.40 MXN delivered), costing $4.00 + $996.00 x (1 - 19.90 / 20.00) = $4.00 + $4.98 = $8.98 total—the true best deal. 2. Fast two-tier lookup with circuit breaking: When a user loads USD -> MXN ($1,000), the Comparison Service fetches all 12 providers' pre-warmed $500-$1,000 bracket quotes in a single Redis MGET (< 5 ms). alpha_pay, beta_remit, and gamma_fx hit the fresh cache (age <= 5 min) and are ranked gamma_fx ($8.98), alpha_pay ($12.49), beta_remit ($16.00). 3. Graceful partial degradation: Suppose delta_wire's scraper started timing out 10 minutes ago, tripping its circuit breaker (an automatic switch that stops calling a failing dependency so requests fail in 0 ms instead of waiting for timeouts). Rather than failing the page or blocking for 3 seconds, the service instantly pulls delta_wire's 16-minute-old quote from the stale-fallback cache, returns HTTP 200 with complete: false, and renders delta_wire greyed out at the bottom as STALE (age: 16m, reason: CIRCUIT_OPEN) with full quote_id provenance pointing to the raw archived response in S3.

Key trade-offs

  • Background pre-warming vs. on-demand live fetching. Pre-warming ~9,600 (provider, corridor, delivery_method, amount_band) keys every 4 minutes keeps outbound traffic at a predictable ~40 fetches/s (~2/s per provider) and serves p95 reads well inside 800 ms, at the cost of polling quiet corridors when nobody is looking. Fetching on demand per user request avoids background polling, but multiplies peak outbound load 15x (600 calls/s) and exposes users to multi-second tail latencies.
  • Amount-band caching vs. exact-amount caching. Caching by fee-tier bracket (such as $0-$500, $500-$1,000) allows one cached quote's fee and FX rate to compute exact payouts for any dollar amount inside that bracket. The trade-off is maintaining an accurate band map per provider, mitigated by a nightly job that probes both edges of each band and alerts if rates diverge (falling back to exact-amount keys when bands are unknown).
  • Display benchmark (as_of) vs. ingestion benchmark (retrieved_at). Normalizing all providers on a user comparison screen against the single current as_of mid-market tick ensures every row uses the same baseline so higher recipient payout always corresponds to lower Total Cost. Storing retrieved_mid_rate at quote fetch time adds one column per quote, but lets validation rules and internal pricing analysts measure each competitor's true FX spread without 4-minute market movements distorting the spread.
  • Serving flagged STALE quotes vs. omitting failed providers. Returning a 15-minute-old quote labeled STALE with its exact age keeps the comparison informative during competitor outages, provided STALE rows are visually separated and strictly excluded from #1 Best Value ranking so the 5-minute freshness requirement is never compromised.
  • Fail-fast circuit breakers vs. waiting out slow providers. Opening an adapter's circuit breaker after repeated timeouts eliminates 2.5-second latency spikes on user requests immediately, trading up to 30 seconds of serving STALE data after the provider recovers until a background probe closes the breaker.
  • Archiving raw payloads (~52 GB/day) vs. storing parsed fields only. Saving compressed raw JSON and HTML in content-addressed object storage before parsing costs a few terabytes per quarter, but provides non-repudiable regulatory provenance and lets engineers replay historical responses whenever a parser bug is fixed.

Common mistakes

  • Comparing upfront fees without FX spread, or miscalculating deducted fees, either ranking "Zero Fee" wide-spread providers first or applying (1 - r / mid) to the full $1,000 instead of the $996.00 converted principal when a $4.00 fee is deducted upfront (causing line items not to sum to Total Cost).
  • Using binary floating-point (float) for currency rates and payouts, introducing penny rounding discrepancies instead of using exact fixed-point Decimal math and normalizing rate direction (target per 1 source) up front.
  • Evaluating two providers on the same screen against different historical mid-market ticks, which can absurdly label a provider delivering fewer pesos for the exact same $1,000 outlay as having a "lower Total Cost".
  • Caching one quote per corridor without send-amount brackets, serving $100 small-transfer fees and rates to a customer sending $5,000.
  • Allowing unauthenticated public requests to trigger live outbound fetches on arbitrary amounts, letting bots or competitors send $1000.01, $1000.02, ... to exhaust your external API quotas and browser pool.
  • Failing the whole HTTP request when one provider times out—or silently omitting failed providers without distinguishing UNAVAILABLE (our fetch failed) from NOT_OFFERED (the competitor does not support that corridor).
  • Parsing inside the network fetch step and discarding raw bytes, making compliance audits impossible and preventing retroactive re-parsing when a competitor tweaks its HTML.
  • Trusting any number that parses without arithmetic and market-sanity checks, allowing a broken CSS selector to publish a $0 fee or inverted FX rate straight into the live cache.

Follow-up questions

  • How could you use an LLM-assisted workflow to repair broken web scrapers automatically when a competitor redesigns its public calculator page? Never put an LLM on the synchronous customer read path or let it invent numbers directly; use it strictly inside an offline/asynchronous parser-repair loop. When structural DOM fingerprinting or quote math validation (amount * rate != receive_amount) quarantines a scraper, an isolated repair job feeds the old selector config, the before/after HTML snapshots, and the last known-good quote into the LLM inside a network-sandboxed environment to propose an updated declarative selector config (CSS/XPath/JSONPath rules, never arbitrary executable code, defending against prompt injection hidden in third-party web pages). The candidate config must pass historical recorded-payload unit tests, cross-field arithmetic checks, and mid-market sanity bounds across multiple test amounts, then run in shadow mode for several refresh cycles before promoting (with human sign-off for major changes).
  • How should your data model and ranking logic separate introductory new-customer teaser rates from everyday repeat-sender pricing? Treat pricing_tier (STANDARD vs. FIRST_TRANSFER_PROMO) as a first-class column in both the database schema and the Redis cache key, paired with structured promo_conditions (new_customers_only, max_promo_amount, valid_until, required promo code). Ingest both tiers separately where available—for example, anonymous public web flows often highlight first-transfer teaser rates (sometimes even beating the mid-market rate up to the first $500), whereas authenticated APIs or logged-in flows return recurring rates. By default, rank apples-to-apples on STANDARD recurring pricing while displaying promotional offers as a clearly badged secondary callout (or behind an explicit "First transfer?" toggle), and enforce promotional amount caps accurately (for instance, applying a promo rate to the first $500 and the standard rate to the remaining $500 on a $1,000 transfer, or marking the promo inapplicable).
  • What signals and verification checks would expose a competitor returning spoofed or artificially favorable quotes specifically to your crawler IPs? Cross-validate scraped quotes continuously against independent vantage points: compare public-page scrapes against partner data feeds, official quote APIs where available, residential/multi-ASN canary probes across regions, and final pre-checkout screens (since bait-and-switch pricing often inflates rates only on the unauthenticated landing calculator). Track each provider's FX spread distribution broken down by egress network; a statistically significant spread shift isolated to our scraper IP range—or rates that consistently beat mid-market without promo disclaimers—triggers automatic quarantine (UNAVAILABLE: VALIDATION_FAILED) and alerts compliance. For ground-truth verification on top corridors, run periodic low-value mystery-shopping transfers (real end-to-end test transactions) and compare actual settled receipts against scraped quotes, prioritizing licensed data-sharing partnerships over cat-and-mouse IP rotation whenever discrepancies appear.

Follow-up questions

Similar questions

More Remitly interview questions

All 11 Remitly questions →