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:

  1. City lookup & equatorial filter (ForecastWindowService.get_decreasing_windows(city_id: int) -> List[Tuple[str, str]]):

    • Look up (latitude, longitude) via find_city(city_id). Raise LookupError if find_city returns None.
    • Only evaluate locations inside the inclusive equatorial band -5.0 <= latitude <= 5.0. If abs(latitude) > 5.0, return [] immediately without calling fetch_forecast.
  2. Resilient forecast retrieval (ForecastWindowService.fetch_with_retry(latitude: float, longitude: float) -> List[Dict[str, Any]] and retry_after_seconds(value: Optional[str], now: float) -> Optional[float]):

    • Request 72 hours of forecast points via fetch_forecast(latitude, longitude, 72) up to max_attempts total tries (5 by default).
    • On HTTP 200, validate that response.body is a list and return it; raise WeatherApiError immediately if body is not a list.
    • On HTTP 500..599, ConnectionError, or TimeoutError, sleep min(max_delay, base_delay * (2 ** attempt)) seconds before retrying (attempt starts at 0).
    • On HTTP 429, look up the Retry-After header case-insensitively and parse it with retry_after_seconds(value, clock()):
      • Non-negative ASCII integer string (e.g., "4") -> wait float(value) seconds.
      • RFC 9110 HTTP-date string -> wait max(0.0, target_epoch - now) seconds.
      • Missing or unparseable header -> retry_after_seconds returns None, and fetch_with_retry falls back to exponential backoff.
      • If the parsed Retry-After delay exceeds max_delay, raise WeatherApiError immediately without sleeping.
    • On any other HTTP status (such as 400, 401, or 404), raise WeatherApiError immediately without retrying.
    • Never sleep after the final failed attempt; once max_attempts attempts fail, raise WeatherApiError.
  3. Contiguous cooling window scan (find_decreasing_windows(points: List[Dict[str, Any]], length: int = 8) -> List[Tuple[str, str]]):

    • Each valid element of points has "timestamp" in UTC format "YYYY-MM-DDTHH:MM:SSZ" and numeric "temp" (rejecting bool, 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 of length (8) consecutive hourly points spaced exact 1-hour steps apart whose temperatures satisfy temp[0] > temp[1] > ... > temp[length - 1]. Any missing hour or equal/warmer step breaks all windows crossing it.

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 1 exact hour (3600 seconds) and satisfy temp[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

  1. Restate the problem and separate I/O from pure logic

    Given a city_id, we need to build a service function get_decreasing_windows(city_id) that:

    1. Looks up (latitude, longitude) for city_id in PostgreSQL, proceeding only if the city is equatorial (-5.0 <= latitude <= 5.0),
    2. Fetches the next 72 hours of forecast readings ({"timestamp": "YYYY-MM-DDTHH:MM:SSZ", "temp": float}) from an unreliable external Weather API,
    3. Retries transient 5xx and network errors with exponential backoff, and honors the Retry-After header on 429 Too Many Requests,
    4. Finds every 8-reading consecutive hourly sliding window (temp[i] > temp[i+1] > ... > temp[i+7], spanning 7 one-hour steps from e.g. 00:00 to 07:00), and
    5. 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 like find_city, fetch_forecast, sleep, and clock into ForecastWindowService as 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 counter
    

    Let's state our boundary decisions clearly up front (say these out loud in an interview):

    • Equatorial band: inclusive (-5.0 and 5.0 qualify; 5.01 returns [] without calling the Weather API).
    • Unknown city_id: raises LookupError (so an HTTP layer can map it to 404 instead 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.
  2. Clean, validate, and sort the hourly forecast points

    Why can't we just check points[i] and points[i + 1] directly in the input list? Because if the API omits 04:00, 03:00 and 05:00 sit right next to each other in the array even though they are two hours apart!

    clean_series prepares a trustworthy chronological list of (moment, original_text, temp) tuples:

    1. Parse point["timestamp"] using "%Y-%m-%dT%H:%M:%SZ" with timezone.utc attached so subtracting two datetime objects gives an exact timedelta.
    2. Reject non-dict records, boolean temp values (in Python isinstance(True, int) is True and float(True) silently evaluates to 1.0!), non-numeric strings, and NaN / inf.
    3. 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.0 vs 99.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
    
  3. Find 8-hour strictly decreasing windows in one pass

    With n <= 72 sorted points, checking all 8 elements from every start index i (7 * 65 = 455 comparisons) 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, run tracks how many consecutive hourly readings ending at series[i] have strictly decreasing temperatures:

    • If i > 0 and moment - prev_moment == timedelta(hours=1) and temp < prev_temp (strictly <, because equal neighbors like 25, 25 are not strictly decreasing), increment run += 1.
    • Otherwise — at index 0, after a missing hour, or on an equal/warmer reading — reset run = 1.
    • Whenever run >= 8, the last 8 points (series[i - 7 .. i]) are guaranteed to be 1 hour 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
    
  4. Parse Retry-After headers and decide what to retry

    Not all API errors should be treated alike:

    Failure / Status What it means Action
    200 with list body Valid forecast payload Return response.body immediately
    500..599, TimeoutError, ConnectionError Server or network glitch Sleep min(max_delay, base_delay * 2 ** attempt) and retry
    429 Too Many Requests Rate limit reached Sleep Retry-After (or backoff if header missing); raise WeatherApiError immediately if wait > max_delay
    400, 401, 403, 404, or 200 non-list body Permanent client/contract bug Raise WeatherApiError immediately without wasting retries

    Per HTTP RFC 9110, Retry-After can arrive in either of two formats, and HTTP header names are case-insensitive ("Retry-After" vs "retry-after"):

    1. Delta-seconds: a non-negative ASCII integer string such as "7" -> wait 7.0 seconds. Note we check text.isascii() and text.isdigit() because Python's .isdigit() alone returns True for Unicode superscripts like "²", which would then crash float("²")!
    2. HTTP-date: e.g. "Wed, 21 Oct 2015 07:28:00 GMT" -> parsed via email.utils.parsedate_to_datetime(text), waiting max(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)
    
  5. Wire together ForecastWindowService and the retry loop

    Now ForecastWindowService connects city lookup, equatorial filtering, bounded retries, and window detection. Pay attention to two subtle retry details:

    • If a 429 response sends Retry-After: 3600 while max_delay = 30.0, we raise WeatherApiError immediately without sleeping, rather than stalling a worker thread for an hour.
    • We check if attempt < self.max_attempts - 1: before calling self.sleep(delay) so a failing 5th and 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}")
    
  6. Connect real PostgreSQL and HTTP adapters in production

    In production, thin adapter functions wire psycopg and requests into ForecastWindowService and expose the top-level get_decreasing_windows(city_id) function from the prompt:

    • Parameterized SQL (%s): Prevents SQL injection, and autocommit=True avoids leaving a read-only connection sitting "idle in transaction".
    • Explicit (connect, read) HTTP timeout: Without timeout=(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
    
  7. Walk through Example 1 and a retry timeline

    Let's trace find_decreasing_windows on Example 1's 10 hourly temperatures [29.5, 28.8, 28.0, 27.4, 26.9, 26.1, 25.5, 24.8, 24.2, 24.2] starting at 2026-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_retry trace (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 s
    
  8. Complete 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 the n points into by_time takes O(n) average time, sorting up to n distinct UTC timestamps takes O(n log n), and the streak-counter scan visits each cleaned point once in O(n). (If input points were guaranteed pre-sorted and duplicate-free, skipping the sort would make it O(n).)
    • Space: O(n). by_time, series, and the output windows list (at most max(0, n - 7) tuples) each hold O(n) items.
  • Service & retries (get_decreasing_windows):
    • Calls & wait time: Performs 1 database lookup (O(1) via primary-key index on cities.id) and at most A Weather API requests (0 requests when abs(latitude) > 5.0). With defaults A = 5, base_delay = 0.5s, and max_delay = 30s, 5xx backoffs sleep at most 0.5 + 1 + 2 + 4 = 7.5s total, while four 429 waits capped at 30s sleep at most 120s.

Edge cases

  • Missing hour in the middle of a cooling streak: moment - prev_moment exceeds 1 hour, resetting run = 1 so no window can bridge the gap.
  • Equal adjacent temperatures (25.0, 25.0): Rejected by strict <, resetting run = 1 because plateaus are not strictly decreasing.
  • Fewer than 8 points or empty response ([]): run never reaches 8, returning [].
  • Latitude on the exact boundary (-5.0 or 5.0) vs outside (5.01, -7.0): Inclusive <= treats ±5.0 as equatorial; outside latitudes return [] without making any HTTP call.
  • Unknown city_id: Raises LookupError rather 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.0 in Python!), or conflicting duplicate hours are dropped into gaps, while identical duplicate records collapse cleanly into one.
  • 429 with HTTP-date, missing header, or huge Retry-After: Supports both integer delta-seconds and RFC 9110 HTTP-dates case-insensitively, falls back to exponential backoff if Retry-After is absent/malformed, clamps past HTTP-dates to 0.0s, and raises WeatherApiError immediately without sleeping if delay > max_delay.

Common mistakes

  • Checking points[i] vs points[i + 1] without comparing parsed timestamps: Silently accepts windows that skip over missing hours or off-grid readings like 03:30.
  • Using <= instead of < on temperatures: Accepts flat temperature plateaus as "strictly decreasing".
  • Retrying 400 / 401 / 404 responses: 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() on Retry-After: In Python, "²".isdigit() is True, causing an uncaught ValueError inside float("²").
  • Sleeping after the final failed attempt: Always guard self.sleep(delay) with if attempt < self.max_attempts - 1: so exhausting retries raises immediately.
  • Omitting HTTP timeouts or building SQL via f-strings: Calling requests.get(...) without timeout=(connect, read) can hang a worker forever, and string-interpolating city_id instead of parameterized %s risks SQL injection.

Alternative approaches

  • Sliding collections.deque of up to 8 points: Append each valid point to a deque (clearing the deque first whenever moment - deque[-1].moment != 1h or temp >= deque[-1].temp, and popping from the left when len > 8). It produces identical output, though the integer run counter achieves the same result with O(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 to random.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 5 backed by a B-tree index on latitude), then bucket nearby cities onto the weather provider's spatial grid (e.g. rounding coordinates to 0.1° ≈ 11 km) so 10 towns 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): at 50 req/s, 20,000 grid cells finish in 20,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 (typically 30–60 minutes), since forecasts do not change between model runs. Add request coalescing (single-flight) — if 40 concurrent requests ask for the same uncached grid cell simultaneously, 39 wait on the single in-flight HTTP call instead of firing 40 duplicate requests — and use stale-while-revalidate (serving slightly stale cached forecasts during background refreshes or 5xx outages). Also send If-None-Match (ETag) headers if the provider discounts 304 Not Modified responses.
  • 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, and clock into ForecastWindowService, then pass a scripted fake callable that pops pre-programmed ApiResponse objects or TimeoutError exceptions ([ApiResponse(502), ApiResponse(429, {"Retry-After": "4"}), ApiResponse(200, {}, points)]) while recording call arguments, paired with a fake sleep = delays.append that records wait durations ([0.5, 4.0]) instantaneously in 0 ms. Test find_decreasing_windows directly 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 thin requests adapter separately with responses or requests-mock.

Follow-up questions

Similar questions

More Versemedical interview questions

All 2 Versemedical questions →