Build a Pluggable Connector Layer for Third-Party Services
System DesignModel answerLast updated
Design a platform that lets a product authorize customer accounts at many external vendors, run actions against them, and ingest their events reliably, with new connectors cheap to add.
Pluggable Connector Layer for Third-Party Services
Your product needs to work with many external vendors, for example email providers and team-chat tools. A customer links their own vendor account, the product triggers operations on that account (send a message, create a record), and the product also receives things that happen on the vendor side (new message, status change) through webhooks or by polling.
Engineering wants to add a new vendor without re-implementing authentication, retries, throttling, and monitoring each time.
Design the platform. Cover:
- The connector contract: what each vendor plugin must provide and what the platform owns.
- Account linking, secret storage, rotation, and revocation.
- How an action travels from the caller to the vendor and back.
- How inbound events are received, verified, deduplicated, and delivered.
- The data model.
- How one misbehaving vendor is kept from harming others.
Constraints and assumptions
- Vendors differ in auth methods, quotas, pagination, webhook delivery guarantees, and error formats.
- Customer credentials and event payloads are sensitive.
- Both requests and events may arrive more than once and out of order.
- A slow, failing, or throttled vendor must not stall unrelated connectors.
- Explicitly state your assumptions about action latency and how much the payloads are normalized into a shared shape.
Questions worth asking the interviewer
- Which actions and events must be identical across all vendors, and which can stay vendor-specific?
- Does the caller wait for an action to finish, or can it complete asynchronously?
- If a vendor has no webhooks, how fresh must the data be?
- Do customers need control over data residency or retention?
Hints
Hint 1
Split the design into a stable platform lifecycle (link, execute, ingest, revoke) and a thin vendor-specific adapter. Do not force every vendor into one identical model; expose capabilities instead.
Hint 2
For actions, think about a durable job queue with idempotency keys, a classification of errors into retryable, non-retryable, and needs-reauthorization, and rate limiting keyed by vendor and by customer account.
Hint 3
For events, treat webhooks and polling as two sources feeding the same pipeline: verify, store the raw payload, deduplicate on a vendor event ID or content hash, then normalize and publish. Keep cursors for polling and support replay.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Actions are asynchronous by default. The API accepts a request, returns an operation ID, and the result is read by polling or a callback. A fast path can wait up to a few seconds for vendors that respond quickly.
- Normalization is partial. A small common core (message, contact, thread, with IDs, timestamps, and actor) is mapped to a shared schema. Everything else is kept in a vendor-specific extension field and the original raw payload.
- Scale for sizing: thousands of tenants, hundreds of vendor accounts per busy tenant, and peaks of a few thousand events per second.
Connector contract
Each connector is a plugin that implements a narrow interface. The platform owns the lifecycle, and the connector only translates.
manifest: vendor ID, version, auth type, supported actions and events, declared rate limits, and pagination style.authorizeandrefresh: build the consent URL, exchange codes for tokens, and refresh them.execute(action, input, credentials): perform the call and return a typed result or a typed error.subscribeandverify_webhook: register webhooks and validate signatures.poll(cursor): return new items and the next cursor.normalize(raw): map vendor payloads to the common schema plus extension fields.classify_error(response): map vendor errors to a small platform taxonomy.
Capabilities are declared in the manifest, so callers can ask "does this connector support threaded replies?" rather than assuming. Connectors are versioned, and a tenant's account is pinned to a version until migrated. This allows safe rollouts and rollback.
Authorization and secrets
- OAuth flows use PKCE and a signed
statevalue bound to the tenant and user, which prevents cross-tenant linking. - Tokens are stored encrypted with envelope encryption: a per-tenant data key wrapped by a KMS master key. Plaintext secrets exist only in memory in the worker for the duration of a call.
- Access tokens are refreshed proactively before expiry, with a per-account lock so concurrent workers do not race and invalidate a rotating refresh token.
- Revocation: on disconnect, call the vendor's revoke endpoint when available, delete the stored secrets, cancel pending jobs, and remove webhook subscriptions. If a vendor reports an invalid grant, mark the account
needs_reauthand notify the customer instead of retrying forever. - Every secret read and every action is audit-logged without logging the secret.
- Access is scoped by tenant at the data layer (tenant ID in every key and query), and workers receive credentials only for the account in the job.
Action execution path
- The API validates input against the connector manifest and writes an
operationrow plus an outbox entry in one transaction. The caller supplies an idempotency key, and a unique constraint on (tenant, key) makes retries return the same operation. - A dispatcher places the job on a queue partitioned by vendor and account, so one vendor's backlog is isolated.
- A worker takes a token from the rate limiter (token bucket per vendor app and per customer account, using the vendor's published limits and
Retry-Afterheaders), loads the credentials, and callsexecute. - The result is classified:
- Retryable (timeouts, 5xx, 429): retry with exponential backoff and jitter, honoring
Retry-After, up to a cap, then dead-letter. - Non-retryable (validation, permission): fail permanently with the vendor message surfaced.
- Auth failure: try one refresh, then
needs_reauth.
- Retryable (timeouts, 5xx, 429): retry with exponential backoff and jitter, honoring
- Sending to a vendor is not always idempotent. Where the vendor supports idempotency keys, pass ours. Otherwise record an
attemptstate before and after the call, and on ambiguous timeouts reconcile by querying the vendor before retrying, to avoid duplicate sends.
A circuit breaker per vendor stops calls after sustained failure and probes periodically, protecting both the vendor and our worker pool.
Event ingestion
Webhooks: a thin, stateless receiver verifies the signature (and timestamp, to limit replay), writes the raw payload to durable storage and a queue, and returns 2xx quickly. Everything else happens asynchronously. Routing to a tenant uses a per-subscription secret or URL token.
Polling: a scheduler runs per account with a stored cursor, at an interval chosen from required freshness and quota (for example 1 minute for premium accounts, 15 minutes otherwise), with jitter. Cursors advance only after items are durably stored.
Common pipeline: raw store, then deduplication on (account, vendor event ID), falling back to a content hash, then normalization, then publishing to internal consumers. Because delivery is at-least-once and unordered, consumers must be idempotent. Events carry a vendor timestamp and a per-entity version when available, so consumers can discard stale updates. Webhooks are not fully trusted: a periodic reconciliation poll catches missed events. Keeping raw payloads for a limited window enables replay after a normalization bug.
Data model
connector(id, version, manifest)account(id, tenant_id, connector_id, version, status, scopes, created_at)credential(account_id, encrypted_blob, key_id, expires_at)operation(id, tenant_id, account_id, action, idempotency_key, status, result_ref, attempts)subscription(account_id, type, external_id, secret_ref)cursor(account_id, stream, value, updated_at)event_raw(account_id, vendor_event_id, received_at, payload_ref)with a unique key for dedupevent(id, account_id, type, occurred_at, common_fields, extension)
Payloads sit in encrypted object storage with per-tenant retention policies and optional regional placement for residency requirements.
Failure isolation and backpressure
- Separate queues and worker pools per vendor (or per vendor tier), with concurrency limits, so a stuck vendor consumes only its own capacity.
- Per-tenant fairness: weighted queues or per-tenant concurrency caps stop one noisy customer from starving others.
- Bounded queues with load shedding or deferral; webhook receivers keep accepting because they only write to durable storage.
- Dead-letter queues with tooling for inspection and redrive.
Schema evolution
Treat the common schema as additive: new optional fields only, with explicit version numbers for breaking changes. Connectors emit the extension field for unmapped data, so vendor changes do not break consumers. Raw payload retention lets you reprocess after mapping changes.
Observability and onboarding
Per-connector dashboards: success rate, latency percentiles, throttling rate, retry counts, webhook lag, polling freshness, and needs_reauth counts, with alerts on deviations. Propagate a trace ID from request to vendor call to event.
New connectors ship with a test kit: recorded fixtures, a contract-test suite run against the interface, a sandbox account, and a staged rollout behind a feature flag.
Trade-offs and common mistakes
- Over-normalizing hides useful vendor features. Under-normalizing pushes complexity onto every consumer. A small core plus extensions is the compromise.
- Retrying non-idempotent sends blindly causes duplicates.
- Doing heavy work inside the webhook handler leads to timeouts and vendor-side disabling of the endpoint.
- Sharing one global rate limiter or worker pool lets one vendor stall the rest.
- Refreshing tokens without a lock breaks rotating refresh tokens.
- Logging full payloads or tokens creates a security exposure.