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)andQuote(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), andDependencyError(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) -> DecimalQuoteRepository.save(quote: Quote) -> None
Implement the following functions and classes:
Part 1 — Validation, Exact Decimal Pricing, Service Layer, and HTTP Mapping
parse_quote_request(body: Any, today: date) -> QuoteRequest:- If
bodyis not adict, raiseValidationError({"body": ...}). - Validate all five fields in a single pass so every invalid field name appears in
ValidationError.errors:originanddestination: strings matchingSTATION_CODE(3–10uppercase ASCII letters or digits). When both are valid strings andorigin == destination, record an error on"destination".commodity: string containing at least one non-whitespace character (storecommodity.strip()onQuoteRequest).car_count: exact integer (int, rejectingbool,float, andstr) 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).
- If
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) toDecimal("0.01"):baseroundsrate_per_car_mile * miles * car_countto cents.surchargeroundsbase * surcharge_rateto cents.total = base + surcharge(sum of the rounded cent amounts).
- Compute
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 validatebodyagainstcreated_at.date(). - Query
tariffs.rate_per_car_mile(commodity)first; ifNone, raiseUnquotableError("NO_TARIFF", ...)before callingroutesorsurcharges. - Query
routes.distance_miles(origin, destination)next; ifNone, raiseUnquotableError("NO_ROUTE", ...)before callingsurcharges. - Fetch
surcharges.surcharge_rate(ship_date), compute(base, surcharge, total), setexpires_at = created_at + self.ttl, constructQuotewithquote_id = self.new_id(), persist viaquotes.save(quote)before returning, and returnquote. AllowDependencyErrorto propagate.
- Read
- Constructor accepts
quote_to_json(quote: Quote) -> Dict[str, Any]andhandle_post_quotes(service: QuoteService, body: Any) -> Tuple[int, Dict[str, Any]]:quote_to_jsonformats"id","origin","destination","commodity","car_count","ship_date"("YYYY-MM-DD"), stringifiedDecimalfields ("miles","rate_per_car_mile","surcharge_rate","base","surcharge","total"),"currency": "USD", and"expires_at"(ISO-8601 timestamp).handle_post_quotesmaps 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.
- Success ->
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_datehas a cached entry whose agenow() - fetched_atis strictly less thanfresh_for, return the cached rate immediately without callinginner. - Otherwise invoke
inner.surcharge_rate(ship_date). On success, update the cache atnow()and return the new rate. - If
innerraisesDependencyError, return the cached rate whenship_dateis cached andnow() - fetched_at <= max_stale; otherwise re-raiseDependencyError.
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 status400witherror == "INVALID_REQUEST"andfieldscontaining 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 callingRouteServiceorSurchargeService. - Outage fallback (
CachedSurchargeServicewithfresh_for=5 min,max_stale=60 min): After cachingDecimal("0.085")att = 0, a lookup att = +3 minskipsinner; ifinnerraisesDependencyError("surcharge", "timeout")att = +20 min, the wrapper servesDecimal("0.085")(20 <= 60), whereas att = +75 min(75 > 60) it re-raisesDependencyErrorsohandle_post_quotesreturns(503, {"error": "DEPENDENCY_UNAVAILABLE", "dependency": "surcharge", "retryable": True}).
Constraints
- Never use binary
floatarithmetic for monetary calculations; use PythonDecimalwithROUND_HALF_UPtoDecimal("0.01"). 1 <= car_count <= 500, andboolvalues (True/False) must be rejected.- Station codes match
^[A-Z0-9]{3,10}$withorigin != destination. ship_datemust matchYYYY-MM-DDand satisfyship_date >= today.fresh_for >= timedelta(0)andmax_stale >= fresh_for.
Step-by-step walkthrough
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
QuoteRepositorybefore returning201, and stays valid for24hours (QUOTE_TTL). - Validation rules:
originanddestinationare 3–10 uppercase alphanumeric characters and must differ;commodityis non-empty text;car_countis an integer in1..500;ship_dateisYYYY-MM-DDand not earlier than today (UTC). - Money: Exact base-10
Decimalarithmetic 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)400INVALID_REQUEST(withfields)No — fix the payload Valid request, but no tariff or rail route exists 422NO_TARIFF/NO_ROUTENo — business rule Downstream service or DB failed / timed out 503DEPENDENCY_UNAVAILABLEYes — with backoff Unexpected bug ( KeyError,ZeroDivisionError)500INTERNAL_ERROR(no internals leaked)Maybe later - Dependency failures: Part 1 fails closed with
Separate HTTP, business logic, and external ports
To make
POST /quotesunit-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 fakesEven the wall clock (
now) and ID generator (new_id) are injected functions with sensible defaults, allowing unit tests to freeze time and assert exactexpires_attimestamps. Notice also how the ports separate normal "not found" outcomes (None) from infrastructure failures (DependencyError).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:
isinstance(True, int)isTruebecauseboolinherits fromintin Python. Always rejectisinstance(car_count, bool)first, or"car_count": truesilently prices 1 railcar!- Python 3.11+
date.fromisoformatis overly permissive: it accepts"20260815"and ISO week strings like"2026-W33-1". Checking a strictYYYY-MM-DDregex first pins the exact API format, anddate.fromisoformatthen 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)Compute money with exact `Decimal` and line-item rounding
IEEE-754 binary
floatcannot 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
Decimalvalues from strings (Decimal("1.8375")), roundbaseonce to$0.01withROUND_HALF_UP, roundsurcharge = base * surcharge_rateonce to$0.01, and settotal = base + surchargeso the displayed invoice lines always add up tototal: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.36CENTS = 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, totalOrchestrate `QuoteService` and map HTTP responses
Inside
QuoteService.create_quote, we order operations from cheapest to most expensive:- Validate input in memory (
0I/O). - Read the commodity tariff from the local DB (
NO_TARIFFstops before any remote RPC). - Call
RouteService(NO_ROUTEstops before callingSurchargeService). - Call
SurchargeService, compute exactDecimalamounts, andsave(quote)before returning so a client never receives aquote_idthat failed to persist.
In the HTTP adapter, all
Decimalvalues are serialized as JSON strings ("3678.36") so JavaScript or Python clients do not parse them into binary floats, and unexpected exceptions return a generic500body 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)- Validate input in memory (
Part 2: shorten the critical path with parallelism and caching
Suppose median call times are: tariff DB
5 ms, route service120 ms, surcharge service80 ms, quote insert10 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- Parallelize independent RPCs: Once the tariff exists,
distance_milesandsurcharge_ratedo not depend on each other, so running them concurrently cuts latency fromroute + surchargetomax(route, surcharge). Note that parallelism alone does not eliminate tail spikes: if each service has an independent1%chance of stalling,1 - 0.99^2 = 1.99%of requests still wait on a slow call. - 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!). - Implement fresh + stale-if-error caching:
CachedSurchargeServicewrapsSurchargeServiceusing two time windows:- Fresh (
age < fresh_for, e.g.,< 5 min): Return immediately from memory with0network calls. - Stale-if-error (
fresh_for <= age <= max_stale, e.g.,<= 60 min): Tryinner.surcharge_ratefirst; if it raisesDependencyError, serve the cached rate instead of returning503. Older thanmax_stale, re-raiseDependencyErrorso pricing error stays bounded.
- Fresh (
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- Parallelize independent RPCs: Once the tariff exists,
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 requestsWithout 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 /quotesan overall budget (say400 ms) and cap each RPC (300 msmax). - 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 outage3x–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 msand triggers stale-cache fallback immediately. - Bulkheads (separate bounded connection/thread pools per dependency, named after watertight ship compartments): Ensures a stalled
RouteServicepool cannot starveTariffRepositoryorQuoteRepository. - Load shedding & asynchronous quotes: Shed excess load early with
503+Retry-Afterwhen queue depth spikes. If dependencies frequently take multiple seconds, offer an asynchronous quote flow:POST /quotesvalidates, writes aPENDINGrow, enqueues a job, and immediately returns202 AcceptedwithLocation: /quotes/{id}while background workers compute the price and clients pollGET /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- Per-call timeouts from a shared request deadline: Give
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
tariffsfrom in-memory caches + read replicas; keepquotesinserts lean on the primary, partitioned bycreated_atday so expired 24-hour quotes can be dropped instantaneously by dropping old partitions instead of running expensiveDELETEscans. - Key metrics to alert on:
- Endpoint: RPS,
p50/p95/p99latency, status breakdown (201,400,422,503,500). - Dependencies: per-service
p99latency, timeout rate, retry rate, circuit-breaker open transitions. - Caches: fresh hit ratio,
stale_served_on_errorcounter, age of cached entries. - Saturation: in-flight requests, bulkhead pool utilization, DB connection pool wait time, queue lag (async mode).
- Endpoint: RPS,
Put it all together
Here is the complete
solution.pycontaining validation, exactDecimalpricing,QuoteService, the HTTP adapter, andCachedSurchargeService: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):
- Validation checks all 5 fields in memory; tariff lookup returns
$1.8375/car-mile; route lookup returns615miles; surcharge lookup fetches0.085(8.5%) and caches(Decimal("0.085"), t0). price()computesbase = round_half_up(1.8375 * 615 * 3) = $3390.19(ROUND_HALF_UProunds5or higher away from zero),surcharge = round_half_up(3390.19 * 0.085) = $288.17, andtotal = $3390.19 + $288.17 = $3678.36. The quote is saved and returned as201with string amounts.- At
t0 + 3 min, another request for"2026-08-15"hits the fresh cache (3 min < 5 min), skipping the surcharge RPC completely. - At
t0 + 20 min, the surcharge service times out (DependencyError); because20 min <= 60 min,CachedSurchargeServiceserves0.085from cache so quoting stays up. Att0 + 75 min,75 min > 60 min, so it re-raisesDependencyError(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
Decimalmultiplications 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 ist_tariff + t_route + t_surcharge + t_savesequentially, dropping tot_tariff + max(t_route, t_surcharge) + t_savewhen independent RPCs run in parallel (and eliminatingt_route/t_surchargeon fresh cache hits). - Space — O(1) per request, O(D) for the surcharge cache: Each request allocates one
QuoteRequest, oneQuote, and one response dictionary of constant size, whileCachedSurchargeService._cachestores one(Decimal, datetime)pair per distinct queriedship_dateD(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 with400becauseisinstance(car_count, bool)is checked beforeisinstance(car_count, int)(boolsubclassesintin Python). - Permissive ISO date strings (
"20260815","2026-W33-1","2026-02-30"):ISO_DATEregex enforcesYYYY-MM-DD, anddate.fromisoformatrejects impossible calendar dates like February 30. - Midnight boundary between validation and expiry:
QuoteService.create_quotecallsself.now()once and derivestoday = created_at.date(), soship_datevalidation andexpires_atnever straddle two different UTC days. - Same
originanddestination("DALX"->"DALX"): Rejected at validation (400) before touchingTariffRepositoryorRouteService. - Line-item sum consistency (
base = 10.004,surcharge_rate = 0.5): Roundingbase(10.00) andsurcharge(5.00) before adding givestotal = 15.00, avoiding the10.00 + 5.00 != 15.01invoice mismatch that occurs if the unrounded total (15.006) is rounded independently. - Fresh vs stale cache boundaries:
age < fresh_foris strict (<) whileage <= max_staleis inclusive (<=), and a never-cachedship_dateduring an outage cleanly raisesDependencyError(503).
Common mistakes
- Using
floatorDecimal(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-inround()uses round-half-to-even (round(Decimal("0.105"), 2)->0.10), whereas commercial tariffs normally specifyROUND_HALF_UP(0.11). - Returning numbers instead of strings for money in JSON: JSON parsers in browsers (
JSON.parse) convert numbers into IEEE-754doubles, reintroducing binary rounding bugs on the client. - Returning
quote_idbeforequotes.save(quote)succeeds: If persistence fails afterward, the client holds a quote ID that returns404when booked. - Leaking raw exception messages in
500responses: 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 = 27downstream 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 ofABCports: Lets test fakes matchTariffRepositoryorRouteServiceby 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 Acceptedquote pipeline: When route/pricing calculations regularly take seconds,POST /quoteswrites aPENDINGquote and pushes a message to a queue while workers price asynchronously and clients pollGET /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 rater_cachedinstead of live rater_livechanges the total byB * |r_live - r_cached|(plus at most$0.01of rounding) — for example, on$3,390.19base, a0.5%surcharge move (8.5%to9.0%) is$16.95. You bound that dollar exposure technically by cappingmax_stalebased 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 recordingsurcharge_rateplussurcharge_fetched_aton every savedQuoterow for audit. Whether honoring a$17under-quote beats turning away a freight booking with503is 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-Keyheader 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, astatus(IN_PROGRESSorCOMPLETED), a shortlease_expires_attimestamp, and the resultingquote_id. Before pricing, atomicallyINSERTthe(client_id, idempotency_key)row asIN_PROGRESS: if a duplicate retry arrives with a different payload hash, return422; if the existing row isCOMPLETED, return the already-saved201quote without re-pricing; if it isIN_PROGRESSwith an active lease, return409 Conflict(or wait briefly) so two concurrent retries never double-insert; and once pricing finishes, write theQuoterow and mark the idempotency rowCOMPLETEDin 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
SurchargeServiceorRouteService, keys cached withinmax_stalecontinue returning201quotes (tagged internally withstale_fallback=True), while uncached keys or expired stale entries fast-fail with503+Retry-After(or202 Acceptedif 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, jitteredRetry-Afterintervals spread returning client traffic smoothly, single-flight cache refreshes repopulate hot keys without a thundering herd, and any queuedPENDINGquotes drain under rate-limited worker concurrency.
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?
- How can the API avoid creating multiple quote records if a caller re-sends a timed-out POST request?
- 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?
Similar questions
- Plain-Text Notes CRUD API and Black-Box Testing
- Optimal Train Dispatch Under Yard Limits
- Minimum Removals for Pairwise Bridge Load
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination