Third-Party and SaaS Integration Questions
Engineering a client against external provider and SaaS APIs you do not control: reading unfamiliar vendor docs and judging how far to trust them, handling provider auth and credential lifecycle (storing, rotating and revoking customer-granted credentials, refreshing a shared token safely, keeping secret keys out of client apps), living within vendor rate limits and quotas (prioritising urgent work, sharing one vendor key fairly across tenants), timeouts, retries with backoff and jitter and idempotency against flaky dependencies including writes of unknown outcome and partial batch failures, graceful degradation, circuit breaking and queue isolation when a provider is slow or down, mapping external data models to internal ones, connector and adapter design, anti-corruption layers, syncing records between SaaS systems, sandbox and contract testing against vendor APIs, and managing vendor-specific quirks, breaking changes, outages, failover and temporary integrations across many integrations. Examples span CRM, payments, shipping, messaging and AI service providers. Excludes diagnosing an individual failing call, webhook receipt mechanics, authentication protocol internals, rate limiter algorithms, API versioning policy for your own API, enterprise-wide integration architecture, bulk data ingestion into a warehouse, and choosing or contracting the vendor.
What does it mean for an operation to be idempotent, and why does it matter when your client retries calls to a vendor API? Which HTTP methods are idempotent in theory, and when does that not hold in practice?
Sample Answer
The idea in plain words
An operation is idempotent when doing it once and doing it several times in a row leave the system in the same state. The word is about the effect on the server, not about getting identical responses. It matters for a vendor client because networks lose answers: when a call times out you cannot tell whether the vendor did the work, and the only safe reaction is to send it again. That is only safe when sending it twice equals sending it once.
HTTP methods in theory
RFC 9110 (an RFC, short for request for comments, is a numbered Internet specification document; this one defines how HTTP behaves, and you can follow this card without reading it) defines the method properties. Idempotent methods are GET, HEAD, OPTIONS, TRACE, PUT and DELETE. POST and PATCH are not defined as idempotent. "Safe" is a stronger property: a safe method (GET, HEAD, OPTIONS, TRACE) is not expected to change server state at all, while PUT and DELETE are idempotent but not safe.
| Method | Idempotent | Safe | Why |
|---|---|---|---|
| GET, HEAD | yes | yes | Read only. |
| PUT | yes | no | Replaces the whole resource with the body; replaying writes the same body again. |
| DELETE | yes | no | After the first delete the resource is gone; deleting again leaves it gone. |
| POST | no | no | Typically creates something or triggers an action; each call can add another. |
| PATCH | not by definition | no | Depends on the patch: "set status to paid" is repeatable, "add 5 to the balance" is not. |
Worked example with numbers
Assume an account balance of 100 and a retry that fires twice because the first response was lost (so the vendor received the request three times in total, but each time the client believes it is sending the same logical request).
- POST /charges with amount 20, received once: 100 - 20 = 80.
- The same POST received three times: 100 - 20 - 20 - 20 = 40. The customer is charged 60 instead of 20.
- PUT /subscriptions/42 with body {"plan": "pro"} received three times: the plan is "pro" after the first and stays "pro". State equals the single-call state.
- DELETE /contacts/7 received three times: the first call returns 204, the second and third usually return 404. The responses differ but the state (contact 7 is absent) is identical, so it is still idempotent. Your client must therefore treat a 404 on a retried DELETE as success, not as an error.
- The same POST /charges received three times with the same idempotency key: the vendor acts on the first and returns the stored result for the other two, so 100 - 20 = 80, exactly as for a single call.
When theory and practice disagree
Idempotent describes the state of the resource the method targets; real systems have side effects around it.
- A GET that increments a view counter, writes an audit row (a log entry recording who did what) or triggers a billing meter (a counter used to charge for usage) is "safe" on paper but not in effect. Repeating it changes something. Usually harmless, sometimes billed.
- A PUT that the server stamps with updated_at, a version number or a new revision id changes state on every call, even though the user-visible fields are the same. Optimistic concurrency means a write is accepted only if the resource is unchanged since you read it: the server labels each version with an ETag (an opaque version label sent in a response header), and your PUT carries
If-Matchwith that label (meaning: do this only if the resource still has this version). If the first attempt succeeded, the resource now has a new ETag, so the replay carries a stale label and the server answers 412 Precondition Failed even though PUT is idempotent. A client that sees 412 on a replay should re-read the resource and check whether its change is already there. - A PUT or PATCH that a vendor implements as "append" or "increment" violates the contract, whatever the verb says. Read the vendor's documentation rather than trust the verb.
- DELETE of a collection member can shift later items if the vendor addresses them by position.
- Vendors sometimes document PUT as upsert (update the record if it exists, create it if not) and POST as create; check which one is replay-safe.
Making a non-idempotent call safe
Send a client-generated idempotency key (a unique token you create once per logical operation and reuse on every retry). A vendor that supports it stores the first result under that key and returns the stored result for repeats instead of acting again. An Idempotency-Key header is the usual shape; it is described in an IETF draft (a specification still being worked out, not yet a final standard), and individual vendors document their own rules (header name, how long keys are kept, what happens when the key is reused with a different body). Read those before relying on it.
Read it on the wire. This is an illustrative exchange, not a capture; the host is a reserved example name and the idempotency key is invented:
POST /charges HTTP/1.1
Host: api.vendor.example
Authorization: Bearer <token>
Idempotency-Key: order-1042-charge-1
Content-Type: application/json
Content-Length: 33
{"amount":20,"customer":"cus_42"}
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 49
{"id":"ch_9001","amount":20,"status":"succeeded"}
The Idempotency-Key line is the whole mechanism: the client creates the value once for this logical charge and sends the same value on every retry. Content-Length counts the bytes of the body (33 and 49 here). If the response is lost and the client resends the identical request, a vendor that supports keys returns the stored response (the same ch_9001) instead of creating a second charge. What the vendor does with the same key and a different body (for example amount 25) is vendor-defined; many reject it, so a key must never be reused for a changed request.
Common mistakes
Assuming POST can never be retried (with a key it can) or that PUT and DELETE are automatically safe (side effects, concurrency checks). Generating a new key on each attempt, which defeats the point. Treating a 404 or 409 on the replay as a failure when it actually proves the first attempt succeeded.
A vendor API returns a mix of success responses, client errors, server errors and the occasional timeout. Which of these would your client retry, which would it never retry, and what does it do instead in each case?
Sample Answer
The idea in plain words
A client decides what to do with a vendor response by asking one question: would sending the same request again plausibly give a different, better result? A response class tells you that. Success means stop. A client error (a 4xx status) means the request itself is wrong, so repeating it unchanged gives the same answer. A server error (5xx) or a timeout means the vendor failed or you never learned the outcome, so a later attempt may work. The extra rule is that a retry is only safe if repeating the call cannot do the work twice (an idempotent call is one whose effect is the same whether it runs once or three times, such as setting a field to a value; a plain "create order" is not, because two attempts make two orders).
Terms the table uses
- Exponential backoff: each wait before a retry is longer than the last, typically doubling (for example about 1 s, then 2 s, then 4 s), so a struggling vendor gets room to recover.
- Jitter: randomness added to those waits (for example picking each wait at random between 0 and the doubling ceiling) so many clients do not all retry at the same instant.
- Retry-After: a response header (a labelled line sent with the response) that tells you how long to wait, either as a number of seconds (
Retry-After: 7) or as a date. It is defined in RFC 9110, the Internet specification of HTTP behaviour. - Idempotency key: a unique token the client creates once per operation and sends on every attempt, so the vendor treats repeats of that write as one operation. It is what makes a retried create safe.
- Location header and hop limit: a redirect response (a 3xx status) carries a Location header holding the URL to ask next; the hop limit is the largest number of redirects the client follows before giving up, so a redirect loop cannot run forever.
- Fallback content: something useful to show when the live call fails, such as the last cached values labelled as such.
The decision table
| Response | Retry? | What the client does instead or in addition |
|---|---|---|
| 200, 201, 204 | No | Use the result. |
| 202 Accepted | No (do not resend) | The vendor took the work; poll the status link or wait for its callback. |
| 301, 302, 303, 307, 308 | Not a retry, a follow | Follow the Location header up to a small hop limit (for example 5). 307 and 308 keep the method and body; 303 switches to GET. Never send credentials to a different host than the one you configured. |
| 400, 404, 409, 410, 422 | Never | The request or the data is wrong. Log the vendor's error body and request id, fail the one item, show the user a specific message ("this record could not be saved"), fix the mapping. Resending the same payload cannot succeed. |
| 401 | Once, after fixing the cause | 401 means the vendor does not know who you are (expired or missing credentials). Refresh the access token or reload the secret, retry once. If it is still 401, stop and alert: the credential is revoked or wrong. |
| 403 | Never | 403 means the vendor knows who you are and says no (missing permission, scope or plan). A new token will not help. Stop, alert the owner of the integration, and show the user "your connection lacks access to this". |
| 408, 429 | Yes, after waiting | 429 Too Many Requests (RFC 6585) means you are over quota. Wait at least the Retry-After value, then retry. |
| 500, 502, 503, 504 | Yes, with backoff, if the call is safe to repeat | Wait with exponential backoff and jitter, cap the attempts. If they keep failing, use fallback content (cached data, "showing last known values") or queue the work. |
| 501 | Never | The vendor does not implement what you called. |
| Timeout or connection reset | Only if safe to repeat | You do not know whether the vendor acted. Reads and idempotent writes retry; a plain create needs an idempotency key or a lookup first. |
A generic response handler
Write one function that maps what came back to one of a few actions, and make every call go through it so the rules live in one place. The actions are SUCCESS, POLL_STATUS, FOLLOW, REFRESH_AUTH_THEN_RETRY_ONCE, FAIL_PERMANENT, RETRY_AFTER_WAIT, RETRY_BACKOFF_IF_SAFE and LOOKUP_BEFORE_RETRY (the call may have taken effect, so check before sending it again). The retry loop reads the action; business code never inspects status codes itself. This also keeps a surprising status (a vendor returning 200 with an error body, which some do) in one place to special-case.
def classify(status, safe_to_repeat, auth_already_retried=False):
"""Map one response (status None means timeout or reset) to one action."""
if status is None:
return "RETRY_BACKOFF_IF_SAFE" if safe_to_repeat else "LOOKUP_BEFORE_RETRY"
if status in (200, 201, 204):
return "SUCCESS"
if status == 202:
return "POLL_STATUS"
if status in (301, 302, 303, 307, 308):
return "FOLLOW"
if status == 401:
return "FAIL_PERMANENT" if auth_already_retried else "REFRESH_AUTH_THEN_RETRY_ONCE"
if status in (408, 429):
return "RETRY_AFTER_WAIT"
if status in (500, 502, 503, 504):
return "RETRY_BACKOFF_IF_SAFE" if safe_to_repeat else "LOOKUP_BEFORE_RETRY"
return "FAIL_PERMANENT" # 400, 403, 404, 409, 410, 422, 501 and anything unknown
cases = [
(200, True, False), (202, False, False), (307, True, False),
(422, True, False), (401, True, False), (401, True, True),
(403, True, False), (429, True, False), (503, True, False),
(503, False, False), (None, True, False), (None, False, False),
]
for status, safe, retried in cases:
print(f"status={status!s:<5} safe_to_repeat={safe!s:<5} auth_retried={retried!s:<5} -> {classify(status, safe, retried)}")
Output
status=200 safe_to_repeat=True auth_retried=False -> SUCCESS
status=202 safe_to_repeat=False auth_retried=False -> POLL_STATUS
status=307 safe_to_repeat=True auth_retried=False -> FOLLOW
status=422 safe_to_repeat=True auth_retried=False -> FAIL_PERMANENT
status=401 safe_to_repeat=True auth_retried=False -> REFRESH_AUTH_THEN_RETRY_ONCE
status=401 safe_to_repeat=True auth_retried=True -> FAIL_PERMANENT
status=403 safe_to_repeat=True auth_retried=False -> FAIL_PERMANENT
status=429 safe_to_repeat=True auth_retried=False -> RETRY_AFTER_WAIT
status=503 safe_to_repeat=True auth_retried=False -> RETRY_BACKOFF_IF_SAFE
status=503 safe_to_repeat=False auth_retried=False -> LOOKUP_BEFORE_RETRY
status=None safe_to_repeat=True auth_retried=False -> RETRY_BACKOFF_IF_SAFE
status=None safe_to_repeat=False auth_retried=False -> LOOKUP_BEFORE_RETRY
Reading the output: each row is one response. safe_to_repeat says whether running the call twice has the same effect as once (a read, or a write sent with an idempotency key); status=None stands for a timeout or reset, where no response arrived. The two 401 rows show the once-only rule: the first 401 refreshes the credential, and a 401 after a refresh stops. The two 503 rows show that one status leads to different actions depending on the call: a safe call is retried with backoff, an unsafe one is looked up first. 403 and 422 never retry. The loop around this function does the waiting: it sleeps for the Retry-After value or a backoff delay, and enforces the attempt cap.
Worked example (illustrative scenario)
A client syncs contacts and makes six calls (assumed scenario).
- Call 1 returns 200: store the contact.
- Call 2 returns 422: the vendor rejected one field. Mark that contact failed with the vendor's message, do not retry, continue with the rest.
- Call 3 returns 401: refresh the token and replay the call once. The replay returns 200, so the cause was an expired token.
- Call 4 returns 429 with Retry-After: 7: pause calls on that credential for 7 seconds, then replay.
- Call 5 returns 503: back off (for example a random wait of up to 1 s, then up to 2 s) and replay, up to the attempt cap.
- Call 6 is a GET that times out: safe to repeat, so retry. If it had been a POST create without an idempotency key, it would not be replayed blindly.
Judgment and mistakes
Retry on the cause, not on "any error". The common mistakes: retrying 400 or 403 (burns quota and delays the real fix), treating 401 and 403 as the same thing, retrying a non-idempotent write after a timeout, retrying forever with no cap, and returning a blank screen instead of a message or cached content. The handler above is a starting point; a production one also needs per-vendor quirks (a vendor that uses 400 for throttling, or 200 with an error field), a cap on total time, and metrics per status class.
Running the code
Save the program as classify_demo.py and run python classify_demo.py with Python 3.12. It prints the output shown.
Implement a retry helper for calls to a flaky dependency. Attempts must be spaced out so that many clients recovering at the same moment do not retry in lockstep. It takes an initial delay, a maximum delay, a maximum attempt count and the call to make, and it must be cancellable. Show the delays it produces for a call that fails four times and then succeeds.
Sample Answer
The idea in plain words
When a dependency fails briefly, retrying usually works. The danger is many clients retrying at the same instant: if 1,000 clients all fail at once (they would be retrying in lockstep, all at the same moment) and all wait exactly 0.5 s, the dependency sees all 1,000 again together and fails again (a "thundering herd"). The cure is exponential backoff (each wait is longer than the last, so a struggling service gets room to recover) plus jitter (a random element, so clients spread out instead of marching in step).
The version that spreads clients best is full jitter. For attempt number k (counting from 0) the helper picks the wait at random between 0 and a ceiling:
ceilingk=min(max_delay, initial_delay×2k),waitk∼Uniform(0, ceilingk)Here initial_delay is the first ceiling, max_delay caps growth so a late retry does not wait minutes, and 2k doubles the ceiling each failure. Read the formula in words: min(a,b) means the smaller of the two numbers, and waitk∼Uniform(0,ceilingk) means the wait is a random number drawn so that every value between 0 and the ceiling is equally likely. By hand with an initial delay of 0.5 s and a cap of 3.0 s: for k=0 the ceiling is min(3.0, 0.5×1)=0.5, and for k=3 it is min(3.0, 0.5×8)=min(3.0, 4.0)=3.0.
Design decisions
- Only retry errors that are transient (timeouts, connection resets, 503 Service Unavailable meaning the server is overloaded or down, and 429 Too Many Requests meaning you are over a quota). A 400 or 404 will fail the same way every time, so the helper only retries one exception class,
TransientError, and lets everything else propagate at once. - The call receives the attempt number, so a caller can reuse the same idempotency key on every attempt (an idempotency key is a unique token sent with a write so that the server treats repeats as one operation).
- Cancellable waits. The helper does not call
sleep. It callscancel.wait(delay), the interface of Python'sthreading.Event(an event is a flag that one thread can set to signal another;wait(timeout)pauses for up to that many seconds): it returnsTrueearly if cancellation was requested, andFalseafter the full delay. The same function therefore works with a realthreading.Eventin production. Cancellation is also checked before each call so a cancelled operation never starts another attempt. That check iscancel.wait(0)at the top of the loop: a zero-second wait does not pause at all, it only reports whether the flag is already set, so it works as a pure check for "has anyone asked to stop?". - The random generator and the wait are passed in. That lets the demo use simulated time (a counter, not the wall clock) and a seeded generator (a random generator started from a fixed number, so it repeats the same sequence on every run), so the printed schedule is reproducible.
- After the last attempt, re-raise the real error. Swallowing it or returning
Nonehides the failure.
Code
The program below defines the helper, runs the requested case (a call that fails four times and then succeeds), and adds three checks: cancellation mid-wait, exhaustion, and a lockstep test with 1,000 clients. The demo clock is simulated: SimClock.wait advances a number.
import random
class TransientError(Exception):
"""A failure worth retrying (timeout, 503, connection reset)."""
class Cancelled(Exception):
"""The caller cancelled while the helper was waiting or about to call."""
def retry_with_backoff(call, initial_delay, max_delay, max_attempts, cancel, rng):
"""Call `call(attempt)` until it returns, using full-jitter exponential backoff.
cancel: object with wait(timeout) -> bool (True means cancelled), like threading.Event.
rng: random.Random instance, passed in so the schedule can be reproduced.
Returns (result, list_of_delays_waited).
"""
delays = []
for attempt in range(max_attempts):
if cancel.wait(0):
raise Cancelled()
try:
return call(attempt), delays
except TransientError:
if attempt == max_attempts - 1:
raise
ceiling = min(max_delay, initial_delay * 2 ** attempt)
delay = rng.uniform(0, ceiling)
delays.append(delay)
if cancel.wait(delay):
raise Cancelled()
raise AssertionError("unreachable")
class SimClock:
"""Simulated time: wait() advances a counter instead of sleeping."""
def __init__(self, cancel_at=None):
self.now = 0.0
self.cancel_at = cancel_at
def wait(self, timeout):
if self.cancel_at is not None and self.now + timeout >= self.cancel_at:
self.now = self.cancel_at
return True
self.now += timeout
return False
def flaky(failures):
def call(attempt):
if attempt < failures:
raise TransientError(f"attempt {attempt} failed")
return f"ok on attempt {attempt}"
return call
BASE, CAP, MAX = 0.5, 3.0, 6
# 1. Four failures, then success.
clock = SimClock()
result, delays = retry_with_backoff(flaky(4), BASE, CAP, MAX, clock, random.Random(7))
ceilings = [min(CAP, BASE * 2 ** k) for k in range(4)]
print("result:", result)
print("ceilings:", ceilings)
print("delays :", [round(d, 3) for d in delays])
print("total simulated wait:", round(clock.now, 3))
print("check delay within [0, ceiling]:", all(0 <= d <= c for d, c in zip(delays, ceilings)))
print("check wait equals sum of delays:", abs(clock.now - sum(delays)) < 1e-9)
# 2. Cancelled at t = 1.0 while waiting.
clock = SimClock(cancel_at=1.0)
try:
retry_with_backoff(flaky(4), BASE, CAP, MAX, clock, random.Random(7))
except Cancelled:
print("cancelled at simulated t =", clock.now)
# 3. Attempts exhausted.
try:
retry_with_backoff(flaky(9), BASE, CAP, MAX, SimClock(), random.Random(7))
except TransientError as e:
print("gave up after", MAX, "attempts:", e)
# 4. Lockstep check: 1000 clients all fail at t = 0, first retry time.
n = 1000
rngs = random.Random(11)
no_jitter = [BASE] * n
jitter = [rngs.uniform(0, BASE) for _ in range(n)]
def busiest_bucket(times, width=0.05):
counts = {}
for t in times:
k = int(t / width)
counts[k] = counts.get(k, 0) + 1
return max(counts.values())
print("no jitter: busiest 50 ms slot holds", busiest_bucket(no_jitter), "of", n)
print("full jitter: busiest 50 ms slot holds", busiest_bucket(jitter), "of", n)
print("expected per slot if spread evenly:", n // 10)
# 5. Cap check over many seeds: no fourth delay may exceed the 3.0 s cap.
worst = 0.0
for seed in range(2000):
_, d = retry_with_backoff(flaky(4), BASE, CAP, MAX, SimClock(), random.Random(seed))
worst = max(worst, d[3])
print("largest fourth delay over 2000 seeds:", round(worst, 3))
print("check cap respected:", worst <= CAP)
Output
result: ok on attempt 4
ceilings: [0.5, 1.0, 2.0, 3.0]
delays : [0.162, 0.151, 1.302, 0.217]
total simulated wait: 1.832
check delay within [0, ceiling]: True
check wait equals sum of delays: True
cancelled at simulated t = 1.0
gave up after 6 attempts: attempt 5 failed
no jitter: busiest 50 ms slot holds 1000 of 1000
full jitter: busiest 50 ms slot holds 111 of 1000
expected per slot if spread evenly: 100
largest fourth delay over 2000 seeds: 2.999
check cap respected: True
Reading the output
- The requested schedule. The call fails on attempts 0 to 3 and succeeds on attempt 4 (the fifth call), so there are four waits. The ceilings are 0.5, 1.0, 2.0 and 3.0 seconds: the fourth would be 0.5 x 2^3 = 4.0 but is capped at
max_delay= 3.0. The seeded random waits are 0.162, 0.151, 1.302 and 0.217 seconds, each inside its ceiling, and they total 1.832 seconds of simulated waiting. A different seed gives different waits within the same ceilings; the ceilings are the part that is fixed. - The self-checks can fail. The first check asserts every wait lies in [0,ceilingk]. A single seed can pass by luck, so the last check draws the fourth wait under 2,000 seeds and requires the largest to be at most the 3.0 s cap (it printed 2.999). A variant of the helper without the
min(max_delay, ...)draws the fourth wait from 0 up to 0.5 x 2^3 = 4.0 seconds, gives a largest fourth wait of 3.999 over the same 2,000 seeds and printscheck cap respected: False, so the check detects that bug. - Cancellation. With the cancel time set to simulated t = 1.0 s, the first two waits (0.162 + 0.151 = 0.313 s) finish, and the third wait (1.302 s) would end at 1.615 s, so cancellation interrupts it at 1.0 s and the helper raises
Cancelledwithout making another call. - Exhaustion. With
max_attempts= 6, a call that fails on every attempt is tried 6 times, waits 5 times, and then the sixth failure is re-raised. - Lockstep. With no jitter, all 1,000 clients retry in the same 50 ms slot (1,000 of 1,000). With full jitter over the first ceiling of 0.5 s, the busiest 50 ms slot holds 111 clients; an even spread over the ten slots would be 100 each. That is the herd being broken up, for this seed and this client count.
Complexity and edge cases
- Time and space: the loop runs at most
max_attemptstimes, so work grows in proportion tomax_attempts(written O(max_attempts) and read 'order of') and the list of waits is the same size. Worst-case total waiting is the sum of the ceilings, here 0.5 + 1.0 + 2.0 + 3.0 + 3.0 = 9.5 seconds across five waits for six attempts, plus the time the calls themselves take. - Edge cases:
max_attemptsof 1 means no retry and no wait. Aninitial_delayof 0 gives zero waits (a tight loop), so reject it. Amax_delaybelowinitial_delaysimply caps every wait atmax_delay. A call that succeeds on the first attempt returns an empty wait list. - Beyond this helper: a production client should also honour a server's
Retry-Afterheader (a response header saying how many seconds the server asks you to wait; use the larger of the server's value and the computed wait), retry only idempotent calls or calls with an idempotency key, enforce an overall deadline so retries cannot outlast the user's request, and share a retry budget (a cap on the fraction of calls that may be retries) so retries cannot turn a partial outage into a total one.
Running the code
Save the program as retry_demo.py and run python retry_demo.py with Python 3.12. It prints the output shown.
You have two weeks to ship a payment provider integration into checkout, knowing it will be replaced in six months by a richer solution. What do you build, what do you deliberately skip, and how do you stop the shortcut from becoming permanent debt?
Sample Answer
The idea in plain words
Money code has two kinds of work. One kind prevents wrong outcomes: charging twice, losing a payment, showing a paid order as unpaid, trusting a forged notification. That work is never the shortcut. The other kind adds convenience or breadth: more payment methods, saved cards, a refund screen, rich reporting. That is what you skip. The way to keep the shortcut from becoming permanent is to put one narrow interface between your product and the provider (a port you own, with an adapter for this provider), so the six-month replacement swaps an adapter instead of rewriting checkout, and to record the debt where it will be seen: a dated ticket, a tracked feature flag (a switch that turns the new payment path on for a share of traffic, or off at once, without a new release) and a named owner.
1. What to build (two weeks is 10 working days)
| Work | Days | Why it is not optional |
|---|---|---|
A PaymentProvider interface (create payment, get status, refund, handle notification) with this provider as one adapter, plus configuration and credentials in the secret store (a managed vault for credentials, kept out of code and config files) | 1 | The seam that makes replacement cheap |
| Create-payment flow from the server side, with an idempotency key tied to the order (a unique string sent with the request; if the same key arrives again, the provider returns the first result instead of charging again), timeouts and error mapping | 2 | Prevents double charges and silent failures |
| Webhook receiver: verify the signature over the raw body (the provider computes a keyed hash of the exact bytes it sends, using a secret only you and it know, and puts it in a header; you recompute it over the bytes you received and reject a mismatch), store event ids to ignore repeats, move the order through a small state machine (a fixed list of order states and the only moves allowed between them: pending, paid, failed, refunded) | 2 | The provider's notification, not the browser redirect, is the source of truth for payment state |
| Daily reconciliation job: a scheduled comparison of the provider's records with your orders that reports differences | 2 | Catches what retries and webhooks miss |
| Tests against the provider's sandbox (its test environment) for the main paths, alerts on failure rates | 1 | Fast feedback if the provider changes |
| Rollout behind a feature flag for a share of traffic, with a day of buffer | 2 | Safe launch |
Check: 1 + 2 + 2 + 2 + 1 + 2 = 10 days.
The sizes follow how many ways each piece can fail. The interface is small and mostly decisions, so 1 day. The payment flow, the webhook receiver, the reconciliation job and the rollout each deal with retries, odd inputs or real traffic, so 2 days each. The sandbox tests get 1 day because they reuse the flows already built.
What the idempotency key, the signature and the state machine do
The program below uses a small in-memory stand-in for the provider (illustrative, not any real provider's API). It shows three things: a retry after a lost reply with and without an idempotency key, a signature check over the raw body, and an order that ignores a repeated event and refuses a move that is not allowed.
import hashlib
import hmac
import json
class FakeProvider:
"""In-memory payment provider that remembers idempotency keys."""
def __init__(self):
self.charges = []
self.seen = {}
def create_payment(self, order_id, amount_minor, idempotency_key=None):
if idempotency_key is not None and idempotency_key in self.seen:
return self.seen[idempotency_key] # same key: hand back the first result
charge = {"charge_id": f"ch_{len(self.charges) + 1}", "order": order_id, "amount_minor": amount_minor}
self.charges.append(charge)
if idempotency_key is not None:
self.seen[idempotency_key] = charge
return charge
def pay_with_retry(provider, order_id, amount_minor, use_key):
key = f"order-{order_id}-pay" if use_key else None
provider.create_payment(order_id, amount_minor, key) # the reply is lost, so the caller retries
return provider.create_payment(order_id, amount_minor, key)
for use_key in (False, True):
provider = FakeProvider()
pay_with_retry(provider, "A1001", 4999, use_key)
print("idempotency key:", use_key, "-> charges created:", len(provider.charges))
# Signature over the raw body: HMAC-SHA256 with a shared secret.
secret = b"whsec_example"
raw_body = b'{"event_id":"evt_1","type":"payment.paid","order":"A1001"}'
signature = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
def verify(body, sig):
expected = hmac.new(secret, body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, sig)
reserialised = json.dumps(json.loads(raw_body)).encode()
print("raw body verifies:", verify(raw_body, signature))
print("re-serialised body verifies:", verify(reserialised, signature))
print("tampered body verifies:", verify(raw_body.replace(b"A1001", b"A9999"), signature))
# Order state machine with duplicate-event protection.
ALLOWED = {"pending": {"paid", "failed"}, "paid": {"refunded"}}
state, seen_events = "pending", set()
for event_id, new_state in [("evt_1", "paid"), ("evt_1", "paid"), ("evt_2", "pending")]:
if event_id in seen_events:
result = "ignored duplicate"
elif new_state in ALLOWED.get(state, set()):
state = new_state
result = "moved to " + state
else:
result = "rejected move to " + new_state
seen_events.add(event_id)
print(event_id, new_state, "->", result)
Output:
idempotency key: False -> charges created: 2
idempotency key: True -> charges created: 1
raw body verifies: True
re-serialised body verifies: False
tampered body verifies: False
evt_1 paid -> moved to paid
evt_1 paid -> ignored duplicate
evt_2 pending -> rejected move to pending
Reading the output:
- The first two lines: the first call succeeded but its reply was lost, so the caller retried. Without a key the provider created 2 charges for one order. With the key
order-A1001-pay, the second call returned the first charge, so 1 charge exists. - The signature lines: the signature was computed over the exact bytes received. Parsing the JSON and writing it back out changes the bytes (spaces are added after the colons and commas), so the re-serialised body fails, and so does a body with the order id altered. This is why the receiver must keep the raw body.
- The last three lines:
evt_1moves the order from pending to paid; the same event id arriving again is ignored;evt_2asks for a move from paid back to pending, which the allowed-moves table does not contain, so it is rejected.
Keep amounts as integers in the smallest currency unit and store the currency with them. Never log card data; let the provider's hosted fields (card-entry boxes served by the provider, so card numbers never reach your servers) or checkout page handle card entry so your servers stay out of that scope.
2. What to deliberately skip
- Extra payment methods beyond the one or two that matter for launch.
- Saved cards and subscriptions.
- A refund user interface: do refunds through the provider's dashboard at first, but keep the interface method so it can be wired later.
- Partial captures (taking less than the amount that was authorised), multi-currency edge cases, and fine-grained reporting.
- A generic abstraction designed to fit every future provider. One interface shaped by the four methods above is enough; designing for the unknown replacement is how two weeks become six.
State what was skipped in the pull request description and in the ticket, so skipped is a decision and not an oversight.
3. How the shortcut avoids becoming permanent
- Date it. Six months is about 26 weeks (6 x 30.44 days / 7 = 26.1). Create the replacement ticket now with a target start of around week 20, which leaves about 6 weeks for the work, and put it on a roadmap with an owner.
- Make the shortcut visible in code: one module, a header comment with the ticket, a feature flag with an expiry date, and a lint rule (an automated code check that runs on every change) or a test that fails once the date has passed so someone must extend or remove it deliberately.
- Protect the seam. Write contract tests at the interface level (tests that state what any provider adapter must do: a payment created, a repeated notification, a failed payment), not only tests against this provider. The same tests then become the acceptance tests for the replacement adapter.
- Record the skipped list in the ticket with the reason for each, so the replacement project starts from a known scope.
- Track the cost: count provider incidents, manual refunds and reconciliation differences per month. Rising numbers are the argument for starting early.
The judgment
I would take the two weeks to build the safe core plus the seam and spend nothing on breadth. What would change this: if the replacement slips or is cancelled, the shortcut becomes the product, so the reconciliation job and the sandbox tests are exactly what make living with it acceptable. If a regulator or the finance team requires refunds or reports at launch, those move out of the skipped list and something else leaves.
Common mistakes
- Skipping idempotency or webhook verification because they are "just plumbing".
- Trusting the redirect to the success page as proof of payment.
- Letting provider-specific names spread through checkout code.
- A TODO comment as the only record of the debt.
- Over-generalising the interface for providers that do not exist yet.
Running the code
python payment_demo.py
Python 3.12.
A service calls a third-party API on a user-facing request path. How do you choose timeouts for connecting, waiting for a response, and the operation as a whole, and what should happen when each one fires?
Sample Answer
The idea in plain words
A call to a third-party API can stall in three different places, and each needs its own clock:
- Connect timeout: how long you wait to open the network connection (the TCP handshake, which opens a reliable connection, plus TLS, the encryption setup). If this fires, your request was never sent, so retrying is safe.
- Response (read) timeout: how long you wait for the vendor to answer after the request is sent. In most HTTP client libraries this is the longest silent gap between bytes, not the whole response time, so a slow trickle can evade it. If this fires, the vendor may have processed the request, so retrying is only safe for idempotent calls (calls where repeating has the same effect as doing it once), or for writes protected by an idempotency key (a unique token the client creates once per operation and sends on every attempt, so the vendor treats repeats as one operation).
- Overall deadline: a cap on the whole operation, including every retry and every wait between retries. This is the one tied to the user: it is what stops a slow vendor from holding the user's request open forever.
The one insight: the timeouts are not independent numbers picked from a default. They are carved out of the budget the user-facing request is allowed to spend, and each one has a planned action when it fires.
Method, in the order I would do it
- Start from the user's budget. Assume (illustration) the page or endpoint should answer within 3,000 ms at the slow end, and that our own work takes 800 ms. That leaves 2,200 ms. Keep a safety margin of 700 ms for network and jitter on our side, so the vendor call as a whole gets an overall deadline of 1,500 ms.
- Measure the vendor, then set the read timeout just above its tail. The tail is the slowest few percent of calls, and tail latency is how long those take. Assume the vendor's observed 99th percentile (p99: 99 of 100 calls are faster) is 450 ms. A read timeout of 600 ms lets almost every healthy call through and cuts off the stalled ones. A timeout set at the median would cut off about half of the healthy calls; a timeout of 30 seconds (a common library default) means one stalled vendor ties up your workers (the threads or task slots that each handle one request at a time) for 30 seconds each.
- Set the connect timeout short. Opening a connection to a healthy host takes tens of milliseconds, so waiting long adds nothing. Assume 200 ms.
- Make each attempt's timeout the smaller of its own limit and what remains of the deadline: attempt timeout = min(read timeout, deadline minus time already spent). Never start an attempt you cannot finish: if the remaining budget is smaller than one connect plus a plausible response (here 200 ms is a floor in this illustration), stop.
- Decide the action for each timeout before writing code (table below).
| Timeout fires | What we know | Action |
|---|---|---|
| Connect | Request never left; no side effect | Retry once after a short jittered wait (random delay so many clients do not retry together), if budget remains; count it toward the circuit breaker (described after this table) |
| Response (read) on a read-only call (GET) | Vendor may have worked, but repeating a read is harmless | Retry with the remaining budget, or serve a cached or degraded value |
| Response (read) on a write (POST) | Outcome unknown: the charge or record may exist | Retry only with the same idempotency key. Without one, do not retry blindly: return "pending", and reconcile (find out afterwards what really happened) by looking the record up by your own reference |
| Overall deadline | Budget spent | Cancel the in-flight call, return a degraded answer to the user (a reduced but still useful reply, such as cached data, "we will confirm by email", a queued job), and record the failure |
The circuit breaker is a small state machine kept per vendor, with illustrative settings. Closed: calls flow normally and timeouts are counted. After 5 timeouts in a row it opens: for the next 30 seconds every call fails immediately with no network attempt and goes straight to the degraded answer. After 30 seconds it goes half-open and lets one probe call through; if the probe succeeds the breaker closes, and if it times out the breaker opens for another 30 seconds. In Trace B below a stalled vendor costs each request 1,330 ms; once the breaker is open a request costs the vendor no time at all, and the worker is free for other work.
Worked example: two traces on a 1,500 ms budget
Settings (assumptions): overall deadline 1,500 ms, connect timeout 200 ms, read timeout 600 ms, one 50 ms jittered wait between attempts, no new attempt if less than 200 ms remains.
Trace A, slow connect, then success (a GET).
Attempt 1: connect timeout fires at 200 ms. Wait 50 ms. Attempt 2: connect takes 80 ms, the response takes 300 ms. Total: 200 + 50 + 80 + 300 = 630 ms, inside 1,500 ms. The user sees a slightly slow page.
Trace B, stalled vendor (a GET).
| Step | Event | Clock | Remaining of 1,500 |
|---|---|---|---|
| 1 | Connect succeeds in 40 ms | 40 ms | 1,460 |
| 2 | Read timeout fires after 600 ms | 640 ms | 860 |
| 3 | Wait 50 ms | 690 ms | 810 |
| 4 | Second connect takes 40 ms | 730 ms | 770 |
| 5 | Attempt timeout = min(600, 770) = 600 ms; vendor stalls again, fires | 1,330 ms | 170 |
| 6 | 170 ms is below the 200 ms floor, so no third attempt: return the cached or degraded answer | 1,330 ms | 170 |
The user waits 1,330 ms in the worst case rather than 30 seconds. The same trace shows a cost: each stalled request occupies a worker for the whole 1,330 ms.
Why the numbers also protect your own capacity
By Little's law (average number of requests in flight equals arrival rate times average time each stays), if 50 requests per second call the vendor and each stays 0.3 s when healthy, about 50 x 0.3 = 15 are in flight. If every one stalls to the full 1.5 s deadline, about 50 x 1.5 = 75 are in flight, five times the healthy figure. A worker pool sized for 15 will be exhausted, and unrelated features start to fail. So the deadline is a capacity control as well as a latency control. Pair it with a separate, bounded worker pool for the vendor and a circuit breaker.
Judgment calls and what would change them
- Long-running vendor operations (report generation, large uploads) do not fit a user-facing deadline. Use an asynchronous pattern: start the job, get an ID, poll or receive a webhook, and give the user a progress state. Timeouts then apply per call, not per job.
- Streaming responses need a read timeout on the gap between chunks plus an overall deadline, because a slow trickle can keep the connection technically alive.
- Retries cost budget: with a 1,500 ms deadline and a 600 ms read timeout, at most two full-length read attempts fit. Raising the retry count without raising the deadline changes nothing, and raising the deadline moves the cost to the user.
- Different calls, different budgets: a payment confirmation may justify a longer deadline than a "suggested contacts" widget that can simply be omitted.
Common mistakes
- Using the library default (often no timeout, or tens of seconds) on a user-facing path.
- Setting only a read timeout and no overall deadline, so retries multiply the wait.
- Retrying a timed-out POST with no idempotency key, which can charge a customer twice.
- Choosing the read timeout from the median instead of the tail.
- Forgetting to cancel the in-flight request when the deadline fires, so the worker is still held.
Unlock Full Question Bank
Get access to all 11 Third-Party and SaaS Integration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.