Build and Scale a Freight Quote Service with Slow Dependencies
System DesignModel answerLast updated
Implement service logic for a freight pricing API, then architect for high traffic when external services are slow.
You're building a pricing service for a rail freight company. The service exposes a REST API that calculates shipping quotes by combining data from multiple sources: a local database, a routing service, and a pricing surcharge service.
API Specification
POST /quotes accepts a JSON request:
{
"origin": "CHI",
"destination": "LAX",
"commodity": "grain",
"car_count": 15,
"ship_date": "2026-12-15"
}
Pricing logic:
- Look up the tariff rate (dollars per car per mile) for the commodity in your database
- Call the routing service to get the rail distance between stations
- Call the surcharge service to get the date-based multiplier
- Calculate:
base_price = tariff_rate × distance × car_count - Calculate:
total_price = base_price × (1 + surcharge_rate) - Store the quote with an expiration timestamp and return it with a unique ID
Your Task
Part 1 (30 minutes): Write the service-layer implementation. Your code should handle validation, orchestrate the dependencies, compute prices accurately, and be testable in isolation. Include a few unit tests.
Part 2 (30 minutes): Design an architecture that keeps this endpoint fast and available under two pressures:
- High request volume (thousands of requests per second)
- Slow or unreliable dependency services (routing and surcharge services may take seconds to respond or fail)
Address caching strategies, timeout and failure handling, synchronous vs. asynchronous quote patterns, scaling approaches, and monitoring.
Expected Deliverables
- Clean, testable service code with dependency injection
- Input validation and clear error responses
- Accurate decimal arithmetic for money
- Architectural diagram and explanation covering reliability patterns, caching, and scaling
- Discussion of trade-offs between price accuracy and availability
Hints
Hint 1
Think about which dependency calls can happen in parallel, and which data might be cacheable for minutes or hours without hurting accuracy.
Hint 2
Consider whether every quote request must block on all three dependencies, or if you can return a quote ID immediately and compute asynchronously.
Hint 3
Circuit breakers and timeouts protect your service from cascading failures when dependencies are slow, but you'll also need a fallback strategy for cached or degraded quotes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Service Implementation
Architecture and Testability
The key is separating concerns through dependency injection. The service layer should not know about HTTP, databases, or network clients directly.
from decimal import Decimal
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Protocol
import uuid
@dataclass
class QuoteRequest:
origin: str
destination: str
commodity: str
car_count: int
ship_date: datetime
@dataclass
class Quote:
id: str
total_price: Decimal
base_price: Decimal
expires_at: datetime
class TariffRepository(Protocol):
def get_rate(self, commodity: str) -> Decimal | None: ...
class RouteService(Protocol):
def get_distance(self, origin: str, destination: str) -> int | None: ...
class SurchargeService(Protocol):
def get_surcharge_rate(self, ship_date: datetime) -> Decimal: ...
class QuoteRepository(Protocol):
def save(self, quote: Quote) -> None: ...
class QuoteService:
def __init__(
self,
tariff_repo: TariffRepository,
route_service: RouteService,
surcharge_service: SurchargeService,
quote_repo: QuoteRepository,
quote_ttl_hours: int = 24
):
self.tariff_repo = tariff_repo
self.route_service = route_service
self.surcharge_service = surcharge_service
self.quote_repo = quote_repo
self.quote_ttl_hours = quote_ttl_hours
def create_quote(self, req: QuoteRequest) -> Quote:
# Validation
if req.car_count <= 0:
raise ValueError("car_count must be positive")
if req.ship_date < datetime.now():
raise ValueError("ship_date cannot be in the past")
# Fetch tariff rate
tariff_rate = self.tariff_repo.get_rate(req.commodity)
if tariff_rate is None:
raise ValueError(f"Unknown commodity: {req.commodity}")
# Fetch distance (blocking)
distance = self.route_service.get_distance(req.origin, req.destination)
if distance is None:
raise ValueError(f"No route from {req.origin} to {req.destination}")
# Fetch surcharge (blocking)
surcharge_rate = self.surcharge_service.get_surcharge_rate(req.ship_date)
# Calculate with exact decimal arithmetic
base_price = tariff_rate * Decimal(distance) * Decimal(req.car_count)
total_price = base_price * (Decimal("1.0") + surcharge_rate)
# Round to cents
total_price = total_price.quantize(Decimal("0.01"))
base_price = base_price.quantize(Decimal("0.01"))
quote = Quote(
id=str(uuid.uuid4()),
total_price=total_price,
base_price=base_price,
expires_at=datetime.now() + timedelta(hours=self.quote_ttl_hours)
)
self.quote_repo.save(quote)
return quote
Unit Tests
import pytest
from unittest.mock import Mock
def test_successful_quote():
tariff_repo = Mock(spec=TariffRepository)
tariff_repo.get_rate.return_value = Decimal("2.50")
route_service = Mock(spec=RouteService)
route_service.get_distance.return_value = 1200
surcharge_service = Mock(spec=SurchargeService)
surcharge_service.get_surcharge_rate.return_value = Decimal("0.15")
quote_repo = Mock(spec=QuoteRepository)
service = QuoteService(tariff_repo, route_service, surcharge_service, quote_repo)
req = QuoteRequest("CHI", "LAX", "grain", 10, datetime(2026, 12, 15))
quote = service.create_quote(req)
assert quote.base_price == Decimal("30000.00") # 2.50 * 1200 * 10
assert quote.total_price == Decimal("34500.00") # 30000 * 1.15
quote_repo.save.assert_called_once()
def test_unknown_commodity():
tariff_repo = Mock(spec=TariffRepository)
tariff_repo.get_rate.return_value = None
service = QuoteService(tariff_repo, Mock(), Mock(), Mock())
req = QuoteRequest("CHI", "LAX", "unobtanium", 5, datetime(2026, 12, 15))
with pytest.raises(ValueError, match="Unknown commodity"):
service.create_quote(req)
Common mistakes: Using floats for money (precision errors), blocking on dependencies serially when they could run in parallel, no validation, tight coupling that prevents testing.
Part 2: Architecture for Scale and Reliability
1. Remove Dependencies from the Critical Path
Parallel calls: Route and surcharge lookups are independent—fetch them concurrently to cut latency in half.
Caching:
- Route distances rarely change. Cache in Redis with a 24-hour TTL. A stale distance is acceptable.
- Surcharge rates are date-based and predictable. Pre-fetch the next 30 days of rates hourly and cache them.
- Tariff rates are in your database already. Add an in-memory cache (e.g., Caffeine, Redis) with 1-hour TTL.
With aggressive caching, 95% of requests hit only your cache and database—no external service calls.
2. Protect Against Slow Dependencies
Timeouts: Set aggressive timeouts (200–500ms) on route and surcharge services. Most requests should be fast; slow ones shouldn't drag down the entire system.
Circuit breakers: After N consecutive failures or timeouts, open the circuit for 30 seconds. Serve cached or fallback quotes instead of hammering a failing service.
Bulkheads: Isolate dependency calls in separate thread pools. A slow route service won't starve threads needed for surcharge calls or database access.
Fallback strategy:
- If route service fails but we have a cached distance, use it and flag the quote as "estimated."
- If surcharge service fails, apply a default 10% surcharge and flag the quote.
- Return a 503 only if we cannot compute any reasonable quote.
3. Synchronous vs. Asynchronous Quotes
Synchronous (current design): Client waits for the full quote. Good for low latency when caching works, but blocks under load.
Asynchronous alternative:
POST /quotesvalidates input, returns{"quote_id": "abc123", "status": "pending"}immediately (< 50ms).- A background worker fetches dependencies, computes the price, and writes the quote.
- Client polls
GET /quotes/abc123or receives a webhook when ready.
Trade-off: Async adds complexity and requires clients to handle polling, but keeps the API responsive under any dependency latency. Use async if P99 latency matters more than simplicity.
4. Scaling the Service
Horizontal scaling: The service layer is stateless—run many instances behind a load balancer.
Database scaling:
- Read replicas for tariff lookups (read-heavy).
- Partition the quotes table by
created_atorquote_idfor write scaling. - Use a write-through cache (Redis) for recent quotes to offload reads.
Rate limiting: Protect against abusive clients with per-API-key rate limits (e.g., 100 req/s per key).
Load shedding: Under extreme load, reject requests with 503 before they enter the system. Better to fail fast than time out slowly.
5. Monitoring and Metrics
- Latency: P50, P95, P99 for the endpoint and each dependency
- Error rates: 4xx (client errors) vs. 5xx (server/dependency failures)
- Cache hit rate: Route and surcharge cache effectiveness
- Circuit breaker state: Open/closed for each dependency
- Queue depth: For async processing, track backlog size
Architecture Diagram
┌─────────┐
│ Client │
└────┬────┘
│
▼
┌─────────────────┐
│ Load Balancer │
└────┬────────────┘
│
▼
┌──────────────────────────────────┐
│ Quote Service (N instances) │
│ ┌──────────────────────────┐ │
│ │ Circuit Breakers │ │
│ │ Timeouts (500ms) │ │
│ └──────────────────────────┘ │
└──┬────────┬──────────┬──────────┘
│ │ │
▼ ▼ ▼
┌──────┐ ┌─────────┐ ┌──────────┐
│Redis │ │ Route │ │Surcharge │
│Cache │ │ Service │ │ Service │
└──────┘ └─────────┘ └──────────┘
│
▼
┌──────────────┐
│ PostgreSQL │
│ (replicated) │
└──────────────┘
Key Trade-Offs
- Accuracy vs. availability: Cached routes/surcharges may be slightly stale, but the service stays fast and available. For critical quotes, offer a "refresh" flag that bypasses cache.
- Sync vs. async: Synchronous is simpler; asynchronous handles load better but complicates clients.
- Cost: Aggressive caching and horizontal scaling add infrastructure cost but are cheaper than losing customers to slow responses.
This architecture handles thousands of requests per second even when dependencies are slow, by removing them from the critical path, failing fast with timeouts and circuit breakers, and providing degraded but useful quotes under failure conditions.