Building a Resumable Multi-Tenant Partner API Ingestor
System DesignModel answerLast updated
Design an ingestion service that pulls from thousands of heterogeneous partner APIs with resumable checkpoints, raw-first staging, fair per-tenant throttling, and replayable normalization.
Context
Platforms that sit on top of commerce, CRM, and payment systems must continuously mirror data out of partner APIs: customer profiles, product catalogs, and transaction events. Every partner behaves differently — some paginate with opaque cursor tokens, some with page numbers and offsets, some with a since timestamp. They throttle hard and inconsistently, they sometimes return malformed payloads, and they add, rename, or drop fields with no warning.
You are designing the ingestion tier that sits between those partner APIs and your internal stores.
Required behavior
- Two sync modes: recurring incremental syncs on a schedule, plus ad-hoc historical backfills triggered by customers or support.
- Resumable progress: a sync that is paused, cancelled, or interrupted by a worker dying must pick up where it stopped instead of starting over.
- Raw before normalized: persist the untouched partner payload first, and derive canonical entities from it in a separate stage.
- Schema drift tolerance: unknown fields, missing fields, or changed types must not drop payloads or stall the pipeline.
- Replayability: if mapping logic changes or a downstream store loses data, re-derive canonical records from stored raw data without re-calling partners.
- No double counting: ingestion may deliver a record more than once, but canonical writes must be idempotent so duplicates are invisible.
- Per-tenant fairness: each connection has its own external quota (roughly 2–40 requests/sec per API key). A slow or failing connection must not starve the rest.
- Operational visibility: metrics and alerts for sync lag, quota exhaustion, error rates, and dead-letter volume.
Assumed scale
Roughly 25,000 active connections across several platforms; on the order of 300 million records per day (about 3.5K/sec average, up to 15K/sec at peak).
What to produce
Cover the overall architecture, how checkpoint/state is persisted, how rate limiting and fair scheduling work, how errors are classified and retried, and how raw storage plus versioned normalization deliver replayability and drift tolerance. Be explicit about write ordering and which crash scenarios it protects against.
Hints
Hint 1
Run the arithmetic first: at 100–250 records per page, 15K records/sec is only ~50–150 outbound calls/sec — the real bottleneck is per-connection quota and skew, not raw throughput.
Hint 2
Break each sync into page-sized tasks and fix the durable write order to 'raw object → manifest + checkpoint in one transaction → publish via outbox', so a cursor can never advance past data you failed to persist.
Hint 3
Rate limit with a per-(platform, credential) token bucket acquired before the outbound call, and have the scheduler skip connections with no tokens instead of letting workers block on them.
Hint 4
Classify errors into transient, auth, and permanent-request buckets — only transient ones warrant retries; the rest go to a dead-letter queue or trigger pausing the connection.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Turn the numbers into constraints
The headline volume looks imposing but isn't the hard part. At 300M records/day — ~3.5K/sec average, 15K/sec peak — with 100–250 records per API page, you need only ~50–150 outbound requests per second at peak. Compute is cheap. The genuine difficulty is fairness under heterogeneous quotas and skew: a single enterprise merchant backfilling three years of orders against a 2 rps key generates millions of calls while a thousand small shops queue behind it.
Storage math: at ~2 KB per raw record that's ~600 GB/day uncompressed, ~120 GB/day gzipped, so ~45 TB for a year of retention — clearly object-storage territory, not a relational database.
Worth clarifying before diving in: are inbound webhooks in scope (treat them as just another source landing in the same raw layer)? What freshness SLA applies to incremental syncs (assume p95 under 15 minutes)? Which stores consume canonical entities (say, a profile store and an event stream)? Stating "the hard part here is per-tenant fairness, not throughput" early signals seniority.
2. Architecture overview
Scheduler ──► per-connection virtual queues ──► Fetch workers ──► Raw store (object storage)
▲ (fair dispatch) │ ▲ │
│ ▼ │ │ manifest + outbox (Postgres)
Cron / control API Redis token buckets per ▼
(platform, credential) Kafka: raw-pages (key=connection)
│
▼
Normalizers (versioned per-platform mappers)
│ │
▼ ▼
Canonical upserts (idempotent) Quarantine / DLQ
│
▼
Kafka: canonical ──► downstream consumers
The pivotal decision: each sync job is split into page-sized tasks. A worker leases one task, fetches one page, persists it, advances the checkpoint, and releases the lease. Tasks last seconds, so a worker crash costs at most one page; short tasks also make fair scheduling and throttling tractable. Fetching is network-bound and normalization is CPU-bound, so decoupling them through raw storage plus a queue means a mapper bug never forces you to re-hit partner APIs.
3. Control-plane schema (Postgres)
connections(id, tenant_id, platform, credential_ref, status, rate_policy)— status isactive | paused | auth_failed.sync_jobs(id, connection_id, mode, entity, range_start, range_end, priority, state).checkpoints(job_id PK, cursor_token, high_watermark_ts, next_page_seq, lease_owner, lease_expires_at, version).page_manifest(job_id, page_seq, object_key, record_count, checksum, fetched_at), unique on(job_id, page_seq).outbox(id, page_ref, published_at).- Canonical store keyed by
(tenant_id, entity_type, source_system, source_id), each row carryingsource_updated_at,mapper_version, and anextras JSONBcolumn for drifted fields.
4. Checkpointing: the write order that prevents both skips and loss
For each page, exactly this sequence:
- Write the raw page to object storage at a deterministic key:
raw/{tenant}/{connection}/{entity}/{job}/{page_seq}.json.gz. Deterministic keys mean a retry overwrites the same object rather than creating a duplicate. - One Postgres transaction: insert the
page_manifestrow, insert anoutboxrow, and advance the checkpoint (cursor_token,next_page_seq+1,high_watermark_ts) guarded byWHERE version = :expected AND lease_owner = :me. - An outbox relay publishes page references to Kafka and stamps
published_at. This gives at-least-once delivery; duplicates are absorbed by idempotent consumers.
Crash analysis: crash before step 2 and the cursor never moved — the page is refetched and the same object key overwritten. Crash after step 2 and the page is durable and will be published. The cursor can never point past data that isn't durably stored. The version column fences out zombie workers whose leases expired, so they cannot clobber newer progress.
For incremental syncs, track high_watermark_ts = max(updated_at seen) and start the next run at watermark − overlap (say five minutes) to absorb clock skew and ties on identical timestamps. The overlap manufactures duplicates, which dedup handles. If a partner issues opaque cursors that expire, keep the timestamp watermark as a restart fallback.
Downstream, canonical writes are upserts keyed on source identity, applied only when the incoming source_updated_at is newer — that is what makes at-least-once ingestion invisible to consumers.
5. Rate limiting and fair scheduling
Keep a distributed token bucket in Redis per (platform, credential), implemented as an atomic script; refill rate and burst come from that connection's rate_policy. Workers acquire a token before calling out, so you throttle yourself instead of letting the partner throttle you — repeated 429s can escalate into bans. Adapt the bucket: honor Retry-After, re-sync from quota headers where platforms expose them, multiplicatively cut on a 429 and recover additively.
For dispatch, avoid modeling 25,000 Kafka partitions. The scheduler keeps per-connection virtual queues and selects work with deficit round-robin across connections that currently hold tokens. A connection with an empty bucket is simply skipped — it never occupies a worker. That's the source of isolation: a throttled tenant re-queues its task with a delay instead of sleeping in a thread. Add bulkheads — separate worker pools per platform — so a Salesforce outage can't consume capacity earmarked for Shopify syncs.
6. Failure classification and retries
| Class | Examples | Action |
|---|---|---|
| Transient | 5xx, timeouts, 429 | Exponential backoff with full jitter, capped; honor Retry-After |
| Auth | 401/403, revoked token | Pause the connection, notify the merchant, no retry storm |
| Permanent request | 400, 404 on a resource | Route the task to the DLQ with context; continue the job |
| Poison payload | unparseable body, type explosion | Quarantine the page, keep the raw object, alert |
Cap retries per page (say 5) before DLQing, and never let one page block the job's other pages — record the failure in the manifest and move on. Partial-page failures are handled by treating the page as the atomic unit: either it lands fully or it's DLQ'd; individual bad records inside a page are split out into quarantine with their raw JSON preserved.
7. Drift, raw preservation, and replay
Raw objects are the source of truth. Normalizers are pure functions over a raw page plus a mapper_version, so they can be rerun at will. When mapping logic changes, submit a replay request naming (connection, entity, time range, mapper_version); a replay worker reads raw objects and re-emits to the canonical topic. Unknown fields land in extras JSONB rather than being dropped; missing fields become nulls with a drift counter incremented; type surprises go to quarantine instead of breaking the mapper. Emit a per-platform "new field observed" metric so schema evolution is visible, not silent.
8. Observability
Track per-connection sync lag (now minus high watermark), page latency, 429/5xx rates, token-bucket utilization, lease expiry count, DLQ depth, and replay progress. Alert on: lag over SLA, sustained 429s (quota policy too aggressive), auth failures (merchant action needed), and DLQ growth rate. Per-platform dashboards make it trivial to see whether an outage is one partner or the whole fleet.
Common mistakes: advancing the cursor before the raw write (loses data on crash), one Kafka partition per connection (unmanageable), blocking workers while waiting on throttled tenants (head-of-line blocking), retrying auth failures, and normalizing inline with fetching so a mapper bug requires re-calling partners.