Railcar Pricing Endpoint Service and Resilient High-Load Architecture

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Build the service-layer implementation and resilience cache for a railcar shipment pricing endpoint (POST /quotes), keeping domain logic cleanly decoupled from live databases and external HTTP services.

The starter module defines these frozen domain types, exceptions, constants, and abstract port interfaces (do not modify their names or signatures):

  • Constants: CENTS = Decimal("0.01"), QUOTE_TTL = timedelta(hours=24), MAX_CARS = 500, STATION_CODE = re.compile(r"[A-Z0-9]{3,10}").
  • Domain dataclasses: QuoteRequest(origin, destination, commodity, car_count, ship_date) and Quote(quote_id, request, miles, rate_per_car_mile, surcharge_rate, base, surcharge, total, created_at, expires_at).
  • Exceptions: ValidationError(errors: Dict[str, str]), UnquotableError(code: str, message: str), and DependencyError(dependency: str, message: str = "").
  • Abstract ports:
    • TariffRepository.rate_per_car_mile(commodity: str) -> Optional[Decimal]
    • RouteService.distance_miles(origin: str, destination: str) -> Optional[Decimal]
    • SurchargeService.surcharge_rate(ship_date: date) -> Decimal
    • QuoteRepository.save(quote: Quote) -> None

Implement the following functions and classes:

Part 1 — Validation, Exact Decimal Pricing, Service Layer, and HTTP Mapping

  1. parse_quote_request(body: Any, today: date) -> QuoteRequest:
    • If body is not a dict, raise ValidationError({"body": ...}).
    • Validate all five fields in a single pass so every invalid field name appears in ValidationError.errors:
      • origin and destination: strings matching STATION_CODE (3–10 uppercase ASCII letters or digits). When both are valid strings and origin == destination, record an error on "destination".
      • commodity: string containing at least one non-whitespace character (store commodity.strip() on QuoteRequest).
      • car_count: exact integer (int, rejecting bool, float, and str) in [1, MAX_CARS].
      • ship_date: strict "YYYY-MM-DD" calendar string representing a real calendar date >= today (reject compact "YYYYMMDD" or ISO week strings).
  2. price(rate_per_car_mile: Decimal, miles: Decimal, car_count: int, surcharge_rate: Decimal) -> Tuple[Decimal, Decimal, Decimal]:
    • Compute (base, surcharge, total) in exact base-10 dollars rounded half up (ROUND_HALF_UP) to Decimal("0.01"):
      • base rounds rate_per_car_mile * miles * car_count to cents.
      • surcharge rounds base * surcharge_rate to cents.
      • total = base + surcharge (sum of the rounded cent amounts).
  3. QuoteService:
    • Constructor accepts (tariffs, routes, surcharges, quotes, now=_utc_now, new_id=_new_id, ttl=QUOTE_TTL).
    • create_quote(self, body: Any) -> Quote:
      • Read created_at = self.now() once and validate body against created_at.date().
      • Query tariffs.rate_per_car_mile(commodity) first; if None, raise UnquotableError("NO_TARIFF", ...) before calling routes or surcharges.
      • Query routes.distance_miles(origin, destination) next; if None, raise UnquotableError("NO_ROUTE", ...) before calling surcharges.
      • Fetch surcharges.surcharge_rate(ship_date), compute (base, surcharge, total), set expires_at = created_at + self.ttl, construct Quote with quote_id = self.new_id(), persist via quotes.save(quote) before returning, and return quote. Allow DependencyError to propagate.
  4. quote_to_json(quote: Quote) -> Dict[str, Any] and handle_post_quotes(service: QuoteService, body: Any) -> Tuple[int, Dict[str, Any]]:
    • quote_to_json formats "id", "origin", "destination", "commodity", "car_count", "ship_date" ("YYYY-MM-DD"), stringified Decimal fields ("miles", "rate_per_car_mile", "surcharge_rate", "base", "surcharge", "total"), "currency": "USD", and "expires_at" (ISO-8601 timestamp).
    • handle_post_quotes maps outcomes to HTTP (status_code, response_dict):
      • Success -> (201, quote_to_json(quote))
      • ValidationError -> (400, {"error": "INVALID_REQUEST", "fields": exc.errors})
      • UnquotableError -> (422, {"error": exc.code, "message": exc.message})
      • DependencyError -> (503, {"error": "DEPENDENCY_UNAVAILABLE", "dependency": exc.dependency, "retryable": True})
      • Any unexpected exception -> (500, {"error": "INTERNAL_ERROR"}) without exposing internal error text.

Part 2 — Fresh + Bounded Stale-if-Error Surcharge Cache

Implement CachedSurchargeService(SurchargeService) initialized with (inner: SurchargeService, fresh_for: timedelta, max_stale: timedelta, now: Callable[[], datetime] = _utc_now):

  • If ship_date has a cached entry whose age now() - fetched_at is strictly less than fresh_for, return the cached rate immediately without calling inner.
  • Otherwise invoke inner.surcharge_rate(ship_date). On success, update the cache at now() and return the new rate.
  • If inner raises DependencyError, return the cached rate when ship_date is cached and now() - fetched_at <= max_stale; otherwise re-raise DependencyError.

Examples

Example 1

Setup: now() returns 2026-08-10T14:00:00+00:00, new_id() returns "q-104", tariff for "LUMBER" is Decimal("1.8375"), route ("DALX", "SEAT") is Decimal("615") miles, and surcharge on 2026-08-15 is Decimal("0.085").

Input:

body = {
    "origin": "DALX",
    "destination": "SEAT",
    "commodity": "LUMBER",
    "car_count": 3,
    "ship_date": "2026-08-15",
}
handle_post_quotes(service, body)

Output:

(
    201,
    {
        "id": "q-104",
        "origin": "DALX",
        "destination": "SEAT",
        "commodity": "LUMBER",
        "car_count": 3,
        "ship_date": "2026-08-15",
        "miles": "615",
        "rate_per_car_mile": "1.8375",
        "surcharge_rate": "0.085",
        "base": "3390.19",
        "surcharge": "288.17",
        "total": "3678.36",
        "currency": "USD",
        "expires_at": "2026-08-11T14:00:00+00:00",
    },
)

Explanation: 1.8375 * 615 * 3 = 3390.1875, which rounds half up to "3390.19". Multiplying 3390.19 * 0.085 = 288.16615 rounds half up to "288.17", and "3390.19" + "288.17" = "3678.36". The quote is saved to QuoteRepository with a 24-hour expiry before returning 201.

Example 2

Input & Output (error mapping and bounded stale cache):

  • Multi-field validation (400): Passing {"origin": "DALX", "destination": "DALX", "commodity": " ", "car_count": True, "ship_date": "2026-08-09"} returns status 400 with error == "INVALID_REQUEST" and fields containing keys {"destination", "commodity", "car_count", "ship_date"}, invoking zero repositories or remote services.
  • Unquotable commodity (422): Requesting "commodity": "STEEL" when no tariff exists returns (422, {"error": "NO_TARIFF", ...}) without calling RouteService or SurchargeService.
  • Outage fallback (CachedSurchargeService with fresh_for=5 min, max_stale=60 min): After caching Decimal("0.085") at t = 0, a lookup at t = +3 min skips inner; if inner raises DependencyError("surcharge", "timeout") at t = +20 min, the wrapper serves Decimal("0.085") (20 <= 60), whereas at t = +75 min (75 > 60) it re-raises DependencyError so handle_post_quotes returns (503, {"error": "DEPENDENCY_UNAVAILABLE", "dependency": "surcharge", "retryable": True}).

Constraints

  • Never use binary float arithmetic for monetary calculations; use Python Decimal with ROUND_HALF_UP to Decimal("0.01").
  • 1 <= car_count <= 500, and bool values (True / False) must be rejected.
  • Station codes match ^[A-Z0-9]{3,10}$ with origin != destination.
  • ship_date must match YYYY-MM-DD and satisfy ship_date >= today.
  • fresh_for >= timedelta(0) and max_stale >= fresh_for.

Step-by-step walkthrough

  1. Pin down assumptions and the HTTP error contract

    Start by establishing explicit engineering invariants so Part 1's code and Part 2's architecture share one crisp specification:

    • Dependency failures: Part 1 fails closed with 503 (never invents a price); Part 2 adds a bounded stale-if-error cache (a cache that serves a slightly older value only when the upstream service fails, up to a strict maximum age).
    • Persistence and validity: Every quote is saved to QuoteRepository before returning 201, and stays valid for 24 hours (QUOTE_TTL).
    • Validation rules: origin and destination are 3–10 uppercase alphanumeric characters and must differ; commodity is non-empty text; car_count is an integer in 1..500; ship_date is YYYY-MM-DD and not earlier than today (UTC).
    • Money: Exact base-10 Decimal arithmetic in USD, rounding each line half up to cents ($0.01).

    Clients react differently depending on why a request failed, so separate four error classes cleanly:

    Situation HTTP status Error code Should client retry as-is?
    Quote created and saved 201 — No
    Malformed fields (wrong type, past date, origin == destination) 400 INVALID_REQUEST (with fields) No — fix the payload
    Valid request, but no tariff or rail route exists 422 NO_TARIFF / NO_ROUTE No — business rule
    Downstream service or DB failed / timed out 503 DEPENDENCY_UNAVAILABLE Yes — with backoff
    Unexpected bug (KeyError, ZeroDivisionError) 500 INTERNAL_ERROR (no internals leaked) Maybe later
  2. Separate HTTP, business logic, and external ports

    To make POST /quotes unit-testable without live databases or network calls, use ports and adapters with dependency injection (passing abstract dependency interfaces into a class's constructor instead of hardcoding network/SQL clients inside it):

    HTTP adapter     handle_post_quotes(service, body) -> (status_code, response_dict)
           |
    Service layer    QuoteService.create_quote(body) -> Quote
           |
    Abstract ports   TariffRepository   RouteService   SurchargeService   QuoteRepository
           |
    Implementations  Production: SQL + HTTP clients    Tests: fast in-memory fakes
    

    Even the wall clock (now) and ID generator (new_id) are injected functions with sensible defaults, allowing unit tests to freeze time and assert exact expires_at timestamps. Notice also how the ports separate normal "not found" outcomes (None) from infrastructure failures (DependencyError).

  3. Validate every field in one pass

    Validation runs before any database or network call so bad payloads cost zero downstream traffic, and collects all field errors into one dictionary so a caller fixes everything in one round trip.

    Watch out for two classic Python validation traps:

    1. isinstance(True, int) is True because bool inherits from int in Python. Always reject isinstance(car_count, bool) first, or "car_count": true silently prices 1 railcar!
    2. Python 3.11+ date.fromisoformat is overly permissive: it accepts "20260815" and ISO week strings like "2026-W33-1". Checking a strict YYYY-MM-DD regex first pins the exact API format, and date.fromisoformat then rejects impossible calendar dates like "2026-02-30".
    ISO_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
    
    
    def _validate_station(body: Dict[str, Any], field: str, errors: Dict[str, str]) -> Optional[str]:
        value = body.get(field)
        if not isinstance(value, str) or not STATION_CODE.fullmatch(value):
            errors[field] = "must be a station code of 3 to 10 uppercase letters or digits"
            return None
        return value
    
    
    def _validate_ship_date(value: Any, today: date, errors: Dict[str, str]) -> Optional[date]:
        # Check ISO_DATE regex first because Python 3.11+ date.fromisoformat() also accepts
        # compact "20261201" and week dates like "2026-W49-1", which violate "YYYY-MM-DD".
        if not isinstance(value, str) or not ISO_DATE.fullmatch(value):
            errors["ship_date"] = "must be a date in the form YYYY-MM-DD"
            return None
        try:
            parsed_date = date.fromisoformat(value)
        except ValueError:
            errors["ship_date"] = "is not a real calendar date"
            return None
        if parsed_date < today:
            errors["ship_date"] = "must not be in the past"
            return None
        return parsed_date
    
    
    def parse_quote_request(body: Any, today: date) -> QuoteRequest:
        """Validate every field in one pass and raise ValidationError listing all bad fields."""
        if not isinstance(body, dict):
            raise ValidationError({"body": "must be a JSON object"})
    
        # errors: field_name -> human-readable validation message; collected across all fields.
        errors: Dict[str, str] = {}
        origin = _validate_station(body, "origin", errors)
        destination = _validate_station(body, "destination", errors)
        if origin is not None and origin == destination:
            errors["destination"] = "must differ from origin"
    
        commodity = body.get("commodity")
        if not isinstance(commodity, str) or commodity.strip() == "":
            errors["commodity"] = "must be a non-empty string"
    
        car_count = body.get("car_count")
        # Check isinstance(..., bool) first because bool is a subclass of int in Python.
        if isinstance(car_count, bool) or not isinstance(car_count, int):
            errors["car_count"] = "must be an integer"
        elif not 1 <= car_count <= MAX_CARS:
            errors["car_count"] = f"must be between 1 and {MAX_CARS}"
    
        ship_date = _validate_ship_date(body.get("ship_date"), today, errors)
        if errors:
            raise ValidationError(errors)
        return QuoteRequest(origin, destination, commodity.strip(), car_count, ship_date)
    
  4. Compute money with exact `Decimal` and line-item rounding

    IEEE-754 binary float cannot represent most base-10 fractions (0.1, 1.005, 0.085) exactly, which causes silent cent errors at half-cent boundaries:

    Example: rate = 1.005, miles = 333, car_count = 3
      Exact base-10 product:  1.005 * 999 = 1003.995  -> rounds half up to $1004.00
      Binary float product:   1003.9949999999999      -> rounds down to    $1003.99  (1 cent lost!)
    
    Example: rate = 0.105, miles = 1, car_count = 1
      Commercial ROUND_HALF_UP:  0.105 -> $0.11
      Python round(0.105, 2):    0.105 -> $0.10 (banker's round-half-to-even)
    

    We construct Decimal values from strings (Decimal("1.8375")), round base once to $0.01 with ROUND_HALF_UP, round surcharge = base * surcharge_rate once to $0.01, and set total = base + surcharge so the displayed invoice lines always add up to total:

    Example 1 (LUMBER: rate = 1.8375, miles = 615, car_count = 3, surcharge_rate = 0.085):
      base      = round_half_up(1.8375 * 615 * 3) = round_half_up(3390.1875) = 3390.19
      surcharge = round_half_up(3390.19 * 0.085)  = round_half_up(288.16615) =  288.17
      total     = 3390.19 + 288.17                                           = 3678.36
    
    CENTS = Decimal("0.01")
    
    
    def to_cents(amount: Decimal) -> Decimal:
        """Round a Decimal dollar amount to 0.01 using commercial round-half-up."""
        return amount.quantize(CENTS, rounding=ROUND_HALF_UP)
    
    
    def price(rate_per_car_mile: Decimal, miles: Decimal, car_count: int,
              surcharge_rate: Decimal) -> Tuple[Decimal, Decimal, Decimal]:
        """Compute (base, surcharge, total) in cents so displayed invoice lines sum to total."""
        # Round each line item once before summing so base + surcharge == total is guaranteed.
        base = to_cents(rate_per_car_mile * miles * car_count)
        surcharge = to_cents(base * surcharge_rate)
        total = base + surcharge
        return base, surcharge, total
    
  5. Orchestrate `QuoteService` and map HTTP responses

    Inside QuoteService.create_quote, we order operations from cheapest to most expensive:

    1. Validate input in memory (0 I/O).
    2. Read the commodity tariff from the local DB (NO_TARIFF stops before any remote RPC).
    3. Call RouteService (NO_ROUTE stops before calling SurchargeService).
    4. Call SurchargeService, compute exact Decimal amounts, and save(quote) before returning so a client never receives a quote_id that failed to persist.

    In the HTTP adapter, all Decimal values are serialized as JSON strings ("3678.36") so JavaScript or Python clients do not parse them into binary floats, and unexpected exceptions return a generic 500 body without leaking internal table or host names:

    class QuoteService:
        """Business logic of POST /quotes. Every dependency is injected so unit tests use fakes."""
    
        def __init__(self, tariffs: TariffRepository, routes: RouteService, surcharges: SurchargeService,
                     quotes: QuoteRepository, now: Callable[[], datetime] = _utc_now,
                     new_id: Callable[[], str] = _new_id, ttl: timedelta = QUOTE_TTL) -> None:
            self.tariffs = tariffs
            self.routes = routes
            self.surcharges = surcharges
            self.quotes = quotes
            self.now = now
            self.new_id = new_id
            self.ttl = ttl
    
        def create_quote(self, body: Any) -> Quote:
            # Phase 1: capture one consistent timestamp for both "today" validation and expiry.
            created_at = self.now()
            request = parse_quote_request(body, created_at.date())
    
            # Phase 2: query dependencies from cheapest/local to slowest/remote so unquotable
            # requests fail early without wasting remote RPCs.
            rate = self.tariffs.rate_per_car_mile(request.commodity)
            if rate is None:
                raise UnquotableError("NO_TARIFF", f"no tariff for commodity {request.commodity!r}")
    
            miles = self.routes.distance_miles(request.origin, request.destination)
            if miles is None:
                raise UnquotableError("NO_ROUTE", f"no rail route from {request.origin} to {request.destination}")
    
            surcharge_rate = self.surcharges.surcharge_rate(request.ship_date)
    
            # Phase 3: compute exact Decimal prices and persist the quote before returning its ID.
            base, surcharge, total = price(rate, miles, request.car_count, surcharge_rate)
            expires_at = created_at + self.ttl
            quote = Quote(
                quote_id=self.new_id(),
                request=request,
                miles=miles,
                rate_per_car_mile=rate,
                surcharge_rate=surcharge_rate,
                base=base,
                surcharge=surcharge,
                total=total,
                created_at=created_at,
                expires_at=expires_at,
            )
            self.quotes.save(quote)
            return quote
    
    
    def quote_to_json(quote: Quote) -> Dict[str, Any]:
        """Serialize Decimal amounts and rates as strings so JSON parsers do not lose cents."""
        return {
            "id": quote.quote_id,
            "origin": quote.request.origin,
            "destination": quote.request.destination,
            "commodity": quote.request.commodity,
            "car_count": quote.request.car_count,
            "ship_date": quote.request.ship_date.isoformat(),
            "miles": str(quote.miles),
            "rate_per_car_mile": str(quote.rate_per_car_mile),
            "surcharge_rate": str(quote.surcharge_rate),
            "base": str(quote.base),
            "surcharge": str(quote.surcharge),
            "total": str(quote.total),
            "currency": "USD",
            "expires_at": quote.expires_at.isoformat(),
        }
    
    
    def handle_post_quotes(service: QuoteService, body: Any) -> Tuple[int, Dict[str, Any]]:
        """Map service outcomes to (HTTP status, JSON response dict) for POST /quotes."""
        try:
            quote = service.create_quote(body)
        except ValidationError as exc:
            return 400, {"error": "INVALID_REQUEST", "fields": exc.errors}
        except UnquotableError as exc:
            return 422, {"error": exc.code, "message": exc.message}
        except DependencyError as exc:
            logger.warning("POST /quotes: dependency failed: %s", exc)
            return 503, {"error": "DEPENDENCY_UNAVAILABLE", "dependency": exc.dependency, "retryable": True}
        except Exception:
            # Log full traceback internally, but never leak internal exception text in a 500 body.
            logger.exception("POST /quotes: unexpected error")
            return 500, {"error": "INTERNAL_ERROR"}
        return 201, quote_to_json(quote)
    
  6. Part 2: shorten the critical path with parallelism and caching

    Suppose median call times are: tariff DB 5 ms, route service 120 ms, surcharge service 80 ms, quote insert 10 ms:

    Sequential critical path:        5 + 120 + 80 + 10            = 215 ms
    Parallel route || surcharge:     5 + max(120, 80) + 10        = 135 ms
    Both route + surcharge cached:   5 + 0 + 0 + 10               =  15 ms
    
    1. Parallelize independent RPCs: Once the tariff exists, distance_miles and surcharge_rate do not depend on each other, so running them concurrently cuts latency from route + surcharge to max(route, surcharge). Note that parallelism alone does not eliminate tail spikes: if each service has an independent 1% chance of stalling, 1 - 0.99^2 = 1.99% of requests still wait on a slow call.
    2. Cache slow-changing lookups: Rail station distances almost never change (cache for hours or precompute a station-pair table), tariffs change only on publish, and surcharges depend only on ship_date (just ~365 keys for a full year!).
    3. Implement fresh + stale-if-error caching: CachedSurchargeService wraps SurchargeService using two time windows:
      • Fresh (age < fresh_for, e.g., < 5 min): Return immediately from memory with 0 network calls.
      • Stale-if-error (fresh_for <= age <= max_stale, e.g., <= 60 min): Try inner.surcharge_rate first; if it raises DependencyError, serve the cached rate instead of returning 503. Older than max_stale, re-raise DependencyError so pricing error stays bounded.
    class CachedSurchargeService(SurchargeService):
        """Wraps a SurchargeService with fresh-hit caching and stale-if-error fallback.
    
        Implements SurchargeService directly so QuoteService needs zero code changes.
        """
    
        def __init__(self, inner: SurchargeService, fresh_for: timedelta, max_stale: timedelta,
                     now: Callable[[], datetime] = _utc_now) -> None:
            self.inner = inner
            self.fresh_for = fresh_for
            self.max_stale = max_stale
            self.now = now
            # _cache maps ship_date -> (cached_rate, fetched_at_timestamp).
            self._cache: Dict[date, Tuple[Decimal, datetime]] = {}
    
        def surcharge_rate(self, ship_date: date) -> Decimal:
            current_time = self.now()
            cached_entry = self._cache.get(ship_date)
    
            # Strict '<': serve immediately without network I/O when strictly younger than fresh_for.
            if cached_entry is not None:
                cached_rate, fetched_at = cached_entry
                if current_time - fetched_at < self.fresh_for:
                    return cached_rate
    
            try:
                fresh_rate = self.inner.surcharge_rate(ship_date)
            except DependencyError:
                # Inclusive '<=': during an outage, fall back to a cached rate up to max_stale old.
                if cached_entry is not None:
                    cached_rate, fetched_at = cached_entry
                    if current_time - fetched_at <= self.max_stale:
                        logger.warning("surcharge service failed; serving stale rate from %s", fetched_at)
                        return cached_rate
                raise
    
            self._cache[ship_date] = (fresh_rate, current_time)
            return fresh_rate
    
  7. Part 2: contain slow dependencies with timeouts, breakers, bulkheads, and async quotes

    Why is a slow dependency worse than a crashed one? By Little's law (average concurrent in-flight requests = arrival rate * average response time):

    Normal at 2,000 req/s and 0.135 s latency:   2,000 * 0.135 =   270 in-flight requests
    Route slows to 2.0 s (total 2.015 s):        2,000 * 2.015 = 4,030 in-flight requests!
    With a 300 ms route timeout (total 0.315 s): 2,000 * 0.315 =   630 in-flight requests
    

    Without protection, 4,030 blocked requests exhaust worker threads and DB connections, taking down healthy endpoints like GET /quotes/{id} too. Five defenses prevent cascading failure:

    • Per-call timeouts from a shared request deadline: Give POST /quotes an overall budget (say 400 ms) and cap each RPC (300 ms max).
    • Bounded, jittered retries: Retry idempotent reads at most once when budget remains, with random jitter and a global retry cap (e.g., retries <= 10% of traffic) so retries do not amplify an outage 3x–27x.
    • Circuit breaker (a state machine per dependency that trips open when recent error/timeout rate exceeds a threshold, failing fast for a short cooldown before testing recovery with a few half-open probe calls): Frees worker threads in < 1 ms and triggers stale-cache fallback immediately.
    • Bulkheads (separate bounded connection/thread pools per dependency, named after watertight ship compartments): Ensures a stalled RouteService pool cannot starve TariffRepository or QuoteRepository.
    • Load shedding & asynchronous quotes: Shed excess load early with 503 + Retry-After when queue depth spikes. If dependencies frequently take multiple seconds, offer an asynchronous quote flow: POST /quotes validates, writes a PENDING row, enqueues a job, and immediately returns 202 Accepted with Location: /quotes/{id} while background workers compute the price and clients poll GET /quotes/{id} or receive a webhook.
    Client ──> Load Balancer ──> Quote API (stateless, horizontally scaled)
                                   │  (request deadline, circuit breakers, bulkheads, load shedding)
                                   ├── Tariff Cache ───────> Tariff DB (read replica)
                                   ├── Route Cache ────────> Route Service
                                   ├── Surcharge Cache ────> Surcharge Service
                                   └── Quotes DB (primary, partitioned by created_at date)
    
    Async option:  POST /quotes (202) ──> Durable Queue ──> Pricing Workers ──> Quotes DB
    
  8. Part 2: database scaling and observability metrics

    • Stateless API scaling: Autoscale instances on in-flight request concurrency and queue wait time (not just CPU, because threads waiting on slow RPCs burn almost zero CPU!).
    • Database scaling: Serve read-heavy tariffs from in-memory caches + read replicas; keep quotes inserts lean on the primary, partitioned by created_at day so expired 24-hour quotes can be dropped instantaneously by dropping old partitions instead of running expensive DELETE scans.
    • Key metrics to alert on:
      • Endpoint: RPS, p50/p95/p99 latency, status breakdown (201, 400, 422, 503, 500).
      • Dependencies: per-service p99 latency, timeout rate, retry rate, circuit-breaker open transitions.
      • Caches: fresh hit ratio, stale_served_on_error counter, age of cached entries.
      • Saturation: in-flight requests, bulkhead pool utilization, DB connection pool wait time, queue lag (async mode).
  9. Put it all together

    Here is the complete solution.py containing validation, exact Decimal pricing, QuoteService, the HTTP adapter, and CachedSurchargeService:

    from typing import Any, Callable, Dict, Optional, Tuple
    from abc import ABC, abstractmethod
    from dataclasses import dataclass
    from datetime import date, datetime, timedelta, timezone
    from decimal import Decimal, ROUND_HALF_UP
    import logging
    import re
    import uuid
    
    logger = logging.getLogger("quotes")
    
    CENTS = Decimal("0.01")
    QUOTE_TTL = timedelta(hours=24)               # assumption: a quote stays valid for 24 hours
    MAX_CARS = 500                                # assumption: upper bound on car_count
    STATION_CODE = re.compile(r"[A-Z0-9]{3,10}")  # assumption: station code format
    ISO_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
    
    
    # ---- Domain types and errors -------------------------------------------------------------
    
    @dataclass(frozen=True)
    class QuoteRequest:
        origin: str
        destination: str
        commodity: str
        car_count: int
        ship_date: date
    
    
    @dataclass(frozen=True)
    class Quote:
        quote_id: str
        request: QuoteRequest
        miles: Decimal
        rate_per_car_mile: Decimal
        surcharge_rate: Decimal
        base: Decimal
        surcharge: Decimal
        total: Decimal
        created_at: datetime
        expires_at: datetime
    
    
    class ValidationError(Exception):
        """The request is malformed. errors maps each invalid field name to a reason string."""
    
        def __init__(self, errors: Dict[str, str]) -> None:
            super().__init__(errors)
            self.errors = errors
    
    
    class UnquotableError(Exception):
        """The request is syntactically valid, but no tariff or rail route exists for it."""
    
        def __init__(self, code: str, message: str) -> None:
            super().__init__(message)
            self.code = code
            self.message = message
    
    
    class DependencyError(Exception):
        """A downstream service or database failed or timed out."""
    
        def __init__(self, dependency: str, message: str = "") -> None:
            super().__init__(f"{dependency}: {message}")
            self.dependency = dependency
    
    
    # ---- Ports: abstract interfaces injected into QuoteService -------------------------------
    
    class TariffRepository(ABC):
        @abstractmethod
        def rate_per_car_mile(self, commodity: str) -> Optional[Decimal]:
            """The tariff rate for commodity, or None if there is no tariff for it."""
    
    
    class RouteService(ABC):
        @abstractmethod
        def distance_miles(self, origin: str, destination: str) -> Optional[Decimal]:
            """Rail distance in miles, or None if no route exists."""
    
    
    class SurchargeService(ABC):
        @abstractmethod
        def surcharge_rate(self, ship_date: date) -> Decimal:
            """Surcharge as a fraction of the base price (Decimal("0.065") means 6.5%)."""
    
    
    class QuoteRepository(ABC):
        @abstractmethod
        def save(self, quote: Quote) -> None:
            """Persist the quote."""
    
    
    # ---- Request validation ------------------------------------------------------------------
    
    def _validate_station(body: Dict[str, Any], field: str, errors: Dict[str, str]) -> Optional[str]:
        value = body.get(field)
        if not isinstance(value, str) or not STATION_CODE.fullmatch(value):
            errors[field] = "must be a station code of 3 to 10 uppercase letters or digits"
            return None
        return value
    
    
    def _validate_ship_date(value: Any, today: date, errors: Dict[str, str]) -> Optional[date]:
        # Check ISO_DATE regex first because Python 3.11+ date.fromisoformat() also accepts
        # compact "20261201" and week dates like "2026-W49-1", which violate "YYYY-MM-DD".
        if not isinstance(value, str) or not ISO_DATE.fullmatch(value):
            errors["ship_date"] = "must be a date in the form YYYY-MM-DD"
            return None
        try:
            parsed_date = date.fromisoformat(value)
        except ValueError:
            errors["ship_date"] = "is not a real calendar date"
            return None
        if parsed_date < today:
            errors["ship_date"] = "must not be in the past"
            return None
        return parsed_date
    
    
    def parse_quote_request(body: Any, today: date) -> QuoteRequest:
        """Validate every field in one pass and raise ValidationError listing all bad fields."""
        if not isinstance(body, dict):
            raise ValidationError({"body": "must be a JSON object"})
    
        # errors: field_name -> human-readable validation message; collected across all fields.
        errors: Dict[str, str] = {}
        origin = _validate_station(body, "origin", errors)
        destination = _validate_station(body, "destination", errors)
        if origin is not None and origin == destination:
            errors["destination"] = "must differ from origin"
    
        commodity = body.get("commodity")
        if not isinstance(commodity, str) or commodity.strip() == "":
            errors["commodity"] = "must be a non-empty string"
    
        car_count = body.get("car_count")
        # Check isinstance(..., bool) first because bool is a subclass of int in Python.
        if isinstance(car_count, bool) or not isinstance(car_count, int):
            errors["car_count"] = "must be an integer"
        elif not 1 <= car_count <= MAX_CARS:
            errors["car_count"] = f"must be between 1 and {MAX_CARS}"
    
        ship_date = _validate_ship_date(body.get("ship_date"), today, errors)
        if errors:
            raise ValidationError(errors)
        return QuoteRequest(origin, destination, commodity.strip(), car_count, ship_date)
    
    
    # ---- Exact decimal pricing ---------------------------------------------------------------
    
    def to_cents(amount: Decimal) -> Decimal:
        """Round a Decimal dollar amount to 0.01 using commercial round-half-up."""
        return amount.quantize(CENTS, rounding=ROUND_HALF_UP)
    
    
    def price(rate_per_car_mile: Decimal, miles: Decimal, car_count: int,
              surcharge_rate: Decimal) -> Tuple[Decimal, Decimal, Decimal]:
        """Compute (base, surcharge, total) in cents so displayed invoice lines sum to total."""
        # Round each line item once before summing so base + surcharge == total is guaranteed.
        base = to_cents(rate_per_car_mile * miles * car_count)
        surcharge = to_cents(base * surcharge_rate)
        total = base + surcharge
        return base, surcharge, total
    
    
    # ---- Service layer -----------------------------------------------------------------------
    
    def _utc_now() -> datetime:
        return datetime.now(timezone.utc)
    
    
    def _new_id() -> str:
        return uuid.uuid4().hex
    
    
    class QuoteService:
        """Business logic of POST /quotes. Every dependency is injected so unit tests use fakes."""
    
        def __init__(self, tariffs: TariffRepository, routes: RouteService, surcharges: SurchargeService,
                     quotes: QuoteRepository, now: Callable[[], datetime] = _utc_now,
                     new_id: Callable[[], str] = _new_id, ttl: timedelta = QUOTE_TTL) -> None:
            self.tariffs = tariffs
            self.routes = routes
            self.surcharges = surcharges
            self.quotes = quotes
            self.now = now
            self.new_id = new_id
            self.ttl = ttl
    
        def create_quote(self, body: Any) -> Quote:
            # Phase 1: capture one consistent timestamp for both "today" validation and expiry.
            created_at = self.now()
            request = parse_quote_request(body, created_at.date())
    
            # Phase 2: query dependencies from cheapest/local to slowest/remote so unquotable
            # requests fail early without wasting remote RPCs.
            rate = self.tariffs.rate_per_car_mile(request.commodity)
            if rate is None:
                raise UnquotableError("NO_TARIFF", f"no tariff for commodity {request.commodity!r}")
    
            miles = self.routes.distance_miles(request.origin, request.destination)
            if miles is None:
                raise UnquotableError("NO_ROUTE", f"no rail route from {request.origin} to {request.destination}")
    
            surcharge_rate = self.surcharges.surcharge_rate(request.ship_date)
    
            # Phase 3: compute exact Decimal prices and persist the quote before returning its ID.
            base, surcharge, total = price(rate, miles, request.car_count, surcharge_rate)
            expires_at = created_at + self.ttl
            quote = Quote(
                quote_id=self.new_id(),
                request=request,
                miles=miles,
                rate_per_car_mile=rate,
                surcharge_rate=surcharge_rate,
                base=base,
                surcharge=surcharge,
                total=total,
                created_at=created_at,
                expires_at=expires_at,
            )
            self.quotes.save(quote)
            return quote
    
    
    # ---- HTTP adapter: translate domain outcomes to HTTP status codes ------------------------
    
    def quote_to_json(quote: Quote) -> Dict[str, Any]:
        """Serialize Decimal amounts and rates as strings so JSON parsers do not lose cents."""
        return {
            "id": quote.quote_id,
            "origin": quote.request.origin,
            "destination": quote.request.destination,
            "commodity": quote.request.commodity,
            "car_count": quote.request.car_count,
            "ship_date": quote.request.ship_date.isoformat(),
            "miles": str(quote.miles),
            "rate_per_car_mile": str(quote.rate_per_car_mile),
            "surcharge_rate": str(quote.surcharge_rate),
            "base": str(quote.base),
            "surcharge": str(quote.surcharge),
            "total": str(quote.total),
            "currency": "USD",
            "expires_at": quote.expires_at.isoformat(),
        }
    
    
    def handle_post_quotes(service: QuoteService, body: Any) -> Tuple[int, Dict[str, Any]]:
        """Map service outcomes to (HTTP status, JSON response dict) for POST /quotes."""
        try:
            quote = service.create_quote(body)
        except ValidationError as exc:
            return 400, {"error": "INVALID_REQUEST", "fields": exc.errors}
        except UnquotableError as exc:
            return 422, {"error": exc.code, "message": exc.message}
        except DependencyError as exc:
            logger.warning("POST /quotes: dependency failed: %s", exc)
            return 503, {"error": "DEPENDENCY_UNAVAILABLE", "dependency": exc.dependency, "retryable": True}
        except Exception:
            # Log full traceback internally, but never leak internal exception text in a 500 body.
            logger.exception("POST /quotes: unexpected error")
            return 500, {"error": "INTERNAL_ERROR"}
        return 201, quote_to_json(quote)
    
    
    # ---- Part 2: fresh + bounded-stale cache wrapper -----------------------------------------
    
    class CachedSurchargeService(SurchargeService):
        """Wraps a SurchargeService with fresh-hit caching and stale-if-error fallback.
    
        Implements SurchargeService directly so QuoteService needs zero code changes.
        """
    
        def __init__(self, inner: SurchargeService, fresh_for: timedelta, max_stale: timedelta,
                     now: Callable[[], datetime] = _utc_now) -> None:
            self.inner = inner
            self.fresh_for = fresh_for
            self.max_stale = max_stale
            self.now = now
            # _cache maps ship_date -> (cached_rate, fetched_at_timestamp).
            self._cache: Dict[date, Tuple[Decimal, datetime]] = {}
    
        def surcharge_rate(self, ship_date: date) -> Decimal:
            current_time = self.now()
            cached_entry = self._cache.get(ship_date)
    
            # Strict '<': serve immediately without network I/O when strictly younger than fresh_for.
            if cached_entry is not None:
                cached_rate, fetched_at = cached_entry
                if current_time - fetched_at < self.fresh_for:
                    return cached_rate
    
            try:
                fresh_rate = self.inner.surcharge_rate(ship_date)
            except DependencyError:
                # Inclusive '<=': during an outage, fall back to a cached rate up to max_stale old.
                if cached_entry is not None:
                    cached_rate, fetched_at = cached_entry
                    if current_time - fetched_at <= self.max_stale:
                        logger.warning("surcharge service failed; serving stale rate from %s", fetched_at)
                        return cached_rate
                raise
    
            self._cache[ship_date] = (fresh_rate, current_time)
            return fresh_rate
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of QuoteService as a freight clerk at a station counter. First, the clerk checks the customer's form right at the window (parse_quote_request) before picking up any phone. Next, the clerk checks the local rate binder (TariffRepository) before calling remote dispatchers for track mileage (RouteService) and fuel surcharges (SurchargeService), calculates dollars and cents using exact base-10 fixed-point decimal arithmetic (Decimal, which stores exact base-10 digits rather than binary approximations), files the carbon copy (QuoteRepository.save), and hands back the numbered receipt (201). Because every external dependency is passed into QuoteService through dependency injection (supplying abstract interfaces in __init__ rather than creating HTTP/SQL clients inside the class), unit tests run instantaneously with in-memory fakes, and Part 2 can slip a stale-if-error cache (a wrapper that serves fresh values from memory and falls back to slightly older cached values during upstream outages) in front of SurchargeService with zero changes to QuoteService.

A naive single-function endpoint fails in both correctness and scale. Using binary float for money silently drops cents on half-cent boundaries (1.005 * 333 * 3 becomes 1003.9949999999999, rounding to $1003.99 instead of $1004.00); collapsing every error into 500 prevents clients from distinguishing bad JSON (400) from missing routes (422) or retryable outages (503); and calling remote dependencies sequentially without timeouts or caches lets one slow service tie up thousands of concurrent worker threads by Little's law (concurrent in-flight requests equal arrival rate multiplied by average response time).

Walk through Example 1 (DALX -> SEAT, LUMBER, 3 cars, ship_date = "2026-08-15") and its Part 2 cache lifecycle (fresh_for = 5 min, max_stale = 60 min):

  1. Validation checks all 5 fields in memory; tariff lookup returns $1.8375/car-mile; route lookup returns 615 miles; surcharge lookup fetches 0.085 (8.5%) and caches (Decimal("0.085"), t0).
  2. price() computes base = round_half_up(1.8375 * 615 * 3) = $3390.19 (ROUND_HALF_UP rounds 5 or higher away from zero), surcharge = round_half_up(3390.19 * 0.085) = $288.17, and total = $3390.19 + $288.17 = $3678.36. The quote is saved and returned as 201 with string amounts.
  3. At t0 + 3 min, another request for "2026-08-15" hits the fresh cache (3 min < 5 min), skipping the surcharge RPC completely.
  4. At t0 + 20 min, the surcharge service times out (DependencyError); because 20 min <= 60 min, CachedSurchargeService serves 0.085 from cache so quoting stays up. At t0 + 75 min, 75 min > 60 min, so it re-raises DependencyError (503) rather than serving overly stale rates.

Complexity

  • Time per request — O(1) CPU plus dependency I/O: Validating the fixed 5-field payload, running three Decimal multiplications and quantizations on bounded digit counts, and formatting the 13-key JSON response dictionary all perform a constant number of operations per request; wall-clock latency is t_tariff + t_route + t_surcharge + t_save sequentially, dropping to t_tariff + max(t_route, t_surcharge) + t_save when independent RPCs run in parallel (and eliminating t_route / t_surcharge on fresh cache hits).
  • Space — O(1) per request, O(D) for the surcharge cache: Each request allocates one QuoteRequest, one Quote, and one response dictionary of constant size, while CachedSurchargeService._cache stores one (Decimal, datetime) pair per distinct queried ship_date D (at most ~365 entries for a 1-year booking window once past dates are evicted).

Edge cases

  • Booleans or floats passed as car_count (true, 3.0, "3"): Rejected with 400 because isinstance(car_count, bool) is checked before isinstance(car_count, int) (bool subclasses int in Python).
  • Permissive ISO date strings ("20260815", "2026-W33-1", "2026-02-30"): ISO_DATE regex enforces YYYY-MM-DD, and date.fromisoformat rejects impossible calendar dates like February 30.
  • Midnight boundary between validation and expiry: QuoteService.create_quote calls self.now() once and derives today = created_at.date(), so ship_date validation and expires_at never straddle two different UTC days.
  • Same origin and destination ("DALX" -> "DALX"): Rejected at validation (400) before touching TariffRepository or RouteService.
  • Line-item sum consistency (base = 10.004, surcharge_rate = 0.5): Rounding base (10.00) and surcharge (5.00) before adding gives total = 15.00, avoiding the 10.00 + 5.00 != 15.01 invoice mismatch that occurs if the unrounded total (15.006) is rounded independently.
  • Fresh vs stale cache boundaries: age < fresh_for is strict (<) while age <= max_stale is inclusive (<=), and a never-cached ship_date during an outage cleanly raises DependencyError (503).

Common mistakes

  • Using float or Decimal(1.8375) (constructed from a float): Decimal(1.8375) bakes in binary floating-point imprecision; always pass strings (Decimal("1.8375")) or integers.
  • Using Python's round(x, 2) for commercial pricing: Built-in round() uses round-half-to-even (round(Decimal("0.105"), 2) -> 0.10), whereas commercial tariffs normally specify ROUND_HALF_UP (0.11).
  • Returning numbers instead of strings for money in JSON: JSON parsers in browsers (JSON.parse) convert numbers into IEEE-754 doubles, reintroducing binary rounding bugs on the client.
  • Returning quote_id before quotes.save(quote) succeeds: If persistence fails afterward, the client holds a quote ID that returns 404 when booked.
  • Leaking raw exception messages in 500 responses: Exposes SQL table names, connection strings, or internal hostnames to external callers.
  • Unbounded retries without timeouts, circuit breakers, or bulkheads: Three tiers each retrying 3 times turn 1 slow request into 3^3 = 27 downstream calls (a retry storm), while missing bulkheads (isolated connection/thread pools per dependency) let one slow dependency starve the whole service.

Alternative approaches

  • typing.Protocol (structural subtyping) instead of ABC ports: Lets test fakes match TariffRepository or RouteService by method signature alone without explicit subclassing.
  • Shared distributed cache (e.g., Redis) with single-flight locking: Shares cached routes and surcharges across all API pods so a cold pod does not miss, and uses a per-key lock/coalescer so 500 simultaneous cache misses for "2026-08-15" trigger 1 upstream RPC instead of a cache stampede.
  • Asynchronous 202 Accepted quote pipeline: When route/pricing calculations regularly take seconds, POST /quotes writes a PENDING quote and pushes a message to a queue while workers price asynchronously and clients poll GET /quotes/{id} or receive a webhook.

Follow-up questions

  • When fuel surcharges update while cached rates remain active, how do you cap the dollar discrepancy, and which team owns that risk threshold? For a quote with base amount B, serving cached rate r_cached instead of live rate r_live changes the total by B * |r_live - r_cached| (plus at most $0.01 of rounding) — for example, on $3,390.19 base, a 0.5% surcharge move (8.5% to 9.0%) is $16.95. You bound that dollar exposure technically by capping max_stale based on the maximum historical rate change per hour (or eliminating staleness entirely by publishing surcharge schedules ahead of their effective timestamp and invalidating on publish), and recording surcharge_rate plus surcharge_fetched_at on every saved Quote row for audit. Whether honoring a $17 under-quote beats turning away a freight booking with 503 is a commercial decision owned by Pricing/Finance, informed by engineering's outage-rate and dollar-drift metrics.
  • How can the API avoid creating multiple quote records if a caller re-sends a timed-out POST request? Require an idempotency key (a unique client-generated token sent in an Idempotency-Key header per logical quote attempt), stored in a database table with a unique constraint on (client_id, idempotency_key) alongside a hash of the request payload, a status (IN_PROGRESS or COMPLETED), a short lease_expires_at timestamp, and the resulting quote_id. Before pricing, atomically INSERT the (client_id, idempotency_key) row as IN_PROGRESS: if a duplicate retry arrives with a different payload hash, return 422; if the existing row is COMPLETED, return the already-saved 201 quote without re-pricing; if it is IN_PROGRESS with an active lease, return 409 Conflict (or wait briefly) so two concurrent retries never double-insert; and once pricing finishes, write the Quote row and mark the idempotency row COMPLETED in a single database transaction.
  • Suppose an upstream service experiences a 60-minute outage: how does the quote endpoint respond throughout that window, and how does it transition back when service returns? A circuit breaker (an automatic switch that opens once failures cross a threshold so calls fail in sub-millisecond time instead of blocking on timeouts) trips open for the broken dependency: for SurchargeService or RouteService, keys cached within max_stale continue returning 201 quotes (tagged internally with stale_fallback=True), while uncached keys or expired stale entries fast-fail with 503 + Retry-After (or 202 Accepted if async quoting is enabled), and health/readiness probes ignore optional downstream outages so the load balancer does not pull healthy API pods out of rotation. When the dependency recovers, half-open probe requests succeed and close the circuit breaker, jittered Retry-After intervals spread returning client traffic smoothly, single-flight cache refreshes repopulate hot keys without a thundering herd, and any queued PENDING quotes drain under rate-limited worker concurrency.

Follow-up questions

Similar questions

More Bnsf interview questions

All 4 Bnsf questions →