Sync Data from a Rate-Limited External API (3 req/s)
System DesignModel answerLast updated
Design a distributed service that ingests and keeps data fresh from a third-party API capped at exactly 3 requests per second.
The Setup
Your company depends on data that lives inside a third-party service. You need to build a backend pipeline that continuously pulls that data into your own database and keeps it reasonably fresh. The provider's API enforces a strict ceiling of 3 requests per second. Any request that exceeds this cap is refused outright.
The core design challenge is making that constraint work across a fleet of workers that run in parallel, possibly on multiple machines.
What You Don't Know Yet — Ask First
Good candidates spend a few minutes clarifying scope before drawing boxes. Consider questions like:
- Is the 3 req/s ceiling shared across your entire integration (one API key), or does each customer credential get its own independent allowance?
- Is the window a strict rolling one-second interval or a fixed calendar second? Does the provider return a
Retry-Afterheader or equivalent when you breach it? - Are you doing a one-time historical backfill, ongoing periodic syncs, or near-real-time streaming? All three at once?
- Does the provider offer bulk endpoints, large page sizes, filtering by modification timestamp, or push-based webhooks?
- Who reads the data after you store it, and what is the cost to them when it arrives late?
State your assumptions explicitly if the interviewer leaves these open.
Part 1 — The Ingestion Pipeline
Design the end-to-end components: what decides what to fetch, what makes the actual HTTP calls, how results are stored, and how downstream systems learn about new data.
Cover:
- The major components (scheduler, work queue, fetch workers, storage layer) and how they connect
- The data model for tracking sync state — what does a "job" or "checkpoint" record look like?
- The difference between a full backfill and an incremental sync, and when each applies
- How you make writes idempotent so re-fetching the same page twice does not corrupt data
- How consumers discover newly arrived or updated records
Part 2 — Enforcing the Global Rate Cap
Multiple workers running concurrently will happily blow past 3 req/s unless something coordinates them. A per-process counter is not enough — it cannot see the other processes.
Address:
- What mechanism enforces a single, shared limit across all workers and hosts?
- How does a worker "ask permission" before firing a request, and what does it do while it waits?
- How do you account for the provider's measurement window (rolling vs. fixed) and build in a small safety margin?
- When a request is rejected (HTTP 429), how do you handle the retry — backoff curve, jitter, and whether retries count against the same budget?
- What happens if the coordination layer (e.g., the rate-limiter store) becomes unavailable?
Part 3 — When Work Outpaces the Budget
At 3 req/s you get at most 10,800 requests per hour. If the data volume or freshness requirements demand more than that, something has to give.
Cover:
- The arithmetic: how do you calculate whether your budget is sufficient given data volume and target freshness SLA?
- Techniques to extract more value from each request (larger pages, delta queries, batch endpoints, conditional GET with ETags)
- How you prioritize work so a large historical backfill does not block time-sensitive incremental updates
- What fairness looks like when you pull data for multiple tenants that share one API key
- How you surface backlog depth and data lag to operators and to downstream consumers
Hints
Hint 1
Start with the rate-limit scope question. If the cap is per-credential rather than global, your architecture changes significantly — you might run isolated worker pools per credential instead of a single shared limiter.
Hint 2
A Redis token bucket or sliding-window counter is the standard answer for cross-process rate limiting. Walk through why a local in-process counter breaks under horizontal scaling before proposing the centralized solution.
Hint 3
Do the math out loud: 3 req/s × 60s × 60min = 10,800 req/hr. If you pull 1,000 records per page, that's 10.8 million records per hour maximum throughput. State that number, then derive what page size and freshness SLA you can actually meet.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifications to State Upfront
Before designing anything, nail down two things. First, is the 3 req/s cap shared across all your workers via a single API key, or does each tenant credential carry its own independent allowance? If the latter, you can run isolated pipelines per credential and the global-coordination problem mostly disappears. Assume the harder case: one shared key, one shared cap. Second, is the window a rolling one second or a fixed calendar second? Rolling is stricter; design for it.
Assume also: a mix of an initial backfill plus ongoing incremental sync, the provider supports pagination with a last_modified_after filter, and a 429 response includes a Retry-After value.
Part 1 — Pipeline Architecture
Components:
- Scheduler — runs on a cron or event trigger. For incremental syncs it reads a checkpoint store to find each resource's last-synced cursor (timestamp or page token) and enqueues fetch jobs. For a backfill it generates page-range jobs from 0 to N.
- Work queue — a durable queue (e.g., SQS, Kafka, Redis Streams). Each message describes one fetch unit: resource type, page or cursor, priority tier.
- Fetch workers — stateless processes that dequeue a job, acquire a rate-limit token (see Part 2), call the provider, and write results.
- Storage layer — idempotent upserts keyed on the provider's record ID and version. An
INSERT ... ON CONFLICT DO UPDATEpattern or a versioned document store works. The same page arriving twice produces the same stored state. - Checkpoint store — a small key-value record (e.g.,
{resource, last_cursor, updated_at}). Workers write this only after a successful upsert, so a crash mid-page re-fetches the page rather than losing it. - Change notification — after writing, publish record IDs to an internal event bus or update a
modified_atcolumn so downstream consumers can poll or subscribe.
Backfill vs. incremental: Backfill jobs enumerate all pages from the beginning. Incremental jobs use last_modified_after=<checkpoint> to fetch only what changed. Both share the same worker pool, but incremental jobs run at higher priority (see Part 3).
Part 2 — Global Rate Limiting
A per-process token bucket cannot see other processes. You need one shared counter.
Mechanism: Store a sliding-window counter in Redis. Before every outbound request a worker runs a Lua script that atomically checks the count of requests in the last 1,000 ms and either increments it (returning "go") or returns "wait" with the milliseconds until the oldest token expires. This is O(1) and atomic with no race conditions.
-- pseudocode for the Lua script
local now = tonumber(ARGV[1])
local window = 1000 -- ms
local limit = 3
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
local count = redis.call('ZCARD', key)
if count < limit then
redis.call('ZADD', key, now, now .. '-' .. math.random())
redis.call('PEXPIRE', key, window)
return 0 -- allowed, 0ms wait
else
local oldest = tonumber(redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')[2])
return (oldest + window) - now -- ms to wait
end
Workers sleep for the returned wait time before retrying the token acquisition. This naturally paces them to the rolling window.
Safety margin: Target 2.7 req/s in the limiter (90% of cap). This absorbs clock skew between workers and any latency in the Redis round-trip without risking a burst that hits the provider ceiling.
On a 429: Read Retry-After. If absent, use exponential backoff starting at 500 ms with ±25% jitter, capped at 30 s. Critically, the retry itself must still acquire a rate-limit token — a flood of retries can push you back over the cap. Put the job back on the queue rather than busy-looping in the worker.
Rate limiter unavailable: Fail closed by default — workers pause and do not fire requests. This is safer than failing open. A short grace period (e.g., 5 s) with a local fallback of 1 req/s per worker can prevent a complete stall if the Redis node is briefly unreachable, as long as no more than two workers apply this fallback simultaneously.
Part 3 — When Budget Is Insufficient
Do the math first: 3 req/s × 3,600 s = 10,800 req/hr. At 500 records per page, that's 5.4 million records per hour. If you have 20 million records and need full freshness every hour, you cannot do it. State this constraint explicitly and propose solutions, not magic.
Squeeze more from each request:
- Maximize page size (ask the provider for the largest allowed).
- Use
last_modified_afterfilters so you skip pages with no changes. This can drop incremental traffic by 90%+ in steady state. - Conditional GET with
ETag/If-None-Matchwhere supported — a 304 consumes your rate budget but not your processing pipeline. - Check for webhooks. If the provider can push changes, incremental polling may become unnecessary entirely.
Prioritization: Use two queue tiers — high (incremental updates, time-sensitive resources) and low (backfill, historical enrichment). Workers always drain high first and process low only when high is empty. Give incremental jobs a guaranteed floor: reserve at least 1 req/s for them even during a backfill, so a large historical job cannot fully starve fresh updates.
Multi-tenant fairness: If you pull for N tenants sharing one key, implement weighted fair queuing. Each tenant gets a share of the budget proportional to their tier or SLA. Track per-tenant request counts in a sliding window and skip a tenant's next job if they've consumed more than their fair share recently.
Observability:
requests_sent_per_second(gauge) — alert if it drifts above 2.9.rate_limit_rejections_total(counter) — any nonzero value is a warning sign.queue_depth_by_tierandoldest_job_age— direct indicators of backlog.data_lag_seconds_by_resource— the age of the most recently synced record vs. now. Expose this to consumers so they know when to distrust freshness.
When lag exceeds a defined SLA, surface it via a status endpoint that consumers can poll, and consider emitting a stale-data event rather than silently serving old records.
Common Mistakes to Avoid
- Per-worker rate limits that multiply with scale — four workers each allowing 3 req/s is 12 req/s.
- Ignoring the rolling window — a fixed-second counter allows bursts of 6 at the second boundary.
- Retries that bypass the limiter — they can cause a feedback loop that amplifies violations.
- No checkpoint — a worker crash re-fetches from scratch, wasting your entire budget on a backfill.
- No fairness policy — one runaway backfill consumes all 10,800 hourly requests and incremental updates stop.