Resilient Caching Client for Daily Equity Prices
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Build a Python client StockDataClient that downloads, validates, deduplicates, and caches daily opening and closing equity prices from an unreliable, cursor-paginated upstream feed.
Classes and Signatures
from typing import Callable, Dict, List
import time
from datetime import date
from decimal import Decimal
class ApiError(Exception):
def __init__(self, status_code: int, message: str = "") -> None: ...
class StockDataClient:
def __init__(
self,
fetch_page: Callable,
max_attempts: int = 3,
base_delay: float = 0.5,
sleep: Callable[[float], None] = time.sleep,
) -> None: ...
def get_price_history(
self, ticker: str, start_date: date, end_date: date
) -> List[Dict]: ...
Behavioral Rules
- Paginated upstream callable:
fetch_page(ticker, start_date, end_date, page_token)returns a dictionary shaped as{"data": [...], "next_page_token": token_or_none}.- Start each range download with
page_token=Noneand continue fetching subsequent pages untilnext_page_tokenisNoneor"". - If the upstream feed ever repeats a non-empty
next_page_tokenwithin the same range download, raiseRuntimeErrorrather than looping indefinitely.
- Retry policy and failure atomicity:
fetch_pagemay raiseApiError(status_code, message)for HTTP failures, orTimeoutError/ConnectionErrorwhen a socket fails.- Treat
TimeoutError,ConnectionError, andApiErrorwith500 <= status_code <= 599as transient errors. Retry a failing page request up tomax_attemptstotal tries; after thek-th failure (1 <= k < max_attempts), pause by callingsleep(base_delay * (2 ** (k - 1)))before retrying that same page. Re-raise the error oncemax_attemptstries fail. - Non-transient exceptions (such as
ApiError(404)or unexpected runtime errors) must propagate immediately without sleeping or retrying. - If any page in a range download ultimately fails, discard partial results from earlier pages so no half-loaded range enters the cache.
- Record parsing and deduplication:
- Valid raw records are dicts with
"date"(an ISO"YYYY-MM-DD"string,date, ordatetime),"open", and"close". - Convert
"open"and"close"into positive, finitedecimal.Decimalinstances without binary floating-point rounding artifacts (convertfloatvalues viastr(...)first; rejectbool,NaN,Infinity, non-positive numbers, and unparseable values). - Skip malformed records and any stray records whose date falls outside the requested sub-range. When multiple valid records share a date, retain the first valid record encountered and ignore later copies.
- Valid raw records are dicts with
- Full calendar output and gap-aware caching:
- Return one dictionary per calendar date from
start_datethroughend_dateinclusive, ordered chronologically from earliest to latest:- Valid trading day:
{"date": day, "open": Decimal(...), "close": Decimal(...), "status": "ok"} - Day with no valid record (weekends, holidays, or empty feed responses):
{"date": day, "open": None, "close": None, "status": "missing"}
- Valid trading day:
- Normalize
tickerby trimming whitespace and uppercasing so"orcl"and"ORCL"share cached entries and send"ORCL"upstream. - Cache both present prices and known
"missing"dates per(ticker, date)so subsequent overlapping calls request only contiguous uncached date intervals.
- Return one dictionary per calendar date from
- Argument validation:
- Raise
ValueErrorin__init__ifmax_attempts < 1(orbase_delay < 0). - Raise
ValueErroringet_price_historyiftickeris not a non-blank string or ifstart_date > end_date. - Raise
TypeErrorunless bothstart_dateandend_datearedatetime.dateobjects (datetime.datetimeinstances must be rejected).
- Raise
Examples
Example 1
# Upstream feed holds ORCL records:
# 2024-04-04 -> open "124.10", close "125.85"
# 2024-04-05 -> open "126.00", close "124.75"
client.get_price_history("ORCL", date(2024, 4, 4), date(2024, 4, 5))
Output:
[
{"date": date(2024, 4, 4), "open": Decimal("124.10"), "close": Decimal("125.85"), "status": "ok"},
{"date": date(2024, 4, 5), "open": Decimal("126.00"), "close": Decimal("124.75"), "status": "ok"},
]
Explanation: Both calendar days in [2024-04-04, 2024-04-05] have valid records, so both rows return status="ok" with exact Decimal prices.
Example 2
# Continuing on the same client instance from Example 1.
# For 2024-04-06..2024-04-08, the feed returns two records on Monday 2024-04-08:
# {"date": "2024-04-08", "open": "125.20", "close": "127.40"}
# {"date": "2024-04-08", "open": "999.00", "close": "999.00"}
# and no records for Saturday 2024-04-06 or Sunday 2024-04-07.
client.get_price_history("orcl", date(2024, 4, 5), date(2024, 4, 8))
Output:
[
{"date": date(2024, 4, 5), "open": Decimal("126.00"), "close": Decimal("124.75"), "status": "ok"},
{"date": date(2024, 4, 6), "open": None, "close": None, "status": "missing"},
{"date": date(2024, 4, 7), "open": None, "close": None, "status": "missing"},
{"date": date(2024, 4, 8), "open": Decimal("125.20"), "close": Decimal("127.40"), "status": "ok"},
]
Explanation: "orcl" normalizes to "ORCL". Because 2024-04-05 was already fetched in Example 1, the client queries fetch_page only for (date(2024, 4, 6), date(2024, 4, 8)). Weekend dates 04-06 and 04-07 become "missing" (and are negatively cached), while 04-08 keeps the first valid record.
Constraints
- Valid date intervals span up to 5 years (
1 <= (end_date - start_date).days + 1 <= 1827). "data"in a page response may be empty,None, unsorted, or contain duplicate dates and malformed entries across page boundaries.max_attempts >= 1andbase_delay >= 0for valid client configurations.
Step-by-step walkthrough
Restate the problem and clarify the contract
We need to build
StockDataClient, whoseget_price_history(ticker, start_date, end_date)method returns one dictionary per calendar day fromstart_datethroughend_dateinclusive, sorted from oldest to newest. Under the hood, prices come from a slow, paginated, and occasionally unreliable external API.An open-ended engineering prompt leaves several interface details implicit. In an interview, state these contracts clearly before writing code:
- Dependency injection for testability.
StockDataClient(fetch_page, max_attempts=3, base_delay=0.5, sleep=time.sleep)acceptsfetch_pageandsleepas arguments so tests can simulate API pages and network failures instantly without real network sockets or real waiting. - How errors arrive.
fetch_pageraisesApiError(status_code)for HTTP errors andTimeoutErrororConnectionErrorwhen the network drops. - Row shape for trading days vs. missing days. Every calendar date gets a row with four keys:
- Present:
{'date': day, 'open': Decimal(...), 'close': Decimal(...), 'status': 'ok'} - Absent (such as weekends, market holidays, or missing API records):
{'date': day, 'open': None, 'close': None, 'status': 'missing'}
- Present:
- Deduplication rule. If the API returns multiple records for the same date, keep the first valid record and ignore later duplicates.
- Input validation. Reject blank tickers or
start_date > end_datewithValueError, and reject non-datevalues (includingdatetime.datetime) withTypeError. Normalize tickers to uppercase so'orcl'and'ORCL'share the same cache.
- Dependency injection for testability.
Why a naive fetch-every-time loop falls short
The most obvious implementation calls
fetch_pagefromstart_datetoend_dateon every call, puts the returned dates in a dictionary, and loops over the calendar range. That works once on a clean network, but breaks down in three ways:- Redundant network calls. Asking for January 1–31 right after asking for January 10–20 downloads those 11 overlapping days all over again. Worse, if you only cache dates that returned prices, every weekend or holiday inside a cached range looks "missing" and triggers fresh API calls forever.
- Fragile pagination. A 5-year range (~1,826 days) can span dozens of pages. Without bounded retries, a single temporary HTTP 503 on page 12 aborts the entire call.
- Floating-point rounding. Parsing
"125.85"or0.1through binaryfloatintroduces tiny representation errors (0.1 + 0.2 == 0.30000000000000004), which corrupts financial calculations.
Because 5 years is at most ~1,827 calendar days, looping over individual
dateobjects in Python takes less than a millisecond. The real bottleneck is the network, so we will add exact Decimal parsing, per-page retries with exponential backoff, and a gap-aware(ticker, date)cache.Parse prices into exact Decimals without float noise
Binary floating-point numbers store fractions in base 2, where
0.1has no exact finite representation. Python'sdecimal.Decimalstores numbers in base 10, soDecimal("0.1") + Decimal("0.2") == Decimal("0.3")exactly.One trap catches many Python developers: calling
Decimal(0.1)directly on afloatcopies the binary error (Decimal('0.1000000000000000055511151231257827021181583404541015625')). Converting thefloatwithstr(value)first produces'0.1', giving the exactDecimal('0.1').We also guard against three edge cases in malformed API payloads: -
isinstance(value, bool): in Python,boolis a subclass ofint(True == 1), so we reject booleans first. -price.is_finite()beforeprice <= 0: comparingDecimal('NaN') <= 0raisesInvalidOperationinstead of returningFalse, so we check finiteness first. - Positive prices only: zero or negative stock prices are rejected as invalid records.from typing import Optional, Tuple from datetime import date, datetime from decimal import Decimal, InvalidOperation def parse_price(value: object) -> Optional[Decimal]: """Convert raw API price input into a positive, finite Decimal, or None if invalid.""" # Reject bool explicitly because bool is a subclass of int in Python (True == 1) if isinstance(value, bool): return None # Convert float via str() first: str(0.1) is '0.1', whereas Decimal(0.1) keeps binary float noise if isinstance(value, float): text = str(value) elif isinstance(value, (str, int, Decimal)): text = str(value).strip() else: return None try: price = Decimal(text) except InvalidOperation: return None # Check is_finite() BEFORE price <= 0 because comparing Decimal('NaN') <= 0 raises InvalidOperation if not price.is_finite() or price <= 0: return None return price def parse_day(value: object) -> Optional[date]: """Convert an ISO 'YYYY-MM-DD' string, date, or datetime into a date object, or None.""" # Check datetime before date because datetime is a subclass of date if isinstance(value, datetime): return value.date() if isinstance(value, date): return value if isinstance(value, str): try: return date.fromisoformat(value.strip()) except ValueError: return None return None def parse_record(record: object) -> Optional[Tuple[date, Decimal, Decimal]]: """Extract (day, open_price, close_price) from one raw API dict, or None if malformed.""" if not isinstance(record, dict): return None day = parse_day(record.get("date")) open_price = parse_price(record.get("open")) close_price = parse_price(record.get("close")) if day is None or open_price is None or close_price is None: return None return day, open_price, close_priceRetry transient failures per page with exponential backoff
Not every error deserves a retry: - Transient errors (temporary glitches that often succeed moments later):
TimeoutError,ConnectionError, and HTTP500–599server errors. - Permanent errors (problems that will fail the exact same way every time): HTTP400–499client errors like404 Not Found, or programming bugs likeKeyError. Retrying these only wastes time, so we re-raise them immediately.When a transient error happens, exponential backoff doubles the pause after each failed attempt (
base_delay * 2**(attempt - 1)), giving an overloaded server breathing room to recover:max_attempts = 3, base_delay = 0.5s Attempt 1 (t = 0.0s) ──► HTTP 503 ──► sleep 0.5s (0.5 * 2^0) Attempt 2 (t = 0.5s) ──► Timeout ──► sleep 1.0s (0.5 * 2^1) Attempt 3 (t = 1.5s) ──► HTTP 503 ──► attempt == 3: stop and re-raise! (no extra sleep)Notice that we retry one page using its
token, so if page 5 fails transiently, we retry page 5 rather than restarting from page 1.from typing import Callable, Dict, Optional from datetime import date class ApiError(Exception): """An HTTP error from the price API; status_code is the HTTP status.""" def __init__(self, status_code: int, message: str = "") -> None: super().__init__(f"HTTP {status_code} {message}".strip()) self.status_code = status_code def is_transient(error: Exception) -> bool: """Return True only for temporary failures worth retrying (timeouts, network drops, HTTP 5xx).""" if isinstance(error, (TimeoutError, ConnectionError)): return True # HTTP 5xx errors come from temporary server trouble; HTTP 4xx errors (like 404) are permanent if isinstance(error, ApiError): return 500 <= error.status_code <= 599 return False class StockDataClient: def _fetch_with_retry(self, ticker: str, first: date, last: date, token: Optional[str]) -> Dict: """Fetch a single page, retrying transient errors with exponential backoff.""" attempt = 0 while True: try: return self._fetch_page(ticker, first, last, token) except Exception as error: attempt += 1 # Fail immediately on permanent errors (4xx, bugs) or once max_attempts is reached if not is_transient(error) or attempt >= self._max_attempts: raise # Exponential backoff: sleep base_delay * 2^0, base_delay * 2^1, ... between attempts backoff_seconds = self._base_delay * (2 ** (attempt - 1)) self._sleep(backoff_seconds)Consume pages safely until next_page_token runs out
A paginated API returns a chunk of records plus a
next_page_tokencursor pointing to the next chunk. We start withpage_token = Noneand loop untilnext_page_tokencomes backNoneor empty:call(token=None) ──► {data: [d1, d2], next_page_token: "p2"} call(token="p2") ──► {data: [d3, d4], next_page_token: "p3"} call(token="p3") ──► {data: [d5], next_page_token: None} ──► done! (5 records)Two defensive checks protect the loop against misbehaving servers: -
page.get("data") or []treats a missing orNone"data"field as an empty list instead of crashing. -seen_tokensremembers every non-empty token we have already requested; if a buggy server ever returns a token we already used, we raiseRuntimeErrorinstead of hanging in an infinite loop.from typing import List, Optional, Set from datetime import date class StockDataClient: def _fetch_all_pages(self, ticker: str, first: date, last: date) -> List: """Consume paginated API responses until next_page_token is empty or None.""" records: List = [] page_token: Optional[str] = None # seen_tokens: set of non-empty page tokens already requested, guarding against infinite token loops seen_tokens: Set[str] = set() while True: page = self._fetch_with_retry(ticker, first, last, page_token) page_items = page.get("data") or [] records.extend(page_items) page_token = page.get("next_page_token") if not page_token: return records if page_token in seen_tokens: raise RuntimeError(f"API repeated page token {page_token!r}") seen_tokens.add(page_token)Cache by (ticker, date) and fetch only uncached gaps
If we keyed the cache by the whole request
(ticker, start_date, end_date), overlapping requests would still miss. Instead, we maintain two per-day structures:_prices[(ticker, day)] = (open_price, close_price)for every valid trading record._fetched: a set of(ticker, day)pairs covered by a completed fetch.
Why do we need
_fetchedin addition to_prices? Suppose Saturday2024-04-06has no trading data. Once we have fetched April 5–8,(ticker, 2024-04-06)is in_fetchedeven though it is not in_prices. On the next call, we immediately know April 6 is genuinely'missing'without asking the API again. Caching known absences like this is called negative caching.When a new range arrives, we filter down to days not in
_fetchedand group consecutive uncached days into(run_start, run_end)intervals:Already in _fetched: [Apr 04 .. Apr 05] New request: [Apr 01 ......................... Apr 08] Uncached gaps: [Apr 01..03] [Apr 06..08] └─ Run 1 ─┘ └─ Run 2 ─┘Finally,
_load_rangecommits to_pricesand_fetchedonly after every page of the run has arrived. If page 3 of 4 fails after all retries, nothing is written to the cache, so a later call cleanly retries the whole gap.from typing import Dict, List, Tuple from datetime import date, timedelta from decimal import Decimal def days_between(start: date, end: date) -> List[date]: """Generate every calendar date from start through end inclusive, in ascending order.""" days: List[date] = [] current_day = start while current_day <= end: days.append(current_day) current_day += timedelta(days=1) return days def contiguous_runs(days: List[date]) -> List[Tuple[date, date]]: """Collapse sorted dates into (run_start, run_end) intervals of consecutive calendar days.""" # runs: list of (first_day, last_day), e.g. [(2024-04-01, 2024-04-03), (2024-04-06, 2024-04-08)] runs: List[Tuple[date, date]] = [] for day in days: if runs and runs[-1][1] + timedelta(days=1) == day: # Extend the current run when this day immediately follows the previous day previous_start = runs[-1][0] runs[-1] = (previous_start, day) else: runs.append((day, day)) return runs class StockDataClient: def _load_range(self, ticker: str, first: date, last: date) -> None: """Download all pages for [first, last], deduplicate, and commit atomically to the cache.""" raw_records = self._fetch_all_pages(ticker, first, last) # found: {day: (open_price, close_price)} keeping only the first valid record per in-range date found: Dict[date, Tuple[Decimal, Decimal]] = {} for raw_record in raw_records: parsed = parse_record(raw_record) if parsed is None: continue day, open_price, close_price = parsed # Ignore stray out-of-range dates so we never cache partial data outside [first, last] if day < first or day > last: continue if day in found: # Duplicate date in API response: keep the first valid record we saw continue found[day] = (open_price, close_price) # Commit to cache only AFTER all pages succeed so a mid-range failure leaves no half-cached state for day, price_pair in found.items(): self._prices[(ticker, day)] = price_pair for day in days_between(first, last): self._fetched.add((ticker, day))Assemble every calendar date and trace two requests
get_price_historyvalidates its inputs, loads any uncached runs, and walksall_daysin ascending order to emit one fresh dictionary per calendar day.Notice one subtle Python type check in
_check_args:datetimeis a subclass ofdate, soisinstance(datetime(2024, 4, 4), date)returnsTrue! However,datetime(2024, 4, 4) != date(2024, 4, 4)when looking up keys in_prices, and comparingdatetime < dateraisesTypeError. Rejectingisinstance(boundary, datetime)explicitly catches that bug immediately.Let's trace the two sample calls starting from an empty cache:
Call 1: get_price_history("ORCL", 2024-04-04, 2024-04-05) uncached_days = [04-04, 04-05] -> runs = [(04-04, 04-05)] API call 1: fetch_page("ORCL", 04-04, 04-05, None) -> 2 records, next_page_token=None _prices = {("ORCL", 04-04): (124.10, 125.85), ("ORCL", 04-05): (126.00, 124.75)} _fetched = {("ORCL", 04-04), ("ORCL", 04-05)} returns: [04-04 ok, 04-05 ok] Call 2: get_price_history("orcl", 2024-04-05, 2024-04-08) (04-06..04-07 weekend; 1st try hits 503) normalized_ticker = "ORCL" uncached_days = [04-06, 04-07, 04-08] -> runs = [(04-06, 04-08)] Run 1 (04-06..04-08): try 1 -> HTTP 503 -> sleep 0.5s -> try 2 -> duplicate records on 04-08 deduplication keeps first valid 04-08 record (125.20, 127.40) returns: [04-05 ok (cached), 04-06 missing, 04-07 missing, 04-08 ok]If we later query
2024-04-06..2024-04-07,uncached_daysis empty (both weekend days are in_fetched), so zero API calls are made.Complete solution
from typing import Callable, Dict, List, Optional, Set, Tuple import time from datetime import date, datetime, timedelta from decimal import Decimal, InvalidOperation class ApiError(Exception): """An HTTP error from the price API; status_code is the HTTP status.""" def __init__(self, status_code: int, message: str = "") -> None: super().__init__(f"HTTP {status_code} {message}".strip()) self.status_code = status_code def is_transient(error: Exception) -> bool: """Return True only for temporary failures worth retrying (timeouts, network drops, HTTP 5xx).""" if isinstance(error, (TimeoutError, ConnectionError)): return True # HTTP 5xx errors come from temporary server trouble; HTTP 4xx errors (like 404) are permanent if isinstance(error, ApiError): return 500 <= error.status_code <= 599 return False def parse_price(value: object) -> Optional[Decimal]: """Convert raw API price input into a positive, finite Decimal, or None if invalid.""" # Reject bool explicitly because bool is a subclass of int in Python (True == 1) if isinstance(value, bool): return None # Convert float via str() first: str(0.1) is '0.1', whereas Decimal(0.1) keeps binary float noise if isinstance(value, float): text = str(value) elif isinstance(value, (str, int, Decimal)): text = str(value).strip() else: return None try: price = Decimal(text) except InvalidOperation: return None # Check is_finite() BEFORE price <= 0 because comparing Decimal('NaN') <= 0 raises InvalidOperation if not price.is_finite() or price <= 0: return None return price def parse_day(value: object) -> Optional[date]: """Convert an ISO 'YYYY-MM-DD' string, date, or datetime into a date object, or None.""" # Check datetime before date because datetime is a subclass of date if isinstance(value, datetime): return value.date() if isinstance(value, date): return value if isinstance(value, str): try: return date.fromisoformat(value.strip()) except ValueError: return None return None def parse_record(record: object) -> Optional[Tuple[date, Decimal, Decimal]]: """Extract (day, open_price, close_price) from one raw API dict, or None if malformed.""" if not isinstance(record, dict): return None day = parse_day(record.get("date")) open_price = parse_price(record.get("open")) close_price = parse_price(record.get("close")) if day is None or open_price is None or close_price is None: return None return day, open_price, close_price def days_between(start: date, end: date) -> List[date]: """Generate every calendar date from start through end inclusive, in ascending order.""" days: List[date] = [] current_day = start while current_day <= end: days.append(current_day) current_day += timedelta(days=1) return days def contiguous_runs(days: List[date]) -> List[Tuple[date, date]]: """Collapse sorted dates into (run_start, run_end) intervals of consecutive calendar days.""" # runs: list of (first_day, last_day), e.g. [(2024-04-01, 2024-04-03), (2024-04-06, 2024-04-08)] runs: List[Tuple[date, date]] = [] for day in days: if runs and runs[-1][1] + timedelta(days=1) == day: # Extend the current run when this day immediately follows the previous day previous_start = runs[-1][0] runs[-1] = (previous_start, day) else: runs.append((day, day)) return runs class StockDataClient: """Client that fetches, validates, deduplicates, and caches daily open/close stock prices.""" def __init__(self, fetch_page: Callable, max_attempts: int = 3, base_delay: float = 0.5, sleep: Callable[[float], None] = time.sleep) -> None: if max_attempts < 1: raise ValueError("max_attempts must be at least 1") if base_delay < 0: raise ValueError("base_delay must be non-negative") self._fetch_page = fetch_page self._max_attempts = max_attempts self._base_delay = base_delay self._sleep = sleep # _prices: {(ticker, day): (open_price, close_price)} for valid trading records self._prices: Dict[Tuple[str, date], Tuple[Decimal, Decimal]] = {} # _fetched: {(ticker, day)} for all calendar days covered by a completed fetch (including missing days) self._fetched: Set[Tuple[str, date]] = set() def get_price_history(self, ticker: str, start_date: date, end_date: date) -> List[Dict]: """Return one row per calendar date in [start_date, end_date], sorted ascending.""" # Phase 1: Validate inputs and normalize ticker symbol so 'orcl' and 'ORCL' share cache entries normalized_ticker = self._check_args(ticker, start_date, end_date) all_days = days_between(start_date, end_date) # Phase 2: Find calendar days not yet fetched and load each contiguous gap from the API uncached_days: List[date] = [] for day in all_days: if (normalized_ticker, day) not in self._fetched: uncached_days.append(day) for run_start, run_end in contiguous_runs(uncached_days): self._load_range(normalized_ticker, run_start, run_end) # Phase 3: Build fresh output rows for every calendar day in ascending order rows: List[Dict] = [] for day in all_days: cached_price = self._prices.get((normalized_ticker, day)) if cached_price is None: rows.append({"date": day, "open": None, "close": None, "status": "missing"}) else: open_price, close_price = cached_price rows.append({"date": day, "open": open_price, "close": close_price, "status": "ok"}) return rows def _check_args(self, ticker: str, start_date: date, end_date: date) -> str: if not isinstance(ticker, str) or not ticker.strip(): raise ValueError("ticker must be a non-empty string") for boundary in (start_date, end_date): # Reject datetime explicitly: datetime subclasses date, yet datetime != date in dict keys if isinstance(boundary, datetime) or not isinstance(boundary, date): raise TypeError("start_date and end_date must be datetime.date objects") if start_date > end_date: raise ValueError("start_date must not be after end_date") return ticker.strip().upper() def _load_range(self, ticker: str, first: date, last: date) -> None: """Download all pages for [first, last], deduplicate, and commit atomically to the cache.""" raw_records = self._fetch_all_pages(ticker, first, last) # found: {day: (open_price, close_price)} keeping only the first valid record per in-range date found: Dict[date, Tuple[Decimal, Decimal]] = {} for raw_record in raw_records: parsed = parse_record(raw_record) if parsed is None: continue day, open_price, close_price = parsed # Ignore stray out-of-range dates so we never cache partial data outside [first, last] if day < first or day > last: continue if day in found: # Duplicate date in API response: keep the first valid record we saw continue found[day] = (open_price, close_price) # Commit to cache only AFTER all pages succeed so a mid-range failure leaves no half-cached state for day, price_pair in found.items(): self._prices[(ticker, day)] = price_pair for day in days_between(first, last): self._fetched.add((ticker, day)) def _fetch_all_pages(self, ticker: str, first: date, last: date) -> List: """Consume paginated API responses until next_page_token is empty or None.""" records: List = [] page_token: Optional[str] = None # seen_tokens: set of non-empty page tokens already requested, guarding against infinite token loops seen_tokens: Set[str] = set() while True: page = self._fetch_with_retry(ticker, first, last, page_token) page_items = page.get("data") or [] records.extend(page_items) page_token = page.get("next_page_token") if not page_token: return records if page_token in seen_tokens: raise RuntimeError(f"API repeated page token {page_token!r}") seen_tokens.add(page_token) def _fetch_with_retry(self, ticker: str, first: date, last: date, token: Optional[str]) -> Dict: """Fetch a single page, retrying transient errors with exponential backoff.""" attempt = 0 while True: try: return self._fetch_page(ticker, first, last, token) except Exception as error: attempt += 1 # Fail immediately on permanent errors (4xx, bugs) or once max_attempts is reached if not is_transient(error) or attempt >= self._max_attempts: raise # Exponential backoff: sleep base_delay * 2^0, base_delay * 2^1, ... between attempts backoff_seconds = self._base_delay * (2 ** (attempt - 1)) self._sleep(backoff_seconds)✅ Submit now — all tests should pass.
Intuition & how it works
Think of StockDataClient like filling in a wall calendar of daily stock prices from a slow mail-order catalog. Whenever someone asks for a stretch of dates, you check which boxes on the calendar are still blank, order catalog pages only for those blank stretches, pencil in the valid prices as exact base-10 decimals, and stamp weekends or holidays as "checked — no trading" so you never waste postage ordering them again.
A naive client that re-downloads [start_date, end_date] from scratch on every call fails in three ways. First, overlapping requests (like asking for January 1–31 right after January 10–20) pay slow network round trips for data you already have, and weekends trigger repeat fetches forever if you only cache days with prices. Second, a single temporary server hiccup on page 8 of 10 crashes the entire call unless you retry individual pages. Third, parsing prices through binary float introduces rounding noise (0.1 + 0.2 == 0.30000000000000004).
Walk through a tiny example:
1. You request ORCL for 2024-04-04 to 2024-04-05. Both days are uncached, so the client fetches one range [04-04, 04-05], stores both Decimal price pairs (124.10/125.85 and 126.00/124.75) in _prices, and marks both dates in _fetched.
2. Next, you request "orcl" for 2024-04-05 to 2024-04-08, where Saturday 04-06 and Sunday 04-07 have no trading. Normalizing to "ORCL" and checking _fetched skips 04-05 and leaves one uncached gap: [04-06, 04-08].
3. Suppose the first request for [04-06, 04-08] hits an HTTP 503 (transient error — a temporary server or network failure that may succeed on retry). The client waits 0.5 seconds using exponential backoff (doubling the wait time after each consecutive failure), retries that page, keeps the first valid Monday 04-08 record (125.20/127.40), and still marks 04-06 and 04-07 in _fetched (negative caching — recording that a lookup returned nothing so you do not repeat it).
4. Finally, the client walks all four calendar dates in order, emitting 'ok' for 04-05 (from cache), 'missing' for 04-06 and 04-07, and 'ok' for 04-08 (newly fetched).
Complexity
Let D be the number of calendar days in [start_date, end_date], R be the total raw records returned by the API across uncached gaps, and P be the number of API pages fetched.
- Time: O(D + R) local CPU work, plus at most
P * max_attemptsnetwork calls. We enumerate theDcalendar days once, performO(1)average hash-set and dictionary lookups per day to find uncached gaps and assemble output rows, and scan theRreturned records once to parseDecimalprices and drop duplicates. BecauseDis at most ~1,827 days for a 5-year range, local work takes under a millisecond and network latency dominates; a fully cached range makes zero API calls. - Space: O(D + R) temporary memory per call, plus O(U) persistent memory for the cache, where
Uis the total number of distinct(ticker, date)pairs ever fetched across the client's lifetime. Each cached day stores at most one tuple in_pricesand one entry in_fetched(roughly 1 MB per 5 years of a single ticker in CPython).
Edge cases
- Single-day range (
start_date == end_date): produces a one-element list without off-by-one errors becausedays_betweenuses<=. datetimepassed instead ofdate: rejected withTypeError. Althoughdatetimesubclassesdate,datetime(2024, 4, 4) != date(2024, 4, 4)in dictionary keys, which would break cache lookups.- Weekends, holidays, or empty API payloads (
data: []orNone): emitted with'status': 'missing'andNoneprices, and marked in_fetchedso subsequent calls do not re-fetch them. - Duplicate dates within or across pages: deduplicated by keeping the first valid record per calendar day; if the first copy for a day is malformed and a second copy is valid, the valid copy wins.
- Malformed values:
NaN,Infinity, zero or negative numbers, booleans (True/False), unparseable strings, missing fields, and non-dict items are safely skipped. - Stray out-of-range dates from the API: ignored rather than cached, since we did not request that date's surrounding range.
- Mid-pagination failure: if page 3 fails all
max_attemptsretries, nothing from pages 1–2 is committed to_pricesor_fetched, leaving the cache clean for a future retry. - Repeated pagination token: raises
RuntimeErrorimmediately instead of looping infinitely against a broken server.
Common mistakes
- Calling
Decimal(float_val)directly:Decimal(0.1)preserves binary floating-point inaccuracy (0.10000000000000000555...). Always convert floats viaDecimal(str(float_val)). - Comparing
Decimal('NaN') <= 0before checkingis_finite(): unlike floats, comparing aNaNDecimalwith<=raisesdecimal.InvalidOperation. - Retrying 4xx client errors: retrying
404 Not Foundor400 Bad Requestthree times wastes 1.5 seconds of sleep on an error that cannot self-heal. - Restarting from page 1 when a later page fails: retry at the single-page helper level with the same
page_tokenso earlier pages are not re-downloaded. - Keying the cache by
(ticker, start_date, end_date): prevents partial reuse when ranges overlap. - Forgetting negative caching: if you only check
day in _prices, every weekend and market holiday triggers a new API request on every call. - Writing to the cache page by page: if a multi-page fetch fails partway through, marking early pages as fetched makes the unreached dates look permanently missing or half-cached.
Alternative approaches
- Interval-tree / merged date intervals for
_fetched: storing sorted(first, last)intervals per ticker usesO(number of contiguous intervals)memory instead of one set entry per day, at the cost of extra interval-subtraction code. For 5-year ranges (~1,827 days per ticker), a hash set of(ticker, date)is simpler and less bug-prone. - Randomized jitter on backoff: in production with many clients, sleeping
random.uniform(0, base_delay * 2 ** (attempt - 1))(jitter — adding randomness to retry delays so synchronized clients do not all retry at the exact same instant) prevents retry waves. Here deterministic delays keep unit tests exact unless a random generator is injected.
Follow-up questions
- How would you redesign the client to handle multi-threaded callers and batch endpoints that accept several symbols per request? Keep the cache keyed by
(ticker, date), compute the uncached(run_start, run_end)gaps for each requested symbol, and group symbols that share overlapping gaps into multi-symbol batch requests. When callers run on multiple threads simultaneously, guard_pricesand_fetchedwith a lock and add single-flight coalescing (a map of in-progress(ticker, run)futures so two threads requesting the same uncached symbol wait on one shared network call rather than issuing duplicates). Bound concurrent outbound requests with a semaphore and treat HTTP429 Too Many Requestsas retryable while respecting itsRetry-Afterheader. - Once memory usage reaches a fixed budget, which cache eviction strategy fits historical price data best, and how do you keep negative-cache state consistent? Use LRU eviction (Least Recently Used — discarding the items untouched for the longest time once capacity is full), because traffic concentrates on active symbols and recent date windows while historical daily closes are immutable once finalized. Evict in coarse units such as
(ticker, year_month)so dropping one bucket reclaims ~30 days with minimal metadata overhead, and always purge_pricesand_fetchedentries together for that bucket so an evicted trading day never looks'missing'. - What schema and write path would you use to back this cache with a relational database rather than process memory? Define
equity_prices(ticker TEXT, day DATE, open NUMERIC, close NUMERIC, status TEXT, fetched_at TIMESTAMP, PRIMARY KEY (ticker, day)), storing exactNUMERIC/DECIMALcolumns instead of binary floats and persistingstatus = 'missing'rows to retain negative caching across restarts. QuerySELECT day, open, close, status FROM equity_prices WHERE ticker = ? AND day BETWEEN ? AND ?to locate uncached date intervals, download only the missing runs upstream, and commit each completed run atomically in one transaction via an upsert (INSERT ... ON CONFLICT DO NOTHINGso concurrent workers safely insert rows without duplicate-key errors). Pair the table with a small in-memory LRU layer for hot symbols, and avoid permanently caching the current unfinished trading day before market close.
Follow-up questions
- How would you redesign the client to handle multi-threaded callers and batch endpoints that accept several symbols per request?
- Once memory usage reaches a fixed budget, which cache eviction strategy fits historical price data best, and how do you keep negative-cache state consistent?
- What schema and write path would you use to back this cache with a relational database rather than process memory?
Similar questions
- Debugging Out-of-Order Fetch Results in React
- In-Memory Publish-Subscribe Event Bus
- Multi-Car Elevator Dispatch Simulator
- Two-Level In-Memory Store with Field Expiration
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target