Build a Near-Real-Time Environmental Data Feed API
System DesignModel answerLast updated
Design a platform that polls an external sensor API hourly for ~2,000 U.S. locations and serves current readings with a strict 10-minute freshness guarantee.
Scenario
A third-party environmental sensor network publishes hourly data snapshots for roughly 2,000 monitoring stations across the United States. Your company wants to expose this data to internal dashboards and external clients through a clean API that always returns the current reading for any station.
Non-negotiable requirement: every response must reflect a reading no older than 10 minutes past the provider's most recent publish time.
What You Need to Design
1. High-Level Architecture
Sketch the major components: how data gets in, where it lives, how it gets cached, and how clients read it. Identify the scheduler or orchestrator that drives ingestion.
2. API Contract
Define the endpoint(s) clients will call. At minimum, support lookup by station ID and by geographic coordinates (return the nearest covered station). Include:
- Request parameters and response schema
- Freshness metadata in the response
- Versioning strategy
- All meaningful error cases (missing station, stale data, client rate limits, etc.)
3. Data Model and Storage
Choose your database(s). Define the schema for stations and for time-series observations. Explain your partitioning and retention approach, your indexing choices, and how raw upstream payloads are preserved for replay or auditing.
4. Ingestion Pipeline
Walk through every stage from "provider publishes new data" to "data is queryable":
- How do you detect a new publish?
- How do you fan out work across ~2,000 stations while staying within the provider's rate limit (assume ~20 req/s)?
- How do you handle retries, deduplication, and idempotent writes?
- How do you backfill gaps caused by transient failures without starving the current hour's ingestion?
5. Caching and Invalidation
Describe your full caching stack (in-process, distributed cache, optional CDN). Explain TTL choices, how cache entries get invalidated when new data arrives, and where the read API enforces the freshness hard limit.
6. Scaling and Capacity
Estimate writes per second, peak read QPS, hot data set size, and annual storage. Show how the system handles traffic spikes (e.g., a major weather event drives 50× normal read traffic).
7. Deployment, Cost, and Security
Cover API authentication, secrets management for the upstream credential, cost levers, and any deployment topology decisions.
8. Observability and Failure Handling
Define the key metrics and alerts that let you know you are about to breach the freshness SLA before it actually breaches. Describe graceful degradation when the upstream is slow, partially unavailable, or fully down.
9. Multi-Region Availability and Recovery
What are your RPO and RTO targets? How do active-active or active-passive setups affect ingestion correctness?
What a Strong Answer Looks Like
The data volume here is small enough that storage is almost a non-issue. A strong candidate recognizes this early and focuses their energy on the freshness budget, rate-limit-aware ingestion, idempotency, and degradation behavior. Bring numbers: show the math on your 10-minute budget and your QPS/storage estimates.
Hints
Hint 1
Start by decomposing the 10-minute freshness budget into explicit per-stage allowances (detect, fetch, write, propagate, serve). Every architecture decision should be justified against those numbers.
Hint 2
The provider rate limit (~20 req/s) means fetching all 2,000 stations takes roughly 100 seconds. That alone consumes most of the budget, so figure out that math before designing the ingestion queue.
Hint 3
Idempotency and deduplication are not the same thing. An idempotent write means re-running the same job produces the same DB state; deduplication means you don't re-process the same payload twice. You need both, and a compound primary key like (station_id, observed_at) gives you the former for free.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
Before drawing any boxes, establish what you are actually optimizing for. The data volume is trivial: ~2,000 rows per hour, roughly 5 GB of history per year. The hard part is the 10-minute end-to-end freshness SLA against a rate-limited, best-effort upstream. Say this explicitly early — it signals to your interviewer that you know where the real complexity lives.
Step 1: Clarify and Estimate
Questions to ask:
- Does the provider publish a bulk dump or require a per-station call? (Assume per-station, ~20 req/s limit.)
- Is there a "latest publish version" endpoint or webhook? (Assume a version endpoint; treat webhooks as a bonus signal.)
- What does "10 minutes stale" mean precisely — from provider publish time, or from observation time? (From publish time.)
Back-of-envelope:
| Item | Estimate |
|---|---|
| Ingestion write rate | 2,000 rows/hour ≈ 0.6 writes/s (burst, not steady) |
| Time to fetch all stations | 2,000 ÷ 20 req/s = ~100 s |
| Row size | ~300 B → ~5 GB/year of history |
| Hot data set | 2,000 stations × ~500 B ≈ ~1 MB — fits in memory on any node |
| Average read QPS | ~1,000; peak during major events ~50,000 |
| Cache hit rate target | >99% (the hot set is tiny) |
10-minute budget broken down:
| Stage | Allowance |
|---|---|
| Detect new publish | ≤ 1 min |
| Fetch all 2,000 stations | ~2 min (parallel workers) |
| Validate, write to DB, propagate to cache | < 1 min |
| CDN / in-process cache TTL drain | ≤ 90 s |
| Buffer | ~4.5 min |
This math shows you can comfortably meet the SLA with a few parallel ingestion workers — you do not need a streaming platform.
Step 2: Architecture Overview
Scheduler (cron, 1-min poll)
└─> detects new version H
└─> enqueues 2,000 jobs into Job Queue (SQS / lightweight Kafka topic)
└─> Ingestion Workers (auto-scaled, shared token bucket in Redis)
└─> Postgres (upsert on (station_id, observed_at))
└─> CDC event / post-commit hook
└─> Cache Updater → Redis (write-through)
Clients → CDN (max-age=60s) → API Gateway (auth, rate limit) → Read API pods
└─> in-proc cache (30 s TTL)
└─> Redis
└─> Postgres (fallback)
Step 3: API Contract
GET /v1/readings?stationId=chi-042
GET /v1/readings?lat=41.88&lon=-87.63[&maxDistanceKm=50]
200 response:
{
"station": {"id": "chi-042", "name": "Chicago O'Hare", "lat": 41.98, "lon": -87.90, "distanceKm": 12.1},
"reading": {"value": -3.2, "unit": "C"},
"observedAt": "2024-01-10T15:00:00Z",
"providerPublishedAt": "2024-01-10T15:02:44Z",
"ingestedAt": "2024-01-10T15:04:11Z",
"dataVersion": "2024011015",
"stale": false
}
Key headers: Cache-Control: max-age=60, ETag, X-Data-Age-Seconds.
Error cases:
| Status | Condition |
|---|---|
| 400 | Bad params, conflicting params, coordinates out of range |
| 404 | Unknown stationId; or no covered station within maxDistanceKm |
| 429 | Client rate limit exceeded |
| 503 | Best available data exceeds hard staleness cap (~3 h); include Retry-After |
Nearest-station lookup: Load all 2,000 points into an in-memory KD-tree (or geohash grid) in each API pod. A lookup is microseconds. Rebuild on any location table change. Never issue a spatial DB query per request — unnecessary at this scale.
Versioning: /v1/ in the path. Changes within a version must be additive only. ?units=F for Fahrenheit conversion.
Step 4: Ingestion Pipeline
-
Detect. The scheduler polls the provider's version endpoint every minute. When it sees a version ID newer than the last successful run, it inserts a row into
ingestion_runsusingINSERT ... ON CONFLICT DO NOTHING— so only one scheduler wins even if you run multiple for redundancy. -
Fan out. Enqueue 2,000 messages
{version, stationId}. If the provider offers a bulk dump, enqueue a single streaming job that splits the payload. -
Fetch with rate limiting. Workers pull from the queue and share a Redis token bucket configured to 18 req/s (10% below the provider limit as headroom). On 429 or 5xx, retry with exponential backoff and jitter capped at 60 s, honoring
Retry-After. Exhausted retries go to a dead-letter queue (DLQ). -
Validate. Check schema, confirm
observed_atmatches the declared version hour, and reject implausible values (e.g., temperature outside −80 to 60 °C). -
Write idempotently. Upsert on
(station_id, observed_at). Only overwrite if the incomingdata_versionis ≥ the stored one. This makes redelivery a safe no-op. -
Propagate. After the DB commit, write-through to Redis using a Lua compare-and-set on
data_versionto prevent an older retry from overwriting newer data. Publish anobservation.updatedevent. -
Backfill. A reconciler runs every 10 minutes, finds
(station, hour)gaps in the last 24 hours and DLQ items, and re-enqueues them at low priority using a separate, smaller token budget — so backfill can never crowd out current-hour ingestion.
Step 5: Caching and Freshness Gate
Redis is write-through on every successful ingest. No correctness dependency on TTL; set a 2-hour TTL as a safety net only.
In-process cache in API pods uses a 30-second TTL and additionally evicts on observation.updated events via Redis pub/sub. Worst-case staleness added: 30 s.
CDN (for public traffic): max-age=60, stale-while-revalidate=30. On a new version, issue a surrogate-key purge for version-current. Worst-case staleness added: ~90 s.
Total worst-case propagation from DB write to client: under 2 minutes — well within budget.
Read API freshness gate: Before returning a response, compute now() - providerPublishedAt. If this exceeds a configurable hard cap (e.g., 3 hours), return 503 with a stale: true body and a Retry-After header rather than serving silent garbage. The stale field in normal responses is also set to true if the age exceeds a soft threshold (e.g., 15 minutes) without hitting the hard cap.
Step 6: Scaling
The hot data set is ~1 MB, so a single Redis node handles all read traffic. At 50,000 read QPS, the CDN absorbs >99% of requests — the origin sees ~500 QPS, which a handful of API pods handle trivially.
Ingestion workers are stateless and auto-scale; the token bucket in Redis enforces the provider rate limit regardless of worker count.
Postgres is sized for ~5 GB/year with monthly partitioning on observed_at. Older partitions are archived to object storage (S3/GCS) as Parquet for analytics. No sharding needed.
Step 7: Observability and Failure Handling
Key metrics to alert on:
ingestion_lag_secondsper version: alert when approaching 8 minutes (before the SLA breaches).cache_miss_rateon Redis: unexpected spikes indicate a propagation failure.- DLQ depth: non-zero means stations are silently missing data.
data_age_secondshistogram on the Read API: P99 should stay under 8 minutes.
Graceful degradation:
- If the upstream is slow, workers continue retrying within the budget. The freshness gate prevents stale data from going out silently.
- If the upstream is fully down, serve the last known data with
stale: trueup to the hard cap, then 503. - If Postgres is degraded, the Read API falls back to Redis and logs the miss — the hot set almost never requires a DB read anyway.
Multi-region: Run ingestion in one primary region and replicate the DB to a secondary. RTO ~5 min (promote replica, restart workers). RPO ~1 min (streaming replication). Ingestion should run in only one region at a time to avoid double-fetching against the rate-limited upstream; use a distributed lock or leader lease.
Common Mistakes to Avoid
- Setting a Redis TTL equal to the SLA — this creates a correctness dependency on TTL expiry rather than active invalidation. TTLs should be safety nets, not the primary invalidation mechanism.
- Ignoring the 100-second fetch window — candidates who skip the rate-limit math often propose architectures with a single sequential worker, which blows the budget.
- No backfill strategy — transient failures leave silent gaps; without a reconciler, those gaps persist indefinitely.
- Spatial DB queries per request — at 2,000 points, an in-memory structure is orders of magnitude cheaper and simpler.