Equatorial Cooling Windows with Resilient Forecast Fetching
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build a weather-monitoring service that inspects 72-hour hourly temperature forecasts for equatorial cities and reports every contiguous 8-reading cooling window where temperatures drop strictly hour after hour.
To keep database queries, HTTP transport, wall-clock time, and sleeping cleanly testable without live network I/O, implement the pure helpers and dependency-injected ForecastWindowService defined in starter.py:
-
City lookup & equatorial filter (
ForecastWindowService.get_decreasing_windows(city_id: int) -> List[Tuple[str, str]]):- Look up
(latitude, longitude)viafind_city(city_id). RaiseLookupErroriffind_cityreturnsNone. - Only evaluate locations inside the inclusive equatorial band
-5.0 <= latitude <= 5.0. Ifabs(latitude) > 5.0, return[]immediately without callingfetch_forecast.
- Look up
-
Resilient forecast retrieval (
ForecastWindowService.fetch_with_retry(latitude: float, longitude: float) -> List[Dict[str, Any]]andretry_after_seconds(value: Optional[str], now: float) -> Optional[float]):- Request
72hours of forecast points viafetch_forecast(latitude, longitude, 72)up tomax_attemptstotal tries (5by default). - On HTTP
200, validate thatresponse.bodyis alistand return it; raiseWeatherApiErrorimmediately ifbodyis not alist. - On HTTP
500..599,ConnectionError, orTimeoutError, sleepmin(max_delay, base_delay * (2 ** attempt))seconds before retrying (attemptstarts at0). - On HTTP
429, look up theRetry-Afterheader case-insensitively and parse it withretry_after_seconds(value, clock()):- Non-negative ASCII integer string (e.g.,
"4") -> waitfloat(value)seconds. - RFC 9110 HTTP-date string -> wait
max(0.0, target_epoch - now)seconds. - Missing or unparseable header ->
retry_after_secondsreturnsNone, andfetch_with_retryfalls back to exponential backoff. - If the parsed
Retry-Afterdelay exceedsmax_delay, raiseWeatherApiErrorimmediately without sleeping.
- Non-negative ASCII integer string (e.g.,
- On any other HTTP status (such as
400,401, or404), raiseWeatherApiErrorimmediately without retrying. - Never sleep after the final failed attempt; once
max_attemptsattempts fail, raiseWeatherApiError.
- Request
-
Contiguous cooling window scan (
find_decreasing_windows(points: List[Dict[str, Any]], length: int = 8) -> List[Tuple[str, str]]):- Each valid element of
pointshas"timestamp"in UTC format"YYYY-MM-DDTHH:MM:SSZ"and numeric"temp"(rejectingbool,None,NaN,inf, and malformed records). - Input points may arrive unsorted or contain duplicates: collapse identical readings for the same hour into one, and treat malformed records or conflicting temperatures at the same hour as missing hours.
- Return
(start_timestamp, end_timestamp)(using the raw timestamp strings, ordered chronologically by start) for every run oflength(8) consecutive hourly points spaced exact 1-hour steps apart whose temperatures satisfytemp[0] > temp[1] > ... > temp[length - 1]. Any missing hour or equal/warmer step breaks all windows crossing it.
- Each valid element of
Examples
Example 1
Input:
Hourly points starting at 2026-04-15T06:00:00Z with temperatures:
[29.5, 28.8, 28.0, 27.4, 26.9, 26.1, 25.5, 24.8, 24.2, 24.2]
Output:
[
("2026-04-15T06:00:00Z", "2026-04-15T13:00:00Z"),
("2026-04-15T07:00:00Z", "2026-04-15T14:00:00Z"),
]
Explanation: Readings 0..7 (06:00Z through 13:00Z) and 1..8 (07:00Z through 14:00Z) each contain 8 consecutive 1-hour steps with strictly falling temperatures (29.5 > ... > 24.8 and 28.8 > ... > 24.2). Reading 9 (15:00Z) stays flat at 24.2, which is not strictly less than 24.2, so 08:00Z..15:00Z does not qualify.
Example 2
Input:
cities = {10: (1.29, 103.85), 20: (12.97, 77.59)}
API responses for city 10:
Attempt 0 -> ApiResponse(502)
Attempt 1 -> ApiResponse(429, {"Retry-After": "4"})
Attempt 2 -> ApiResponse(200, {}, points)
where points has hours 00:00Z..07:00Z on 2026-04-15 at
[27.0, 26.5, 26.0, 25.5, 25.0, 24.5, 24.0, 23.5],
skips 08:00Z, and has 09:00Z at 22.0.
Output:
service.get_decreasing_windows(20) -> [] (0 API calls; latitude 12.97 > 5.0)
service.get_decreasing_windows(10) -> [("2026-04-15T00:00:00Z", "2026-04-15T07:00:00Z")]
recorded sleeps -> [0.5, 4.0]
Explanation: City 20 lies outside [-5.0, 5.0], so no HTTP request is sent. For city 10, attempt 0 backs off 0.5s on HTTP 502, attempt 1 honors Retry-After: 4 (4.0s) on HTTP 429, and attempt 2 succeeds. Hours 00:00Z..07:00Z form one valid 8-reading window, while the missing 08:00Z reading blocks any window from bridging across to 09:00Z.
Constraints
- Equatorial latitude check is inclusive:
-5.0 <= latitude <= 5.0. - Valid timestamps strictly match
"%Y-%m-%dT%H:%M:%SZ"in UTC. - Adjacent points in a valid window must differ by
1exact hour (3600seconds) and satisfytemp[k] < temp[k - 1]. - Default retry configuration:
max_attempts = 5,base_delay = 0.5,max_delay = 30.0. - Pure Python standard library only.
Step-by-step walkthrough
Restate the problem and separate I/O from pure logic
Given a
city_id, we need to build a service functionget_decreasing_windows(city_id)that:- Looks up
(latitude, longitude)forcity_idin PostgreSQL, proceeding only if the city is equatorial (-5.0 <= latitude <= 5.0), - Fetches the next
72hours of forecast readings ({"timestamp": "YYYY-MM-DDTHH:MM:SSZ", "temp": float}) from an unreliable external Weather API, - Retries transient
5xxand network errors with exponential backoff, and honors theRetry-Afterheader on429 Too Many Requests, - Finds every 8-reading consecutive hourly sliding window (
temp[i] > temp[i+1] > ... > temp[i+7], spanning7one-hour steps from e.g.00:00to07:00), and - Treats any missing hour as breaking every window that would cross that hour.
Mixing SQL queries,
time.sleep, HTTP calls, and sliding-window math inside one big function makes testing slow and brittle. Instead, we use dependency injection (passing external dependencies likefind_city,fetch_forecast,sleep, andclockintoForecastWindowServiceas callable arguments) so our code splits cleanly into three independently testable layers:get_decreasing_windows(city_id) | +-- 1. find_city(city_id) -> LookupError if None; return [] if abs(lat) > 5.0 (no API call!) +-- 2. fetch_with_retry(lat, lon) -> retries 5xx / timeouts & 429 Retry-After via injected sleep/clock +-- 3. find_decreasing_windows() -> pure O(n log n) clean + O(n) single-pass streak counterLet's state our boundary decisions clearly up front (say these out loud in an interview):
- Equatorial band: inclusive (
-5.0and5.0qualify;5.01returns[]without calling the Weather API). - Unknown
city_id: raisesLookupError(so an HTTP layer can map it to404instead of confusing it with a valid city that had zero cooling windows). - Corrupt or conflicting data points: unparseable timestamps,
None/NaN/boolean temperatures, or duplicate entries for the same hour with different temperatures are dropped, turning that hour into a gap. Exact duplicate points for the same hour are harmlessly deduplicated.
- Looks up
Clean, validate, and sort the hourly forecast points
Why can't we just check
points[i]andpoints[i + 1]directly in the input list? Because if the API omits04:00,03:00and05:00sit right next to each other in the array even though they are two hours apart!clean_seriesprepares a trustworthy chronological list of(moment, original_text, temp)tuples:- Parse
point["timestamp"]using"%Y-%m-%dT%H:%M:%SZ"withtimezone.utcattached so subtracting twodatetimeobjects gives an exacttimedelta. - Reject non-dict records, boolean
tempvalues (in Pythonisinstance(True, int)isTrueandfloat(True)silently evaluates to1.0!), non-numeric strings, andNaN/inf. - Group readings by timestamp and sort chronologically: if an hour appears multiple times with the same temperature, keep one copy; if two entries for the same hour disagree (
22.0vs99.0), drop that hour so it acts as a gap.
WINDOW_HOURS = 8 FORECAST_HOURS = 72 EQUATOR_BAND_DEGREES = 5.0 ONE_HOUR = timedelta(hours=1) TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ" def is_equatorial(latitude: float) -> bool: """Return True when latitude lies within the inclusive [-5.0, 5.0] degree equatorial band.""" return -EQUATOR_BAND_DEGREES <= latitude <= EQUATOR_BAND_DEGREES def parse_timestamp(text: str) -> datetime: """Parse an ISO-8601 UTC timestamp ('YYYY-MM-DDTHH:MM:SSZ') into a timezone-aware datetime.""" return datetime.strptime(text, TIMESTAMP_FORMAT).replace(tzinfo=timezone.utc) def clean_series(points: List[Dict[str, Any]]) -> List[Tuple[datetime, str, float]]: """Validate, deduplicate, and sort forecast points into `(moment, original_text, temp)` tuples.""" # by_time: maps parsed UTC datetime -> list of (raw_timestamp_str, temp_float) seen for that hour. by_time: Dict[datetime, List[Tuple[str, float]]] = {} for point in points: # Drop malformed dicts, unparseable timestamps, booleans (float(True) == 1.0!), or NaN/inf temps. # Dropping a bad record leaves a missing hour, which naturally breaks any window crossing it. if not isinstance(point, dict): continue raw_temp = point.get("temp") if isinstance(raw_temp, bool): continue try: raw_ts = point["timestamp"] moment = parse_timestamp(raw_ts) temp = float(raw_temp) except (KeyError, TypeError, ValueError): continue if not math.isfinite(temp): continue if moment not in by_time: by_time[moment] = [] by_time[moment].append((raw_ts, temp)) # Keep an hour only if all duplicate copies agree on the exact same temperature. series: List[Tuple[datetime, str, float]] = [] for moment in sorted(by_time): copies = by_time[moment] first_text, first_temp = copies[0] consistent = True for _, temp in copies: if temp != first_temp: consistent = False break if consistent: series.append((moment, first_text, first_temp)) return series- Parse
Find 8-hour strictly decreasing windows in one pass
With
n <= 72sorted points, checking all8elements from every start indexi(7 * 65 = 455comparisons) would already be fast enough, but a single-pass streak counter (run) is shorter,O(n), and handles gaps and plateaus with one uniform rule.As we scan
i = 0 .. len(series) - 1,runtracks how many consecutive hourly readings ending atseries[i]have strictly decreasing temperatures:- If
i > 0andmoment - prev_moment == timedelta(hours=1)andtemp < prev_temp(strictly<, because equal neighbors like25, 25are not strictly decreasing), incrementrun += 1. - Otherwise — at index
0, after a missing hour, or on an equal/warmer reading — resetrun = 1. - Whenever
run >= 8, the last8points (series[i - 7 .. i]) are guaranteed to be1hour apart and strictly falling, so we append(series[i - 7][1], series[i][1]).
Example with a missing hour (10:00 omitted): Hour: 06:00 07:00 08:00 09:00 [gap!] 11:00 12:00 Temp: 29.5 28.8 28.0 27.4 26.1 25.5 run: 1 2 3 4 1 2 <- 11:00 - 09:00 == 2h != 1h, so run resets to 1!def find_decreasing_windows(points: List[Dict[str, Any]], length: int = WINDOW_HOURS) -> List[Tuple[str, str]]: """Return `(start_timestamp, end_timestamp)` for every `length` consecutive strictly decreasing hours.""" series = clean_series(points) windows: List[Tuple[str, str]] = [] # run: count of consecutive 1-hour steps with strictly falling temps ending at series[i]. run = 0 for i in range(len(series)): moment, text, temp = series[i] if i > 0: prev_moment, _, prev_temp = series[i - 1] # Must be BOTH exactly 1 hour after the previous reading AND strictly colder (<, not <=). is_next_hour = (moment - prev_moment == ONE_HOUR) is_strictly_colder = (temp < prev_temp) if is_next_hour and is_strictly_colder: run += 1 else: run = 1 else: run = 1 # Whenever the active streak reaches `length` (8 readings), the last `length` points form a valid window. if run >= length: start_index = i - length + 1 start_text = series[start_index][1] windows.append((start_text, text)) return windows- If
Parse Retry-After headers and decide what to retry
Not all API errors should be treated alike:
Failure / Status What it means Action 200withlistbodyValid forecast payload Return response.bodyimmediately500..599,TimeoutError,ConnectionErrorServer or network glitch Sleep min(max_delay, base_delay * 2 ** attempt)and retry429 Too Many RequestsRate limit reached Sleep Retry-After(or backoff if header missing); raiseWeatherApiErrorimmediately if wait> max_delay400,401,403,404, or200non-list bodyPermanent client/contract bug Raise WeatherApiErrorimmediately without wasting retriesPer HTTP RFC 9110,
Retry-Aftercan arrive in either of two formats, and HTTP header names are case-insensitive ("Retry-After"vs"retry-after"):- Delta-seconds: a non-negative ASCII integer string such as
"7"-> wait7.0seconds. Note we checktext.isascii() and text.isdigit()because Python's.isdigit()alone returnsTruefor Unicode superscripts like"²", which would then crashfloat("²")! - HTTP-date: e.g.
"Wed, 21 Oct 2015 07:28:00 GMT"-> parsed viaemail.utils.parsedate_to_datetime(text), waitingmax(0.0, when.timestamp() - now).
def get_header(headers: Dict[str, str], name: str) -> Optional[str]: """Look up an HTTP header case-insensitively (e.g. 'retry-after' vs 'Retry-After').""" target = name.lower() for key, value in headers.items(): if key.lower() == target: return value return None def retry_after_seconds(value: Optional[str], now: float) -> Optional[float]: """Parse an HTTP `Retry-After` header (integer seconds or HTTP-date) into non-negative wait seconds.""" if value is None: return None text = value.strip() # Guard with isascii() because "²".isdigit() is True in Python even though float("²") raises ValueError. if text.isascii() and text.isdigit(): return float(text) try: when = parsedate_to_datetime(text) except (TypeError, ValueError, IndexError, OverflowError): return None if when.tzinfo is None: when = when.replace(tzinfo=timezone.utc) # If the server's HTTP-date is already in the past, retry immediately (0.0 seconds). return max(0.0, when.timestamp() - now)- Delta-seconds: a non-negative ASCII integer string such as
Wire together ForecastWindowService and the retry loop
Now
ForecastWindowServiceconnects city lookup, equatorial filtering, bounded retries, and window detection. Pay attention to two subtle retry details:- If a
429response sendsRetry-After: 3600whilemax_delay = 30.0, we raiseWeatherApiErrorimmediately without sleeping, rather than stalling a worker thread for an hour. - We check
if attempt < self.max_attempts - 1:before callingself.sleep(delay)so a failing5thand final attempt raises right away instead of sleeping pointlessly first.
class ForecastWindowService: def __init__(self, find_city: Callable[[int], Optional[Tuple[float, float]]], fetch_forecast: Callable[[float, float, int], ApiResponse], sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.time, max_attempts: int = 5, base_delay: float = 0.5, max_delay: float = 30.0): self.find_city = find_city self.fetch_forecast = fetch_forecast self.sleep = sleep self.clock = clock self.max_attempts = max_attempts self.base_delay = base_delay self.max_delay = max_delay def get_decreasing_windows(self, city_id: int) -> List[Tuple[str, str]]: """Look up `city_id`, skip non-equatorial cities, fetch 72h forecast, and return 8h cooling windows.""" location = self.find_city(city_id) if location is None: raise LookupError(f"unknown city_id {city_id}") latitude, longitude = location # Skip external API calls entirely when the city lies outside [-5.0, 5.0] degrees latitude. if not is_equatorial(latitude): return [] points = self.fetch_with_retry(latitude, longitude) return find_decreasing_windows(points) def backoff(self, attempt: int) -> float: """Exponential backoff `base_delay * 2^attempt` capped at `max_delay`.""" return min(self.max_delay, self.base_delay * (2 ** attempt)) def fetch_with_retry(self, latitude: float, longitude: float) -> List[Dict[str, Any]]: """Fetch hourly forecast with bounded retries on 5xx, network errors, and 429 Retry-After.""" last_problem = "no attempt made" for attempt in range(self.max_attempts): try: response = self.fetch_forecast(latitude, longitude, FORECAST_HOURS) except (ConnectionError, TimeoutError) as exc: # Transient network failures retry with exponential backoff. last_problem = f"network error: {exc}" delay = self.backoff(attempt) else: if response.status == 200: if not isinstance(response.body, list): raise WeatherApiError("forecast body is not a list") return response.body if response.status == 429: # Honor Retry-After when present; fail fast if the requested wait exceeds max_delay. last_problem = "HTTP 429" header_val = get_header(response.headers, "Retry-After") delay = retry_after_seconds(header_val, self.clock()) if delay is None: delay = self.backoff(attempt) elif delay > self.max_delay: raise WeatherApiError( f"rate limited for {delay:.0f}s, longer than the {self.max_delay:.0f}s budget" ) elif 500 <= response.status <= 599: # Server 5xx errors are transient and retry with exponential backoff. last_problem = f"HTTP {response.status}" delay = self.backoff(attempt) else: # Client 4xx errors (400, 401, 404) are permanent — fail immediately without retrying. raise WeatherApiError(f"HTTP {response.status} is not retryable") # Never sleep after the final attempt when no further retry will be made. if attempt < self.max_attempts - 1: self.sleep(delay) raise WeatherApiError(f"gave up after {self.max_attempts} attempts; last: {last_problem}")- If a
Connect real PostgreSQL and HTTP adapters in production
In production, thin adapter functions wire
psycopgandrequestsintoForecastWindowServiceand expose the top-levelget_decreasing_windows(city_id)function from the prompt:- Parameterized SQL (
%s): Prevents SQL injection, andautocommit=Trueavoids leaving a read-only connection sitting"idle in transaction". - Explicit
(connect, read)HTTP timeout: Withouttimeout=(3, 10), a hung socket blocks forever and never reaches our retry loop.
def make_find_city(conn): def find_city(city_id: int): with conn.cursor() as cur: cur.execute("SELECT latitude, longitude FROM cities WHERE id = %s", (city_id,)) return cur.fetchone() return find_city def make_fetch_forecast(session, base_url: str, api_key: str): import requests def fetch_forecast(latitude: float, longitude: float, hours: int) -> ApiResponse: try: resp = session.get( f"{base_url}/forecast/hourly", params={"lat": latitude, "lon": longitude, "hours": hours}, headers={"Authorization": f"Bearer {api_key}"}, timeout=(3.0, 10.0), ) except requests.Timeout as exc: raise TimeoutError(str(exc)) from exc except requests.ConnectionError as exc: raise ConnectionError(str(exc)) from exc body = None if resp.status_code == 200: try: body = resp.json() except ValueError: body = None return ApiResponse(resp.status_code, dict(resp.headers), body) return fetch_forecast- Parameterized SQL (
Walk through Example 1 and a retry timeline
Let's trace
find_decreasing_windowson Example 1's10hourly temperatures[29.5, 28.8, 28.0, 27.4, 26.9, 26.1, 25.5, 24.8, 24.2, 24.2]starting at2026-04-15T06:00:00Z:Index Timestamp Temp +1h & colder? run Window emitted ----- -------------------- ---- ------------- --- ------------------------------------------------ 0 2026-04-15T06:00:00Z 29.5 (start) 1 - 1 2026-04-15T07:00:00Z 28.8 yes 2 - 2..6 08:00Z .. 12:00Z 28.0..25.5 yes 3..7 - 7 2026-04-15T13:00:00Z 24.8 yes 8 ('2026-04-15T06:00:00Z', '2026-04-15T13:00:00Z') 8 2026-04-15T14:00:00Z 24.2 yes 9 ('2026-04-15T07:00:00Z', '2026-04-15T14:00:00Z') 9 2026-04-15T15:00:00Z 24.2 no (plateau) 1 -And here is Example 2's
fetch_with_retrytrace (base_delay = 0.5,max_attempts = 5):attempt 0 -> HTTP 502 -> transient 5xx -> sleep 0.5 * 2^0 = 0.5 s attempt 1 -> HTTP 429, Retry-After: 4 -> rate limited -> sleep 4.0 s (uses header, not 1.0 s backoff!) attempt 2 -> HTTP 200, [forecast list] -> returns list -> total wait = 4.5 sComplete solution
from typing import Any, Callable, Dict, List, Optional, Tuple from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from email.utils import parsedate_to_datetime import math import time WINDOW_HOURS = 8 FORECAST_HOURS = 72 EQUATOR_BAND_DEGREES = 5.0 ONE_HOUR = timedelta(hours=1) TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ" @dataclass class ApiResponse: """HTTP status, response headers, and parsed JSON body returned by `fetch_forecast`.""" status: int headers: Dict[str, str] = field(default_factory=dict) body: Any = None class WeatherApiError(Exception): """Raised when the forecast cannot be retrieved (non-retryable error, bad body, or retries exhausted).""" def is_equatorial(latitude: float) -> bool: """Return True when latitude lies within the inclusive [-5.0, 5.0] degree equatorial band.""" return -EQUATOR_BAND_DEGREES <= latitude <= EQUATOR_BAND_DEGREES def parse_timestamp(text: str) -> datetime: """Parse an ISO-8601 UTC timestamp ('YYYY-MM-DDTHH:MM:SSZ') into a timezone-aware datetime.""" return datetime.strptime(text, TIMESTAMP_FORMAT).replace(tzinfo=timezone.utc) def clean_series(points: List[Dict[str, Any]]) -> List[Tuple[datetime, str, float]]: """Validate, deduplicate, and sort forecast points into `(moment, original_text, temp)` tuples.""" # by_time: maps parsed UTC datetime -> list of (raw_timestamp_str, temp_float) seen for that hour. by_time: Dict[datetime, List[Tuple[str, float]]] = {} for point in points: # Drop malformed dicts, unparseable timestamps, booleans (float(True) == 1.0!), or NaN/inf temps. # Dropping a bad record leaves a missing hour, which naturally breaks any window crossing it. if not isinstance(point, dict): continue raw_temp = point.get("temp") if isinstance(raw_temp, bool): continue try: raw_ts = point["timestamp"] moment = parse_timestamp(raw_ts) temp = float(raw_temp) except (KeyError, TypeError, ValueError): continue if not math.isfinite(temp): continue if moment not in by_time: by_time[moment] = [] by_time[moment].append((raw_ts, temp)) # Keep an hour only if all duplicate copies agree on the exact same temperature. series: List[Tuple[datetime, str, float]] = [] for moment in sorted(by_time): copies = by_time[moment] first_text, first_temp = copies[0] consistent = True for _, temp in copies: if temp != first_temp: consistent = False break if consistent: series.append((moment, first_text, first_temp)) return series def find_decreasing_windows(points: List[Dict[str, Any]], length: int = WINDOW_HOURS) -> List[Tuple[str, str]]: """Return `(start_timestamp, end_timestamp)` for every `length` consecutive strictly decreasing hours.""" series = clean_series(points) windows: List[Tuple[str, str]] = [] # run: count of consecutive 1-hour steps with strictly falling temps ending at series[i]. run = 0 for i in range(len(series)): moment, text, temp = series[i] if i > 0: prev_moment, _, prev_temp = series[i - 1] # Must be BOTH exactly 1 hour after the previous reading AND strictly colder (<, not <=). is_next_hour = (moment - prev_moment == ONE_HOUR) is_strictly_colder = (temp < prev_temp) if is_next_hour and is_strictly_colder: run += 1 else: run = 1 else: run = 1 # Whenever the active streak reaches `length` (8 readings), the last `length` points form a valid window. if run >= length: start_index = i - length + 1 start_text = series[start_index][1] windows.append((start_text, text)) return windows def get_header(headers: Dict[str, str], name: str) -> Optional[str]: """Look up an HTTP header case-insensitively (e.g. 'retry-after' vs 'Retry-After').""" target = name.lower() for key, value in headers.items(): if key.lower() == target: return value return None def retry_after_seconds(value: Optional[str], now: float) -> Optional[float]: """Parse an HTTP `Retry-After` header (integer seconds or HTTP-date) into non-negative wait seconds.""" if value is None: return None text = value.strip() # Guard with isascii() because "²".isdigit() is True in Python even though float("²") raises ValueError. if text.isascii() and text.isdigit(): return float(text) try: when = parsedate_to_datetime(text) except (TypeError, ValueError, IndexError, OverflowError): return None if when.tzinfo is None: when = when.replace(tzinfo=timezone.utc) # If the server's HTTP-date is already in the past, retry immediately (0.0 seconds). return max(0.0, when.timestamp() - now) class ForecastWindowService: def __init__(self, find_city: Callable[[int], Optional[Tuple[float, float]]], fetch_forecast: Callable[[float, float, int], ApiResponse], sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.time, max_attempts: int = 5, base_delay: float = 0.5, max_delay: float = 30.0): self.find_city = find_city self.fetch_forecast = fetch_forecast self.sleep = sleep self.clock = clock self.max_attempts = max_attempts self.base_delay = base_delay self.max_delay = max_delay def get_decreasing_windows(self, city_id: int) -> List[Tuple[str, str]]: """Look up `city_id`, skip non-equatorial cities, fetch 72h forecast, and return 8h cooling windows.""" location = self.find_city(city_id) if location is None: raise LookupError(f"unknown city_id {city_id}") latitude, longitude = location # Skip external API calls entirely when the city lies outside [-5.0, 5.0] degrees latitude. if not is_equatorial(latitude): return [] points = self.fetch_with_retry(latitude, longitude) return find_decreasing_windows(points) def backoff(self, attempt: int) -> float: """Exponential backoff `base_delay * 2^attempt` capped at `max_delay`.""" return min(self.max_delay, self.base_delay * (2 ** attempt)) def fetch_with_retry(self, latitude: float, longitude: float) -> List[Dict[str, Any]]: """Fetch hourly forecast with bounded retries on 5xx, network errors, and 429 Retry-After.""" last_problem = "no attempt made" for attempt in range(self.max_attempts): try: response = self.fetch_forecast(latitude, longitude, FORECAST_HOURS) except (ConnectionError, TimeoutError) as exc: # Transient network failures retry with exponential backoff. last_problem = f"network error: {exc}" delay = self.backoff(attempt) else: if response.status == 200: if not isinstance(response.body, list): raise WeatherApiError("forecast body is not a list") return response.body if response.status == 429: # Honor Retry-After when present; fail fast if the requested wait exceeds max_delay. last_problem = "HTTP 429" header_val = get_header(response.headers, "Retry-After") delay = retry_after_seconds(header_val, self.clock()) if delay is None: delay = self.backoff(attempt) elif delay > self.max_delay: raise WeatherApiError( f"rate limited for {delay:.0f}s, longer than the {self.max_delay:.0f}s budget" ) elif 500 <= response.status <= 599: # Server 5xx errors are transient and retry with exponential backoff. last_problem = f"HTTP {response.status}" delay = self.backoff(attempt) else: # Client 4xx errors (400, 401, 404) are permanent — fail immediately without retrying. raise WeatherApiError(f"HTTP {response.status} is not retryable") # Never sleep after the final attempt when no further retry will be made. if attempt < self.max_attempts - 1: self.sleep(delay) raise WeatherApiError(f"gave up after {self.max_attempts} attempts; last: {last_problem}")✅ Submit now — all tests should pass.
Intuition & how it works
Imagine scanning a paper weather logbook for an 8-hour cooling streak by counting on your fingers: as you read down the sorted hourly rows, you add 1 to your streak counter run whenever the clock moves forward by exactly 1 hour and the temperature is strictly lower than the previous row; any missing hour or flat/warmer reading resets run back to 1, and every row where run >= 8 completes a valid sliding window (a fixed-length sub-interval moving one step at a time across a sequence) from i - 7 to i. Around that pure window logic, our service wraps network calls in exponential backoff (doubling the wait time 0.5s, 1s, 2s, 4s... after transient 5xx or network failures so an overloaded server gets room to recover) and honors Retry-After headers on 429 rate limits, using dependency injection (accepting database, HTTP, sleep, and clock callables as constructor arguments rather than hardcoding global I/O) so tests run in milliseconds without touching a network.
Why does a naive implementation fail in production? Checking points[i]["temp"] > points[i + 1]["temp"] by list index alone treats 03:00 and 05:00 as neighbors even when 04:00 was dropped by the API, falsely reporting windows across missing hours! On the network side, retrying every error with a fixed sleep(1) wastes quota on permanent 404/401 client bugs, ignores the server's Retry-After schedule during 429 throttling, and hangs forever if the HTTP client has no socket timeout.
Let's trace a compact 4-reading window (length = 4 for brevity; the actual code uses length = 8) over 06:00..11:00 where 07:00 is missing:
Input points: 06:00 (29.5°), [07:00 missing!], 08:00 (28.0°), 09:00 (27.4°), 10:00 (26.9°), 11:00 (26.1°)
Scan cleaned series:
i=0 06:00 temp=29.5 (first point) -> run = 1
i=1 08:00 temp=28.0 08:00 - 06:00 == 2h (gap!) -> run = 1 (gap resets streak!)
i=2 09:00 temp=27.4 +1h and 27.4 < 28.0 -> run = 2
i=3 10:00 temp=26.9 +1h and 26.9 < 27.4 -> run = 3
i=4 11:00 temp=26.1 +1h and 26.1 < 26.9 -> run = 4 -> emits ('08:00', '11:00')
Complexity
Let n be len(points) (n <= 72 for a 72-hour hourly forecast) and A be max_attempts (default 5).
- Window detection (
find_decreasing_windows):- Time:
O(n log n). Validating and grouping thenpoints intoby_timetakesO(n)average time, sorting up tondistinct UTC timestamps takesO(n log n), and the streak-counter scan visits each cleaned point once inO(n). (If input points were guaranteed pre-sorted and duplicate-free, skipping the sort would make itO(n).) - Space:
O(n).by_time,series, and the outputwindowslist (at mostmax(0, n - 7)tuples) each holdO(n)items.
- Time:
- Service & retries (
get_decreasing_windows):- Calls & wait time: Performs
1database lookup (O(1)via primary-key index oncities.id) and at mostAWeather API requests (0requests whenabs(latitude) > 5.0). With defaultsA = 5,base_delay = 0.5s, andmax_delay = 30s,5xxbackoffs sleep at most0.5 + 1 + 2 + 4 = 7.5stotal, while four429waits capped at30ssleep at most120s.
- Calls & wait time: Performs
Edge cases
- Missing hour in the middle of a cooling streak:
moment - prev_momentexceeds1hour, resettingrun = 1so no window can bridge the gap. - Equal adjacent temperatures (
25.0,25.0): Rejected by strict<, resettingrun = 1because plateaus are not strictly decreasing. - Fewer than
8points or empty response ([]):runnever reaches8, returning[]. - Latitude on the exact boundary (
-5.0or5.0) vs outside (5.01,-7.0): Inclusive<=treats±5.0as equatorial; outside latitudes return[]without making any HTTP call. - Unknown
city_id: RaisesLookupErrorrather than returning[], distinguishing a missing database record from an uneventful forecast. - Out-of-order, corrupt, boolean, or duplicate points: Sorting fixes disordered payloads;
None,"n/a",NaN,True(float(True) == 1.0in Python!), or conflicting duplicate hours are dropped into gaps, while identical duplicate records collapse cleanly into one. 429with HTTP-date, missing header, or hugeRetry-After: Supports both integer delta-seconds and RFC 9110 HTTP-dates case-insensitively, falls back to exponential backoff ifRetry-Afteris absent/malformed, clamps past HTTP-dates to0.0s, and raisesWeatherApiErrorimmediately without sleeping ifdelay > max_delay.
Common mistakes
- Checking
points[i]vspoints[i + 1]without comparing parsed timestamps: Silently accepts windows that skip over missing hours or off-grid readings like03:30. - Using
<=instead of<on temperatures: Accepts flat temperature plateaus as "strictly decreasing". - Retrying
400/401/404responses: Permanent client errors will fail identically on every retry, burning rate-limit quota and adding seconds of latency before surfacing the bug. - Calling
.isdigit()without.isascii()onRetry-After: In Python,"²".isdigit()isTrue, causing an uncaughtValueErrorinsidefloat("²"). - Sleeping after the final failed attempt: Always guard
self.sleep(delay)withif attempt < self.max_attempts - 1:so exhausting retries raises immediately. - Omitting HTTP timeouts or building SQL via f-strings: Calling
requests.get(...)withouttimeout=(connect, read)can hang a worker forever, and string-interpolatingcity_idinstead of parameterized%srisks SQL injection.
Alternative approaches
- Sliding
collections.dequeof up to 8 points: Append each valid point to adeque(clearing thedequefirst whenevermoment - deque[-1].moment != 1hortemp >= deque[-1].temp, and popping from the left whenlen > 8). It produces identical output, though the integerruncounter achieves the same result withO(1)state. - Exponential backoff with jitter: After an API outage recovers, thousands of clients retrying at exact powers of two (
0.5s, 1.0s, 2.0s) hammer the server in synchronized waves; jitter (randomizing each sleep torandom.uniform(0, backoff(attempt))) spreads retry spikes evenly across time in production.
Follow-up questions
- How would you scale this architecture if millions of cities were stored in PostgreSQL and every equatorial location had to be evaluated once per hour? Query all equatorial cities in one indexed range scan (
SELECT id, latitude, longitude FROM cities WHERE latitude BETWEEN -5 AND 5backed by a B-tree index onlatitude), then bucket nearby cities onto the weather provider's spatial grid (e.g. rounding coordinates to0.1° ≈ 11 km) so10towns in the same grid cell share one API call. Enqueue one task per unique grid cell onto a worker queue governed by a shared Redis token bucket (a distributed rate-limiter counter that refills at the provider's allowed requests/sec): at50 req/s,20,000grid cells finish in20,000 / 50 = 400 seconds(~6.7 minutes), well inside the 1-hour schedule. Persist output rows with an idempotent upsert (INSERT ... ON CONFLICT (city_id, forecast_run_hour) DO UPDATE) so retried worker jobs never create duplicate alerts. - How should forecasts be cached and deduplicated across requests to cut third-party weather API spend and avoid rate-limit exhaustion? Cache raw 72-hour forecasts in Redis keyed by
(rounded_lat, rounded_lon)with a TTL matching the weather model's update cadence (typically30–60minutes), since forecasts do not change between model runs. Add request coalescing (single-flight) — if40concurrent requests ask for the same uncached grid cell simultaneously,39wait on the single in-flight HTTP call instead of firing40duplicate requests — and use stale-while-revalidate (serving slightly stale cached forecasts during background refreshes or5xxoutages). Also sendIf-None-Match(ETag) headers if the provider discounts304 Not Modifiedresponses. - How can you unit-test backoff timing, Retry-After headers, and missing-hour gaps deterministically without live HTTP calls or real sleeps? Inject
find_city,fetch_forecast,sleep, andclockintoForecastWindowService, then pass a scripted fake callable that pops pre-programmedApiResponseobjects orTimeoutErrorexceptions ([ApiResponse(502), ApiResponse(429, {"Retry-After": "4"}), ApiResponse(200, {}, points)]) while recording call arguments, paired with a fakesleep = delays.appendthat records wait durations ([0.5, 4.0]) instantaneously in0 ms. Testfind_decreasing_windowsdirectly as a pure function on synthetic point lists covering missing hours, plateaus, shuffled timestamps, and randomized fuzzing against a brute-force checker, and test the thinrequestsadapter separately withresponsesorrequests-mock.
Follow-up questions
- How would you scale this architecture if millions of cities were stored in PostgreSQL and every equatorial location had to be evaluated once per hour?
- How should forecasts be cached and deduplicated across requests to cut third-party weather API spend and avoid rate-limit exhaustion?
- How can you unit-test backoff timing, Retry-After headers, and missing-hour gaps deterministically without live HTTP calls or real sleeps?
Similar questions
- Paginated Clinician Directory Search and Filter
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager