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.
Here is a source record from a CRM and the schema a billing system expects. Write the code that maps one into the other, coping with the differences in shape and type, with missing or null values, and with records that cannot be mapped, so that failures are surfaced usefully. Show its output for the sample and for a broken record.
Source: {"userId":"u123","name":{"first":"Alice","last":"Z"},"joined":"2024-01-02T15:00:00Z","meta":null}
Target expects: {"customer_id":...,"full_name":...,"signup_ts":...}
Sample Answer
The idea in plain words
A mapper takes one record in the CRM's shape and produces one record in the billing system's shape, or says exactly why it cannot. The design rule is: never raise on bad input and never invent values. Check every field, collect every problem in one pass (so the person fixing it sees all of them, not the first), and return either a mapped record or a list of errors. Dropping a record silently or filling gaps with defaults moves the failure downstream, where it is harder to find.
Assumptions about the target
The question gives the target field names only, so I assume customer_id is a non-empty string, full_name is a string built from the first and last name, and signup_ts is an ISO 8601 UTC timestamp string with a trailing Z. ISO 8601 is the standard written form of a date and time, such as 2024-01-02T15:00:00Z; UTC is the world reference time (no daylight saving), and the trailing Z means "this is UTC". A real billing schema may differ (for example epoch seconds), and the answer should be checked against its documentation.
The mapping rules
| Target | Source | Rule | Failure becomes |
|---|---|---|---|
| customer_id | userId | must be a non-empty string; trimmed | missing_or_empty |
| full_name | name.first, name.last | object required; each part that is present must be a string; join the non-blank parts with a space; a missing or null part is allowed, no usable part at all is not | missing_or_not_object, name_part_not_string or no_usable_name_part |
| signup_ts | joined | ISO 8601 with a timezone, converted to UTC | missing_or_not_string, not_iso_8601, no_timezone, out_of_range |
| (none) | meta | not in the target, dropped on purpose, even when null | none |
A timestamp without a timezone is rejected because the instant is ambiguous: guessing a zone would silently shift billing dates. Such a value is called naive (it carries no zone or offset, for example 2024-01-02T10:00:00). A UTC offset such as -05:00 at the end says the clock time is five hours behind UTC, so 10:00:00-05:00 and 15:00:00Z are the same instant.
The code
import json
from datetime import datetime, timezone
def map_record(src):
"""Return (target_or_None, errors). Each error is (field, code, detail)."""
errors = []
if not isinstance(src, dict):
return None, [("(root)", "not_an_object", type(src).__name__)]
uid = src.get("userId")
if not isinstance(uid, str) or not uid.strip():
errors.append(("userId", "missing_or_empty", repr(uid)))
name = src.get("name")
full_name = None
if not isinstance(name, dict):
errors.append(("name", "missing_or_not_object", repr(name)))
else:
raw = [name.get("first"), name.get("last")]
for key, p in zip(("first", "last"), raw):
if p is not None and not isinstance(p, str):
errors.append(("name." + key, "name_part_not_string", repr(p)))
parts = [p.strip() for p in raw if isinstance(p, str) and p.strip()]
if parts:
full_name = " ".join(parts)
elif not any(e[0].startswith("name.") for e in errors):
errors.append(("name", "no_usable_name_part", repr(name)))
signup_ts = None
joined = src.get("joined")
if not isinstance(joined, str):
errors.append(("joined", "missing_or_not_string", repr(joined)))
else:
try:
dt = datetime.fromisoformat(joined)
if dt.tzinfo is None:
errors.append(("joined", "no_timezone", joined))
else:
utc = dt.astimezone(timezone.utc)
signup_ts = utc.isoformat(timespec="seconds").replace("+00:00", "Z")
except ValueError:
errors.append(("joined", "not_iso_8601", joined))
except OverflowError: # an instant too close to year 1 or 9999 cannot be shifted to UTC
errors.append(("joined", "out_of_range", joined))
# "meta" is not in the target schema: dropped on purpose, null or not.
if errors:
return None, errors
return {"customer_id": uid.strip(), "full_name": full_name, "signup_ts": signup_ts}, []
def show(label, src):
target, errors = map_record(src)
print(label)
print(" target:", json.dumps(target))
print(" errors:", json.dumps(errors))
return target, errors
good = {"userId": "u123", "name": {"first": "Alice", "last": "Z"},
"joined": "2024-01-02T15:00:00Z", "meta": None}
bad = {"name": None, "joined": "02/01/2024", "meta": None}
offset = {"userId": "u9", "name": {"first": "Bo", "last": None},
"joined": "2024-01-02T10:00:00-05:00"}
t, e = show("sample", good)
assert t == {"customer_id": "u123", "full_name": "Alice Z", "signup_ts": "2024-01-02T15:00:00Z"} and e == []
t, e = show("broken", bad)
assert t is None and [x[0] for x in e] == ["userId", "name", "joined"]
t, e = show("edge of range", {"userId": "u8", "name": {"first": "Cy"}, "joined": "0001-01-01T00:00:00+05:00"})
assert t is None and e == [("joined", "out_of_range", "0001-01-01T00:00:00+05:00")]
t, e = show("early year", {"userId": "u7", "name": {"first": "Di"}, "joined": "0005-03-04T05:06:07Z"})
assert t["signup_ts"] == "0005-03-04T05:06:07Z", "the year must stay four digits"
t, e = show("wrong type", {"userId": "u6", "name": {"first": 5, "last": "Z"}, "joined": "2024-01-02T15:00:00Z"})
assert t is None and e == [("name.first", "name_part_not_string", "5")], "a wrongly typed part must not be dropped silently"
t, e = show("offset", offset)
# independent check: 10:00 at UTC-5 is 15:00 UTC
assert t["signup_ts"] == "2024-01-02T15:00:00Z" and t["full_name"] == "Bo"
print("checks passed")
Output:
sample
target: {"customer_id": "u123", "full_name": "Alice Z", "signup_ts": "2024-01-02T15:00:00Z"}
errors: []
broken
target: null
errors: [["userId", "missing_or_empty", "None"], ["name", "missing_or_not_object", "None"], ["joined", "not_iso_8601", "02/01/2024"]]
edge of range
target: null
errors: [["joined", "out_of_range", "0001-01-01T00:00:00+05:00"]]
early year
target: {"customer_id": "u7", "full_name": "Di", "signup_ts": "0005-03-04T05:06:07Z"}
errors: []
wrong type
target: null
errors: [["name.first", "name_part_not_string", "5"]]
offset
target: {"customer_id": "u9", "full_name": "Bo", "signup_ts": "2024-01-02T15:00:00Z"}
errors: []
checks passed
Reading the output
- The sample maps cleanly: first and last name join into
Alice Z, and the timestamp is already UTC, so it is unchanged. - The broken record has three independent problems, and all three are reported together, each with the field, a stable code a program can switch on, and the offending value. No partial target is returned, so a half-built record cannot reach billing.
- The edge-of-range record is reported as
out_of_rangeinstead of crashing: shifting the first instant of year 1 five hours back to UTC would fall before the earliest representable datetime, and Python raisesOverflowErrorfor that. - The early-year record shows the year kept at four digits:
strftime("%Y")prints year 5 as5on some platforms, which would hand billing the malformed text5-03-04T05:06:07Z, so the timestamp is written withisoformatinstead. - The wrong-type record has a number where a first name belongs. Dropping it would have billed the customer as
Z, so it is reported asname_part_not_stringand no target is built. - The last case checks the time conversion independently: 10:00 at UTC-5 is 15:00 UTC (10 + 5), which is the value the program printed, and a missing last name still gives a valid name.
- Removing the UTC conversion makes the offset assertion fail, so the check can fail.
What this demo covers, and what a real mapper must also handle
This is a small illustration for the three inputs above. It is not a complete validator. A production mapper must also handle: the real target schema and its limits (length, character set), numeric and enum fields, fractional seconds and other timestamp formats the vendor really sends, Unicode normalisation of names (the same visible letter, such as an accented e, can be stored as one character or as two combined ones, so names that look identical may compare as different until both are converted to one standard form), duplicate or conflicting ids, and a versioned mapping so that schema changes can be rolled out and old records re-mapped. Failed records should go to a dead-letter store (a holding area for records that could not be processed) with the original payload, the error list and the mapper version, with a count alert.
Walking through the code
map_record(src)always returns two things: the mapped record (orNone) and a list of errors. Each error is a tuple of field, code and offending value. Python tuples become lists whenjson.dumpsprints them, which is why the output shows square brackets.if not isinstance(src, dict)checks that the input is a JSON object at all (a Python dict); a list or a string would otherwise crash the next line.src.get("userId")returnsNonewhen the key is absent, wheresrc["userId"]would raise aKeyError(the exception Python raises for a missing dictionary key).None, a number or a blank string all fail theisinstance(uid, str) and uid.strip()test, so one rule covers missing, null, wrongly typed and whitespace-only ids.- The name block first collects
firstandlastas they arrive, possiblyNone, inraw. A part that is present but not a string (a number, a list) is reported asname_part_not_stringinstead of being dropped.partsis then a list comprehension, a loop written in one line: keep eachpthat is a non-blank string, and strip its spaces." ".join(parts)then glues what survives, soBowith aNonelast name becomesBo, and two missing or blank parts leave an empty list, which is theno_usable_name_parterror (reported only when no part was already reported as the wrong type). datetime.fromisoformat(joined)parses the text into a datetime object and raisesValueErrorif the text is not ISO 8601, which the firstexceptturns intonot_iso_8601; the secondexceptturns theOverflowErrorthatastimezoneraises for an instant it cannot shift intoout_of_range. The parsed object has atzinfoattribute (its timezone); it isNonefor a naive timestamp, which becomesno_timezone.dt.astimezone(timezone.utc)converts the instant to UTC, andisoformat(timespec="seconds")writes it back as text with a four-digit year and whole seconds (any fractional second is cut off), with the+00:00ending replaced by the target'sZ.- Errors are only appended, never raised, so every field is checked before the function decides: if the list is non-empty it returns
(None, errors), otherwise the finished record.
Common mistakes
- Using
dict["key"]and letting a KeyError crash the whole batch. - Returning an empty string for a missing name, which passes validation downstream and bills a nameless customer.
- Treating a naive timestamp as UTC.
- Reporting only the first error.
Running the code
Python 3.12 (standard library only). Save the listing as map_record.py and run python map_record.py.
You suspect a third-party API change is intermittently returning null join keys, but you cannot see the vendor's logs. How would you validate the hypothesis from your side, what would you capture, what temporary mitigations would you put in place, and how do you escalate to the vendor while still uncertain?
Sample Answer
The idea in plain words
You cannot read the vendor's logs, so you build your own evidence at the boundary you do control: what you sent, what came back, and when. The aim is to turn "I suspect the vendor changed something" into a measured statement such as "the join key is null in 1.9 percent of responses since a given date, for these endpoints and these record types, and a replay of the same request returns it". A join key is the field you use to match a vendor record to a record elsewhere (for example a customer id). Intermittent nulls can come from three places: the vendor's serialisation (turning its stored record into the bytes of the response), the vendor's data (some records genuinely lack the key), or your own code (a parsing change, a field selection, a pagination bug, where a list returned in pages skips or repeats records at a page boundary). The work is to separate those.
What I would capture (from my side)
For every call to the affected endpoints, in a store with a short retention and PII (personally identifiable information, such as names and emails) redacted:
- Request: method, URL, query parameters (including any field-selection or expand parameters, which ask the API to embed related objects), the API version you pin (you ask for one fixed version instead of the vendor's newest), and a timestamp in UTC.
- Response: status code, the headers (the vendor's request id, a unique label for that call that their support can look up, if it sends one, plus Date), and the raw body, before your parser touches it. The raw body matters because it separates "the vendor sent null" from "my mapper dropped it".
- Your build version and config at the time, so a null that starts on a deploy day points at you.
- A derived metric per hour: nulls in the join key divided by records received, split by endpoint, record type and record creation date.
How I would test the hypothesis
- Find the onset (the time the problem started). Plot the hourly null rate. A step change (a sudden jump at one moment) is a deploy (yours or theirs); a slow ramp (a gradual climb) suggests data or a staged rollout on their side.
- Split by record age. If only records created after a date have null keys, the cause is likely in how those records are created (a new form, a new integration writing to the vendor), not in the vendor's API. If old records that used to return the key now return null, that points at the vendor's read path.
- Replay. Re-issue the exact request for a few records that returned null. If the same request sometimes returns the key and sometimes not, the behaviour is intermittent at the vendor (replica lag, meaning a read copy of the data that is a few seconds behind the main copy, or a cache is a common kind of cause, but I would only say "consistent with" it, not claim it). If it always returns null for that record, it is a data property.
- Rule out yourself. Run the previous build's parser on the stored raw bodies. Same nulls means the bytes already had them.
- Compare against a pinned older API version if the vendor offers versions, and against a known-good baseline of raw payloads if you kept one.
Worked example (assumed numbers, hand arithmetic)
Assume the sync made 2,000 sampled calls a day. Before the suspected change day, 0 of 2,000 had a null key. After it, 38 of 2,000 did.
- Null rate after = 38 / 2,000 = 0.019 = 1.9 percent.
- Split of those 38 by record creation date (assumed): 36 created before the change day, 2 after. So 36 / 38 = 94.7 percent of nulls are old records that previously had keys, which supports a change in how the vendor returns them rather than a change in data entry.
- Replay (assumed): 5 of the null records replayed 10 times each; 3 of the 5 returned the key on some attempts. That is intermittent at the source, which is the most useful single fact to give the vendor. Ten replays is a reasonable minimum: if a record's key came back on 30 percent of attempts, ten nulls in a row would still happen about 3 percent of the time (0.710≈0.028), and three nulls in a row about 34 percent of the time, so an all-null result after only a few replays says little.
These figures are assumptions for illustration, not measurements.
The same arithmetic from stored captures
One stored capture, as an illustrative record (the URL, ids and header names are invented):
{"captured_at": "2026-03-02T14:02:11Z", "request": {"method": "GET", "url": "https://api.vendor.example/v2/contacts/884", "api_version": "2025-11-01"}, "response": {"status": 200, "headers": {"Date": "Mon, 02 Mar 2026 14:02:11 GMT", "X-Request-Id": "req-7f3a"}, "raw_body": "{\"id\": \"884\", \"email\": \"[redacted]\", \"external_id\": null}"}, "build": "sync-2026.03.01"}
With captures in a table, the null rate and the split by record creation date are one group-by each. This program builds 2,000 assumed captures with exactly the counts above and prints the same figures, then prints the replay arithmetic:
import pandas as pd
# 2,000 sampled responses from the day after the suspected change, built so the counts are exact:
# 36 null keys on records created before the change day, 2 on records created after it.
newer_records = {7, 1999}
null_keys = set(range(0, 36 * 53, 53)) | newer_records
df = pd.DataFrame({
"join_key": [None if i in null_keys else f"k{i}" for i in range(2000)],
"record_created": ["after_change" if i in newer_records else "before_change" for i in range(2000)],
})
print("null keys:", int(df.join_key.isna().sum()), "of", len(df), "=", round(df.join_key.isna().mean(), 4))
print(df[df.join_key.isna()].groupby("record_created").size().to_string())
# How many replays make "always null" informative? If the key came back on 30% of attempts,
# the chance that n replays are all null is 0.7 ** n.
for n in (3, 5, 10):
print(f"{n} replays all null if the key returns 30% of the time: {0.7 ** n:.3f}")
Output
null keys: 38 of 2000 = 0.019
record_created
after_change 2
before_change 36
3 replays all null if the key returns 30% of the time: 0.343
5 replays all null if the key returns 30% of the time: 0.168
10 replays all null if the key returns 30% of the time: 0.028
Reading the output: 38 of 2,000 is 0.019; the split shows 36 nulls on records created before the change day and 2 after; the last three lines are the all-null probabilities for 3, 5 and 10 replays under the assumed 30 percent return rate.
Temporary mitigations
- Quarantine, do not guess. Records with a null join key go to a holding table (a dead-letter table, meaning a holding table for items that could not be processed), not into the joined dataset, and are re-fetched later. Never fall back to fuzzy matching on name, because that creates wrong joins that are hard to find later.
- Retry the fetch once or twice for a null key, with backoff, since the replay suggests it can resolve itself. Cap this so you do not multiply load on a degraded vendor.
- Use a secondary key if the vendor documents one that is unique (for example an email address plus the vendor id), and mark such rows as matched by fallback so they can be audited.
- Alert on the null rate crossing a threshold, and freeze downstream jobs that would publish bad aggregates.
- Pin the API version if the vendor supports it and the older version does not show the problem.
Escalating while uncertain
Send a support ticket (or ask your account contact) with: a one-paragraph summary, the onset time in UTC, the affected endpoints, 3 to 5 example request ids with the good and bad responses side by side, the null rate before and after, what you ruled out (your parser, your version), and what you have not ruled out. State the uncertainty plainly: "we observe this on our side; we cannot see yours; here is the evidence". Ask two specific things: whether anything changed in that area around the onset, and whether they can look up those request ids. Set severity by business impact, not by how sure you are, and name a time at which you will update them.
An illustrative ticket draft (the endpoint, ids and times are invented):
Subject: Join key returned as null on some responses since 2 March, about 08:00 UTC
Summary: Since about 2026-03-02 08:00 UTC, 38 of 2,000 sampled responses (1.9 percent)
from GET /v2/contacts/{id} returned external_id: null. Before that: 0 of 2,000.
36 of the 38 are records created before 2 March. We replayed the same request 10 times
for 5 of them; 3 of the 5 returned the key on at least one attempt.
Examples (request id, result):
req-7f3a external_id null 14:02:11Z
req-7f3a replayed, external_id set 14:09:40Z
req-81c2 external_id null 14:03:02Z
req-90d4 external_id null 14:05:57Z
Ruled out: our parser (the previous build gives the same nulls on the stored raw bodies).
Not ruled out: a change on your side to caching or read replicas.
Please tell us: did anything change in this area around 08:00 UTC on 2 March, and can you
look up the request ids above?
Impact: the nightly customer sync is holding affected records back. We will update this
ticket by 17:00 UTC tomorrow.
Common mistakes
- Debugging from parsed objects instead of raw bodies.
- Declaring "the vendor broke it" before running the old parser on the stored bytes.
- Backfilling with guessed matches.
- A ticket that says "your API is broken" with no request ids.
Running the code
Save the program as null_key_check.py and run python null_key_check.py with Python 3.12 and pandas 2.2. It prints the output shown.
You are integrating a CRM, an ad platform, a product analytics tool and a support system, and each names and structures customer fields differently. How would you design the mapping layer so these systems can exchange data without every downstream consumer needing custom logic?
Sample Answer
The idea in plain words
Give every external system a small translator (an adapter) that converts its records into one internal shape, the canonical data model (a single agreed definition of "customer" that the rest of your product uses), and back. Downstream consumers then read only the canonical shape. This is a hub-and-spoke design: with 4 systems you write 4 adapters, instead of a separate conversion for each pair. The catch is that a canonical model is a design decision with trade-offs, so keep it small and keep the original data.
Why hub-and-spoke (counted)
Pairwise, each of the 4 systems needs a conversion to each of the other 3: 4 x 3 = 12 one-way mappings. With a canonical model each system needs one mapping into it and one out of it: 4 x 2 = 8 mappings, grouped as 4 adapters (an adapter holds both directions: one function into the canonical shape and one out of it), and a fifth system adds 2 mappings instead of 8. (Check: the fifth system pairwise needs 4 conversions out and 4 in, which is 8.)
An illustrative example (invented field names)
The field names below are assumptions, not any real product's schema.
| Meaning | CRM | Ad platform | Product analytics | Support system |
|---|---|---|---|---|
| Person's id in that system | contact_id | user_id | distinct_id | requester_id |
| hashed_email | email_prop | email_address | ||
| Name | FirstName, LastName | (none) | name | full_name |
| Consent to marketing | HasOptedOut (inverted meaning) | consent_flag | (none) | (none) |
| Last change time | LastModifiedDate | updated | last_seen | updated_at |
One record traced through the adapter
Take one illustrative CRM record: contact_id 003-884, Email " Ann@X.com " (with stray spaces and capitals), FirstName Ann, LastName Lee, HasOptedOut true, and LastModifiedDate 2026-03-02T14:05:00+02:00. The adapter trims and lower-cases the email, inverts the opt-out flag into marketing_consent, converts the timestamp to UTC (14:05 at +02:00 is 12:05 UTC), and writes a crosswalk row. The reverse function shows the way back out. The last lines show the safe default when the CRM record has no consent flag, or a null one, and the one case that grants consent.
import json
from datetime import datetime, timezone
def crm_to_canonical(rec, customer_id):
last = datetime.fromisoformat(rec["LastModifiedDate"])
if last.tzinfo is None: # a production adapter would send this record to its error output
raise ValueError("LastModifiedDate has no UTC offset; refusing to guess a zone")
last = last.astimezone(timezone.utc)
return {
"customer_id": customer_id,
"email": rec["Email"].strip().lower(),
"given_name": rec.get("FirstName") or None,
"family_name": rec.get("LastName") or None,
"marketing_consent": rec.get("HasOptedOut") is False, # only an explicit false opts in; missing or null means no consent
"source_system": "crm",
"source_id": rec["contact_id"],
"source_updated_at": last.isoformat().replace("+00:00", "Z"),
"extensions": {},
}
def canonical_to_crm(c):
return {"contact_id": c["source_id"], "Email": c["email"],
"HasOptedOut": not c["marketing_consent"]}
crm_record = {"contact_id": "003-884", "Email": " Ann@X.com ", "FirstName": "Ann",
"LastName": "Lee", "HasOptedOut": True,
"LastModifiedDate": "2026-03-02T14:05:00+02:00"}
canonical = crm_to_canonical(crm_record, "cust-1001")
print(json.dumps(canonical, indent=2))
print("crosswalk row:", ("cust-1001", "crm", "003-884"))
print("back to the CRM shape:", canonical_to_crm(canonical))
without_flag = {k: v for k, v in crm_record.items() if k != "HasOptedOut"}
print("flag missing, consent:", crm_to_canonical(without_flag, "cust-1001")["marketing_consent"])
null_flag = {**crm_record, "HasOptedOut": None}
print("flag null, consent:", crm_to_canonical(null_flag, "cust-1001")["marketing_consent"])
explicit_false = {**crm_record, "HasOptedOut": False}
print("flag false, consent:", crm_to_canonical(explicit_false, "cust-1001")["marketing_consent"])
Output
{
"customer_id": "cust-1001",
"email": "ann@x.com",
"given_name": "Ann",
"family_name": "Lee",
"marketing_consent": false,
"source_system": "crm",
"source_id": "003-884",
"source_updated_at": "2026-03-02T12:05:00Z",
"extensions": {}
}
crosswalk row: ('cust-1001', 'crm', '003-884')
back to the CRM shape: {'contact_id': '003-884', 'Email': 'ann@x.com', 'HasOptedOut': True}
flag missing, consent: False
flag null, consent: False
flag false, consent: True
Reading the output: HasOptedOut: true became marketing_consent: false, so the meaning is preserved even though the CRM stores the opposite question. The email is normalised, which is what makes exact-match identity resolution work. source_updated_at is in UTC with a Z suffix, which is what the replay rule below compares. The crosswalk row ties our cust-1001 to the CRM's 003-884. A record with no HasOptedOut field, or with a null one, maps to marketing_consent: false, the no-consent default; only an explicit HasOptedOut: false maps to true.
The design
- Canonical record, kept small: our own
customer_id;email(lower-cased, trimmed);given_name,family_name(nullable, meaning they may be empty);marketing_consent(boolean plus a time and source);source_system,source_id,source_updated_at;extensions(a map for fields only one system has). - Identity crosswalk table (a lookup table saying which vendor id belongs to which of our customers): (customer_id, system, source_id). The canonical id is ours, so no vendor id leaks into consumers.
- Per-system adapter: field mapping, type conversion (the inverted
HasOptedOutbecomesmarketing_consent = (HasOptedOut is false), so a missing or null flag cannot grant consent), unit and time-zone normalisation to UTC (a timestamp with no offset is rejected, not guessed), and an error output for records that cannot be mapped. Mapping tables live in versioned configuration, so a vendor renaming a field is a config change and a test run. - Raw payload retention: store the original record next to the canonical one (for debugging and re-mapping when the model changes).
- Field-level source of truth (the system whose value wins when systems disagree): decide per field which system wins on a conflict. For example, the CRM owns name and consent; the support system owns nothing; the ad platform's hashed email (a one-way scrambled fingerprint of the address: the same address always gives the same fingerprint, but the address cannot be recovered from it) is used only for matching, never as the stored email. Without this rule two systems overwrite each other in turn.
- Identity resolution: matching records across systems (the same person has a different id in each) is the hardest step. Start with exact match on normalised email; treat fuzzy matches (names or emails that are similar but not identical, such as "Jon" and "John") as suggestions that need review, not automatic merges.
- Change propagation: adapters emit canonical change events; consumers subscribe. A consumer needing a field the model lacks asks for a model change, which is versioned.
Trade-offs, and the decision
A canonical model has costs: it can become a lowest common denominator (fields only some systems have get dropped) or a union that nobody understands. It also becomes a shared dependency, so changes need ownership and versioning. My decision for 4 systems that need to exchange customer data: use a canonical model, deliberately thin (identity, contact, consent, timestamps), with extensions and raw payloads for the rest. If only two systems ever talk and nothing else will join, a direct mapping is cheaper and I would not build the hub.
Failure modes
- Lossy mapping: hashed email cannot be reversed, so an ad-platform record can match but not create a customer.
- Consent semantics: inverted, missing or null flags must default to "no consent", not "consent". Test the null value as well as the absent key, because
not Noneis true. - Replays (the same update delivered again) and out-of-order updates (an older update arriving after a newer one): compare
source_updated_atbefore overwriting. - Drift: a vendor adds an enum value (one more entry in a fixed list of allowed values, such as a new status option); unknown values go to a review queue, not a silent default.
Common mistakes
- Making the canonical model mirror the CRM, which re-couples everything to one vendor.
- Mapping inside each consumer.
- Dropping the raw payload and then being unable to re-map.
Running the code
Save the program as crm_adapter.py and run python crm_adapter.py with Python 3.12. It prints the output shown.
Design a sync of lead data from a CRM, about 100,000 new or updated leads a day, to another SaaS tool, with a target latency under 5 seconds for priority records. It must resolve duplicates, honour consent flags, tolerate vendor outages, and keep one clear source of truth for each record.
Sample Answer
The idea in plain words
This is a one-way synchronisation between two systems you do not fully control. Three ideas decide whether it is correct. First, give every field one owner (the system of record, meaning the system whose value wins when the two disagree). Second, treat consent as a gate that fails closed: if you cannot prove a lead may be sent, do not send it. Third, put a durable queue between the CRM and the destination so that a vendor outage delays records and loses none, and use separate lanes so the few records with the 5 second target are not stuck behind bulk traffic. In an interview, say these three ideas and the field-owner table first; the latency budget, outage maths and reconciliation come next.
Requirements, with the numbers stated
Assumptions (stated, not given): 100,000 changed leads per day, spread over the day on average, with bursts of up to 10 times the average; 5 percent of changes are flagged priority; the destination accepts single-record upserts and batches of 100; its call latency at the 99th percentile is 2 seconds (99 percent of calls finish faster than that, so it is a near-worst-case figure). An upsert is a write that updates the record if it already exists and inserts it if it does not.
- Average rate: 100,000 / 86,400 seconds in a day = 1.157 records per second.
- Design peak at 10 times: 1.157 x 10 = 11.57 records per second.
- Priority volume: 100,000 x 0.05 = 5,000 records per day = 0.058 per second.
- Bulk lane in batches of 100: the 95,000 non-priority records give 95,000 / 100 = 950 vendor calls per day, which is 0.011 calls per second. Batching makes the vendor's request-count limits easy to respect; the priority lane sends single records because waiting to fill a batch would break 5 seconds.
These rates are low. The hard parts are correctness and outages, not throughput.
Who owns what
| Data | System of record | Rule |
|---|---|---|
| Identity and contact fields (name, email, phone, company) | CRM | Overwrite the destination on change |
| Consent flags | The consent source, which is the CRM field if that is where consent is captured | Withdrawal always overwrites; the destination can never grant consent |
| Destination-only fields (engagement scores, campaign membership) | Destination | Never written back or overwritten by the sync |
| The link between records | A mapping table in your service: CRM lead id, destination id | Owned by the sync |
One owner per field means a conflict has a defined winner and the sync never needs to guess.
The pipeline
- Capture. Use the CRM's change events (a webhook, meaning the CRM calls your URL when a lead changes, or a change feed, a stream of change records you read) for low latency, and a periodic cursor poll as the safety net, since event delivery can drop. The poll asks the CRM for leads modified since the last saved timestamp (the cursor), starting a few minutes earlier than that timestamp (the overlap window) so a change committed late is not missed; the version check in step 5 makes the repeats harmless. Both feed the same intake stage, which routes each record to a lane in step 2, and duplicates are expected (delivery is at least once, so a receiver must tolerate repeats).
- Two queues: priority and bulk. Reserve a worker pool for the priority queue, so a bulk call already in progress (up to about 2 seconds) never delays a priority record; spare capacity may take bulk work.
- Normalise and de-duplicate. Match deterministically: lower-cased, trimmed email is the key; fall back to phone in E.164 form (the international format: a plus sign, country code and number with no spaces, such as
+14155550123) plus a name check. Auto-merge only on deterministic matches. Fuzzy matches (similar names, same company) go to a review list, because a wrong merge sends one person's data to another person and is expensive to undo. - Consent gate. Send only if the flag says consent is granted. A missing, null or unrecognised value means "do not send". A withdrawal event goes to the priority lane, and the destination record is suppressed or deleted by whatever mechanism the destination documents.
- Version check, made atomic per lead. Each CRM change carries a version or modified timestamp. Store the last applied version per lead and drop an event that is not newer than it. A plain read-then-write is not enough: two workers can hold two events for the same lead at once (in the trace below, versions 12 and 11 of L-1001 sit in different queues), both read "last applied is 10", both pass, and the older one can land last and overwrite the newer. So run steps 4 to 7 for one lead under a per-lead lock with a lease (an expiry, so a crashed worker releases it), and let the version store accept a write only with a fencing token (a number that grows with every lock grant, so a holder whose lease has expired is refused). A lease alone does not close the race: a worker that stalls past its lease can wake up and send an older event after a newer one was already sent, because the destination cannot check the lock. Narrow that gap by giving every destination call a timeout shorter than the lease and re-checking the lease just before sending; the daily reconciliation below catches what remains. The alternative is to route every event for one lead id to the same partition and process it in order, which avoids the lock but must cover both lanes for that lead. Inside the guard, compare the version, send, then store the new version. Store the version for every decision, including a consent block or a withdrawal, so an older "granted" event cannot pass later.
- Upsert to the destination keyed on the mapped id (or email for a first sight), so a retry is harmless. Where the destination supports an idempotency key, send one derived from lead id plus version.
- Record the result in a ledger (a table with one row per lead recording what was done to it: lead id, version, state, attempts, destination id, last error).
A traced example with illustrative values, three leads arriving close together:
| Step | Lead A (priority, id L-1001, version 12) | Lead B (id L-1002, version 4) | Lead C (id L-1001, version 11, a late older event) |
|---|---|---|---|
| Capture | event arrives by webhook, goes to the priority queue | found by the cursor poll, goes to the bulk queue | duplicate delivery of an older edit, goes to the bulk queue |
| Normalise and dedupe | email Ann@Example.com becomes ann@example.com, matches the existing destination record | email bo@example.com, no match, so a new record | same email, matches the same destination record |
| Consent gate | flag granted, passes | flag is null, so do not send; ledger row blocked_no_consent | flag granted, passes |
| Version check | last applied for L-1001 is 11, so 12 is newer, passes | not reached | last applied is 12, so 11 is older and is dropped; ledger unchanged |
| Upsert | upsert keyed on the mapped destination id, idempotency key L-1001:12 | not sent | not sent |
| Ledger | state applied, version 12, attempts 1 | state blocked_no_consent, version 4 | no change |
The 5 second budget
For the priority lane, an illustrative latency budget: event reaches the queue 0.3 s, worker pickup 0.5 s, dedupe and consent lookup 0.2 s, vendor call at its 99th percentile 2.0 s. The sum is 0.3 + 0.5 + 0.2 + 2.0 = 3.0 seconds, leaving 2.0 seconds of margin and no room for a second attempt. So priority retries happen on a short second try only if the first fails fast; otherwise the record is retried with backoff and counted as a missed target. The promise is "under 5 seconds while the destination is healthy", measured as a percentile on a dashboard, not a guarantee.
Surviving vendor outages
Place a circuit breaker (a switch that stops calls after repeated failures and probes occasionally for recovery) in front of the destination. While it is open, records stay in the queue. Retry with exponential backoff and full jitter (a random wait between 0 and the exponential cap), honouring Retry-After on a 429.
Backlog size depends on the peak assumption. For an assumed 2 hour outage:
- At the average rate: 100,000 x 2 / 24 = 8,333 records.
- At the 10 times peak rate: 11.574 x 7,200 seconds = 83,333 records.
- Drain at an assumed 100 records per second (a number to confirm against the vendor's limits). While draining, new records still arrive, so the backlog shrinks at the drain rate minus the arrival rate, and the time to empty is backlog / (drain rate - arrival rate). The average backlog drains in 8,333 / (100 - 1.157) = 84.3 seconds; the peak backlog drains in 83,333 / (100 - 11.574) = 942 seconds, about 15.7 minutes. Reaching 100 records per second is plausible only with batching or concurrency: one upsert takes up to 2 seconds, so single calls need 100 x 2 = 200 in flight at once (concurrency = rate x duration), whereas batches of 100 need 100 / 100 = 1 call per second, about 2 in flight, assuming a batch call also finishes in about 2 seconds, which must be checked against the vendor's batch limits.
The peak case keeps the arrival rate at the peak value while draining, which is the conservative choice. After recovery the priority lane drains first. Make the queue large and durable; the outage is a delay, not a loss.
Proving it stays in sync
Run a daily reconciliation (a scheduled comparison of the two systems to find records that disagree): count leads changed in the CRM in the last 24 hours against ledger rows in state "applied", and compare a hash of the owned fields for a sample. Differences become alerts and replays. Track queue age (how long the oldest unprocessed record has been waiting) as the main health metric.
The judgment
I would build it as event capture plus cursor poll, two lanes, deterministic dedupe, a fail-closed consent gate, versioned idempotent upserts and a daily reconciliation. I would not build a two-way sync unless asked: it creates a conflict problem the one-owner table avoids. What would change the plan: if the destination has no upsert by key, add a lookup before each write and accept a longer latency budget; if consent lives in a third system, the gate queries it and fails closed when it is unreachable.
Common mistakes
- Designing for throughput (it is only 1.157 per second) and ignoring correctness.
- Treating missing consent as consent.
- Syncing both directions with no field owner.
- No version check, or a version check without a per-lead lock or ordering, so a replay or a racing worker overwrites newer data.
- Auto-merging on fuzzy matches.
That is every published Third-Party and SaaS Integration question for Data Engineer so far. Browse the other topics in this category, or practice this one interactively.