Detect 8-Hour Cooling Streaks in a Flaky Forecast Feed
Arrays & HashingModel answerLast updated
Build a service that checks a city's latitude, pulls a 72-hour forecast from an unreliable API with proper retries, and returns every 8-hour span of strictly falling, gapless hourly temperatures.
Task
Write a function get_decreasing_windows(city_id) that reports every 8-hour stretch in which the forecast temperature falls at every step.
What the function must do
- Look up the city. Use a PostgreSQL query to get the latitude and longitude for
city_id. Continue only if the city is near the equator, meaning latitude from -5 to 5 degrees inclusive. - Fetch the forecast. Request the next 72 hours of hourly data from an external weather service. It returns a list of records shaped like
{'timestamp': 'YYYY-MM-DDTHH:MM:SSZ', 'temp': float}. - Handle an unreliable service.
- Retry server errors (5xx) using exponential backoff.
- On a 429 response, wait for the duration given in the
Retry-Afterheader before trying again.
- Find the windows. A window is 8 consecutive hourly readings
t[i], t[i+1], ..., t[i+7]wheret[i] > t[i+1] > ... > t[i+7]. - Respect data continuity. If any hour is absent from the response inside a candidate window, that window is invalid.
Signature
def get_decreasing_windows(city_id: int) -> List[Tuple[str, str]]:
# returns (start_timestamp, end_timestamp) for each valid window
Example
Temperatures, one per hour starting at 2023-10-01T00:00:00Z: [30, 29, 28, 27, 26, 25, 24, 23, 22, 24]
- Indices 0-7:
30 ... 23, strictly decreasing, valid. - Indices 1-8:
29 ... 22, strictly decreasing, valid. - Indices 2-9: ends with
22, 24, not valid.
Result: [('2023-10-01T00:00:00Z', '2023-10-01T07:00:00Z'), ('2023-10-01T01:00:00Z', '2023-10-01T08:00:00Z')]
Edge cases to cover
- Missing hours in the response.
- A city outside the equatorial band.
- Fewer than 8 data points in total.
What to cover in your answer
Describe how you would structure the code, the retry and error policy, the window-detection algorithm with its complexity, and how you would test it. Include code.
Hints
Hint 1
Separate the work into three pieces: the database lookup plus latitude check, the HTTP client with retries, and a pure function that takes records and returns windows. The last one is easy to unit test with no mocks.
Hint 2
You do not need to re-examine 8 values for each starting index. Keep a running count of how many consecutive valid steps end at the current element, and reset it whenever the time difference is not exactly one hour or the temperature fails to drop.
Hint 3
Treat each failure class differently: retry network errors and 5xx with backoff and jitter, obey Retry-After on 429 (with an upper cap), and fail immediately on other 4xx. When retries run out, raise an error rather than returning an empty list, so callers can tell failure from 'no windows'.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the function into three layers, each testable alone:
- Data access. A parameterized query fetches
(latitude, longitude)for the city, followed by a guard-5 <= lat <= 5(inclusive). - Fetching with resilience. An HTTP loop that treats each failure class differently.
- Pure detection logic. A single linear pass over the sorted readings.
Detection algorithm
The tempting approach is to check all 8 values for every starting index, which costs O(8n). A cleaner approach tracks run, the length of the valid chain ending at index j.
Reading j extends the chain when both hold:
- its timestamp is exactly one hour after the previous reading, and
- the previous temperature is strictly greater than the current one.
Otherwise run resets to 1. Whenever run >= 8, the window [j-7, j] is valid and is emitted.
Why it is correct. A window is valid exactly when all 7 adjacent pairs inside it have a one-hour gap and a strict drop. run >= 8 at j says the 7 pairs ending at j all satisfy that. So the output is exactly the set of valid windows, in chronological order.
Gaps need no special code: a missing hour produces a delta of two hours or more, which resets the chain. Duplicate timestamps (delta 0) and equal temperatures also reset it, since they are not strict drops.
Walking through the example: at index 7, run hits 8 and window 0-7 is emitted. At index 8, run is 9 and window 1-8 is emitted. At index 9, 24 > 22 fails the drop test, so run resets to 1. Two windows result, as expected.
Resilience policy
| Condition | Action |
|---|---|
| Network error or timeout | Retry with exponential backoff and jitter |
| 5xx | Same as above |
| 429 | Wait for Retry-After (seconds or HTTP-date), capped; fall back to backoff if the header is missing or malformed |
| Other 4xx | Fail immediately, since retrying will not help |
| Retries exhausted | Raise an exception |
Use a bounded number of attempts (say 5), a base delay of 0.5 s doubling each time, and a cap of about 30 s per wait. The cap matters: a hostile or buggy Retry-After: 86400 should not freeze a worker. Jitter prevents many clients from retrying in lockstep. Set a request timeout so a hung connection does not block forever.
Edge cases
- City not found: raise
LookupError. It is a caller error and should not look like "no windows". - Non-equatorial city: return
[]before calling the API, saving quota and latency. - Fewer than 8 readings: the scan naturally returns
[]. - Unsorted, duplicated or malformed records: sort by parsed timestamp first, and drop records that fail to parse. A dropped record creates a gap, so it can never create a false window.
- Retries exhausted: raise rather than return
[]. Returning an empty list would be indistinguishable from a real "nothing found" answer.
Complexity
- Time: O(n log n) for the defensive sort plus O(n) for the scan, with n at most 72. Network latency dominates by orders of magnitude.
- Space: O(n).
Code
import os, random, time
from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from typing import Callable, List, Optional, Tuple
import psycopg2
import requests
WINDOW = 8
ONE_HOUR = timedelta(hours=1)
TS_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
MAX_ATTEMPTS = 5
BASE_DELAY, MAX_DELAY, REQUEST_TIMEOUT = 0.5, 30.0, 5.0
class WeatherAPIError(Exception):
pass
def fetch_city_coords(conn, city_id: int) -> Tuple[float, float]:
with conn.cursor() as cur:
cur.execute("SELECT latitude, longitude FROM cities WHERE id = %s", (city_id,))
row = cur.fetchone()
if row is None:
raise LookupError(f"city {city_id} not found")
return float(row[0]), float(row[1])
def is_equatorial(lat: float) -> bool:
return -5.0 <= lat <= 5.0
def _parse_retry_after(value: Optional[str]) -> Optional[float]:
if not value:
return None
try:
return max(0.0, float(value))
except ValueError:
pass
try:
dt = parsedate_to_datetime(value)
return max(0.0, (dt - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError):
return None
def _backoff(attempt: int) -> float:
return min(MAX_DELAY, BASE_DELAY * 2 ** attempt) * random.uniform(0.5, 1.0)
def fetch_forecast(lat, lon, session, sleep: Callable[[float], None] = time.sleep) -> list:
url = os.environ["WEATHER_API_URL"]
params = {"lat": lat, "lon": lon, "hours": 72}
for attempt in range(MAX_ATTEMPTS):
last = attempt == MAX_ATTEMPTS - 1
try:
resp = session.get(url, params=params, timeout=REQUEST_TIMEOUT)
except (requests.ConnectionError, requests.Timeout) as exc:
if last:
raise WeatherAPIError("network failure") from exc
sleep(_backoff(attempt))
continue
status = resp.status_code
if status == 200:
return resp.json()
if status == 429:
wait = _parse_retry_after(resp.headers.get("Retry-After"))
delay = min(MAX_DELAY, wait if wait is not None else _backoff(attempt))
elif 500 <= status < 600:
delay = _backoff(attempt)
else:
raise WeatherAPIError(f"non-retryable status {status}")
if last:
raise WeatherAPIError(f"retries exhausted (last status {status})")
sleep(delay)
raise WeatherAPIError("unreachable")
def find_decreasing_windows(records: list) -> List[Tuple[str, str]]:
points = []
for r in records:
try:
s = r["timestamp"]
ts = datetime.strptime(s, TS_FORMAT).replace(tzinfo=timezone.utc)
points.append((ts, float(r["temp"]), s))
except (KeyError, TypeError, ValueError):
continue
points.sort(key=lambda p: p[0])
out, run = [], 0
for j, (ts, temp, _) in enumerate(points):
if j == 0:
run = 1
else:
pts, ptemp, _ = points[j - 1]
run = run + 1 if (ts - pts == ONE_HOUR and ptemp > temp) else 1
if run >= WINDOW:
out.append((points[j - WINDOW + 1][2], points[j][2]))
return out
def get_decreasing_windows(city_id: int, *, conn=None, session=None,
sleep: Callable[[float], None] = time.sleep):
own = conn is None
if own:
conn = psycopg2.connect(os.environ["DATABASE_URL"])
try:
lat, lon = fetch_city_coords(conn, city_id)
finally:
if own:
conn.close()
if not is_equatorial(lat):
return []
session = session or requests.Session()
records = fetch_forecast(lat, lon, session, sleep)
return find_decreasing_windows(records)
Injecting conn, session and sleep lets tests run without a database, a network, or real waiting.
Testing
- Pure logic: the given example, a gap in the middle, equal adjacent temperatures, shuffled input, fewer than 8 points, and exactly 8 points.
- Fetching: a fake session that returns 503 twice then 200, a 429 with numeric and date
Retry-After, a malformed header, a 404, and total exhaustion. Assert on the delays passed to the fakesleep. - Boundaries: latitude exactly 5 and -5 (included), 5.01 (excluded).
Common mistakes
- Rechecking every window from scratch instead of using a running count.
- Testing only temperatures and ignoring timestamp gaps.
- Using
>=where a strict drop is required. - Retrying all 4xx errors, or sleeping for an unbounded
Retry-After. - Returning
[]after failed retries, which hides outages. - Building the SQL with string formatting rather than parameters.