Enterprise Application Integration Questions
Integration architecture across many heterogeneous enterprise systems, legacy and modern: how systems exchange data (synchronous calls, push, scheduled bulk or file transfer, messaging) and when each fits, point-to-point versus middleware designs, connectors and adapters, choosing a native connector, iPaaS or custom build, bridging SOAP/XML and REST/JSON, canonical data models and schema mapping, governing shared-schema change, system-of-record ownership, orchestration versus choreography, hybrid on-premises to cloud connectivity over outbound-only or flaky links, multi-tenant integration platforms with idempotent delivery and downstream rate limits, failure handling, dead-letter queues and reconciliation at integration seams, and phased delivery against poorly understood legacy systems. Excludes the design of a single API surface, API gateway and versioning mechanics, broker-level event streaming, data-platform ingestion, and vendor selection or cloud migration programmes covered elsewhere.
An integration must reach an on-premises ERP behind a flaky VPN, with strict rules that data stays inside the customer's boundary and with outbound-only traffic through proxies and tight egress controls. Design the integration architecture to keep business disruption minimal: what runs on-prem, how data moves, what happens when the link is down, how it authenticates, and how you size the delivery effort and risk.
Sample Answer
The idea in plain words
The customer's rules decide the shape of the design. "Data stays inside the boundary" means the part of the integration that touches business data must run inside the customer's network. "Outbound-only through proxies" means nothing outside may open a connection into that network, so everything must be started from the inside. "Flaky VPN" (virtual private network, an encrypted tunnel between sites) means the link will drop, so the integration must keep working, and keep its promises about data, while the link is down.
The design that fits all three is a local runtime with a remote control plane (the control plane is the part that configures, schedules and monitors; the data plane is the part that carries the business records, and here it stays inside). A small agent (a connector process) runs on-premises next to the ERP (enterprise resource planning system, the system of record for orders, stock, finance). It reads from and writes to the ERP, transforms the data, and stores everything it cannot deliver yet in a durable local queue. It only ever dials out. The cloud side holds configuration, schedules and monitoring, and receives only the data fields the customer has approved for export. If the link fails, the agent keeps working and catches up afterwards.
Step 1: clarify before drawing anything
| Question | Why it changes the design |
|---|---|
| Which data may cross the boundary: nothing, metadata only, or a named field list? | Decides whether the cloud ever sees payloads at all |
| Which systems must the integration talk to, and in which direction? | Read-only extraction is far lower risk than writing to the ERP |
| How fresh must data be, and how long an outage must we survive? | Sets the polling interval, the buffer size and the drain plan |
| Is the proxy TLS-inspecting (it decrypts and re-encrypts traffic)? | If yes, client certificates cannot be used end to end |
| Who can approve firewall rules, and how long does that take? | Often the longest item on the calendar, not the code |
Step 2: what runs on-prem, and how data moves
ERP (system of record) customer network | boundary cloud
| adapter (API, DB view, +-----------------------------+ |
| file drop, SOAP) | integration agent (per | |
+--------------------------> | subnet): transform, validate| ---- outbound HTTPS 443 ---> ingestion
| durable disk queue (log) | <--- commands/config pulled endpoint
+-------------+---------------+ | via the same outbound
| authenticating proxy | connection (poll/long-poll)
+---------------------> |
How to read the diagram: the left box is the ERP, the middle box is the agent running inside the customer network, and the vertical bar is the network boundary. Every arrow that crosses the boundary is a connection the agent opens from the inside. The cloud never opens one. The commands/config pulled arrow is not a second connection: it is the agent asking the cloud, over the same outbound HTTPS, whether there is anything for it to do, and the cloud answers in that reply.
One message, named, to follow it through: ERP order 4711 changes status to SHIPPED. (1) The agent's adapter reads the change from the ERP. (2) It maps the record to the shared message shape and drops every field not on the approved list, for example the customer's phone number. (3) It appends the message, with id order-4711-v3, to the disk queue. (4) It posts a batch containing that message to the ingestion endpoint through the authenticating proxy. (5) The cloud stores it, replies 200, and only then does the agent delete order-4711-v3 from its queue. If the link is down at step 4, the message simply stays in the queue and step 4 is retried later.
- Adapter on-prem. The agent talks to the ERP with whatever interface the ERP offers (a SOAP or REST API, a database view, a file export). The ERP is never exposed to the internet.
- Transform and filter at the source. The agent maps ERP records to the shared message shape and strips every field that is not on the approved export list (the allowlist), or replaces a sensitive value with a meaningless stand-in called a token while the real value stays on-prem. This is how "data stays inside" is enforced in code: the filter runs inside the boundary, before anything is queued for sending.
- Durable local queue. Each message is written to disk (an append-only log or an embedded database) before it is acknowledged to the source. Only after the cloud acknowledges receipt is it removed. This is store-and-forward: hold the message now, send it when the link allows.
- Outbound pull and push over one port. The agent opens HTTPS (port 443, outbound) to the ingestion endpoint. It pushes batches up, and it polls (or long-polls, meaning the server holds the request open until there is something to say) for commands and configuration. No inbound firewall rule is needed.
- One forwarder agent per subnet or network zone. A subnet is a separate address range inside the customer network, and zones are often walled off from each other. Segmented networks often cannot reach each other, so each zone runs an agent with its own disk buffer. A zone agent forwards to the one that has proxy access, or each has its own approved proxy route. This avoids a single choke point and keeps a failure to one zone.
- Cloud side keeps only what is allowed. Ingestion stores approved fields in the customer's region, and the control plane keeps run status, counts and error codes, never payloads.
Step 3: authentication and the proxy
Proxy authentication. A corporate proxy often answers the agent's CONNECT request (the request that asks the proxy to open a tunnel) with 407 Proxy Authentication Required and a Proxy-Authenticate header (407 is the proxy's own version of 401: it asks for credentials meant for the proxy, not for the destination) naming the scheme, such as Negotiate (which carries Kerberos, a ticket-based protocol used inside Windows domains) or NTLM (an older challenge-response scheme). The agent then repeats the request with a Proxy-Authorization header. Illustrative exchange:
CONNECT ingest.example.com:443 HTTP/1.1
Host: ingest.example.com:443
HTTP/1.1 407 Proxy Authentication Required
Proxy-Authenticate: Negotiate
Content-Length: 0
CONNECT ingest.example.com:443 HTTP/1.1
Host: ingest.example.com:443
Proxy-Authorization: Negotiate <base64 ticket>
The <base64 ticket> in the last request is a Kerberos ticket: a short-lived proof of identity that the agent obtains from the domain's Kerberos server using its own service account, then sends as base64 text (a way of writing binary data using only printable characters). Prefer Kerberos with a dedicated service account for the agent. Its credentials sit in a keytab (a protected file holding the service account's key, so the agent can get tickets without a person typing a password) or the OS credential store, never in a config file in plain text. NTLM is weaker and is a fallback for proxies that offer nothing else. Ask for an allowlist rule (a firewall or proxy entry that explicitly permits one destination) for the ingestion hostname so the agent does not depend on a human user's session.
Authenticating to the cloud. There are two common choices. A first design needs only one of them; the proxy sign-in above, the local queue and outbound HTTPS are the parts that must exist on day one.
| Option | Strength | Weakness here |
|---|---|---|
| mTLS (mutual TLS, both sides present certificates) | Strong identity at the connection level | A TLS-inspecting proxy ends the connection, so the cloud never sees the agent's certificate; needs a passthrough rule and certificate rotation work |
| Short-lived access token (for example an OAuth 2.0 client-credentials grant, signed with a private key the agent holds) | Works through inspection, expires in minutes, revocable | Needs a secure place for the signing key and a token refresh path that still works when the link is flapping |
My recommendation: use short-lived tokens as the baseline because they survive an inspecting proxy, keep the private key in the host's key store, and add mTLS only if the customer's proxy passes the tunnel through untouched. Rotate keys on a schedule and make the agent refuse to run on a clock that is badly wrong, since token validity depends on time.
Step 4: what happens when the link is down
- The agent keeps reading from the ERP and writing to the disk queue. Nothing is lost while the disk has room.
- Sending retries with exponential backoff and jitter (a random wait that grows after each failure, so a recovering link is not hit by every agent at once). Between attempts the agent probes cheaply, so it notices recovery quickly.
- Every message carries an id and a per-entity sequence number. The cloud side deduplicates on the id, so redelivery after a half-completed batch is harmless (the link can drop after the cloud stored a batch but before the agent saw the acknowledgement).
- Order matters per business entity (an order's update 3 must not overtake update 2), not across the whole stream. The cloud applies per-entity order using the sequence number.
- The queue has a size limit and a stated policy for when it fills. For example: alert at 70 percent, then pause low-priority feeds and keep critical ones, and never silently drop. The policy is agreed with the customer in advance.
- After recovery the agent drains the backlog at a capped rate so catch-up traffic does not starve live traffic or saturate the shared VPN.
- A daily reconciliation compares counts and control totals (the sum of a numeric column, such as order amounts, computed on both sides and compared) per entity between the ERP extract and what the cloud holds, and reports gaps. This is the safety net that proves the buffer worked.
Air-gapped fallback (needed only if no live link is allowed). Air-gapped means the network has no live connection to the outside. If the customer needs a mode with no live link at all (or the link is down for days), the agent writes signed export files: a batch of records, a manifest with record count, a hash of the content and a batch sequence number. A person carries the file across (or it passes through an approved transfer point), and an importer on the other side verifies the signature, the hash and that the sequence number has no gap, then loads it with the same deduplication. This is slower but uses the same message format, so it is a transport swap, not a second system.
Step 5: sizing bandwidth, disk and drain time
The inputs below are assumptions for the example, to be replaced with measured volumes in discovery.
- 200,000 messages per day, 4 KB (kilobytes, decimal) each.
- Traffic is uneven: 60 percent of the day's messages arrive in an 8-hour business window, and short bursts inside that window (a few minutes) reach 10 times the daily average rate. A whole business day cannot run at 10 times the average, because the day's total would then be several times 200,000.
- The outage to survive is 8 hours that covers the whole business window (the worst case), and 3 days for the disk limit.
- The VPN offers 10 Mbit/s and the integration may use at most half of it while draining.
Step by step:
- Daily volume: 200,000×4 KB=800,000 KB=800 MB.
- Average rate: 800,000 KB/86,400 s≈9.26 KB/s≈74 kbit/s (multiplying by 8 bits per byte).
- Burst at 10 times: about 741 kbit/s, which is 0.74 Mbit/s, well under a 10 Mbit/s link. Steady-state bandwidth is therefore not the constraint; the drain is.
- Backlog after an 8-hour outage over the business window: 0.6×200,000=120,000 messages, which is 120,000×4 KB=480 MB. (An 8-hour outage at night holds far less: 200,000/24×8≈66,667 messages, about 267 MB if traffic were even.)
- Drain at 5 Mbit/s (half the link): 480 MB×8=3,840 Mbit, and 3,840/5=768 s≈12.8 minutes. Live traffic arriving during the drain in the business window averages 120,000×4 KB×8/28,800 s≈0.13 Mbit/s, which stretches the drain to about 13 minutes if the drain shares the 5 Mbit/s budget, so it does not change the conclusion.
- Disk for 3 days: 800 MB×3=2,400 MB; with a 2 times safety factor (for retries, indexes and growth) provision about 4.8 GB per agent that carries the whole feed.
Latency is a different calculation: the agent batches (for example up to 100 messages or 1 second), so end-to-end delay in a healthy state is dominated by the batch wait plus one round trip through the proxy, which the pilot measures.
Step 6: sizing the delivery effort and risk
This step is project planning rather than architecture, and interviewers often ask it as a closing question. A three-point estimate (also called a PERT estimate) per work item, in engineer-weeks, using (O+4M+P)/6 where O is optimistic, M is most likely and P is pessimistic. These O, M and P values are assumptions for a team of three.
| Work item | O | M | P | Expected |
|---|---|---|---|---|
| Discovery, access and firewall approvals | 2 | 3 | 6 | 3.33 |
| Agent, disk queue, retry and drain | 4 | 6 | 9 | 6.17 |
| Proxy and authentication | 2 | 3 | 8 | 3.67 |
| ERP adapter and field filter | 3 | 5 | 10 | 5.50 |
| Security and performance testing | 3 | 4 | 7 | 4.33 |
| Pilot and cutover | 2 | 3 | 5 | 3.17 |
| Total | 26.17 |
Variance is a measure of spread (the average squared distance from the expected value), and the standard deviation is its square root. For independent items the variance of the total is the sum of the item variances, and each item's variance is ((P−O)/6)2=(P−O)2/36. The six values of (P−O)2 are 16, 25, 36, 49, 16 and 9, which sum to 151. So the summed variance is 151/36≈4.19, the standard deviation is 4.19≈2.05 weeks, and a two-standard-deviation range is 26.17±4.10, about 22.1 to 30.3 engineer-weeks. If the work divides evenly across three engineers (perfect parallelism, which real projects never reach), that is 22.1/3≈7.4 to 30.3/3≈10.1 calendar weeks, with a midpoint of 26.17/3≈8.7. Handoffs and shared dependencies make the upper end the safer figure to quote. Approvals by the customer's security and network teams run on their calendar, not ours, so I would quote the approvals as a separate dependency with a date.
Top risks, with the mitigation each gets: (1) firewall and proxy approvals slip, so start the requests in week one and use a test endpoint; (2) the ERP has no good change feed, so budget for polling on a modified-date column and test its cost on the ERP; (3) TLS inspection breaks the chosen authentication, so test through the real proxy early; (4) disk fills during a long outage, so ship the size limit and alert before go-live; (5) a bad field filter leaks data, so make the allowlist reviewed code with tests, not a setting.
Step 7: test plan
- Security tests: scan the host for open inbound ports (expect none); confirm payloads never appear in cloud logs; use an expired token and a wrong clock to confirm the agent stops and alerts; confirm the field filter drops a field that is not on the list.
- Performance tests: replay a day of recorded or synthetic messages with bursts at 10 times the average, then throttle the link to the planned 5 Mbit/s and measure drain time against the 13 minute estimate.
- Failure tests: cut the link mid-batch, kill the agent between writing to disk and sending, fill the disk to the alert threshold, and restart the proxy; after each, the reconciliation report must show zero missing and zero duplicate records.
Judgment
I would commit to the local-runtime, outbound-only agent with store-and-forward, short-lived-token authentication, a field allowlist enforced on-prem, and a daily reconciliation. What would change it: if the customer allows no outbound connection at all, the signed-file path becomes the primary transport; if the proxy passes tunnels through, add mTLS; if the ERP offers a reliable event feed, replace polling with it. The pilot's job is to turn the assumptions in steps 5 and 6 into measurements.
Common mistakes
- Designing a cloud-hosted integration that calls into the ERP, which needs an inbound path the customer forbids.
- Sending whole records to the cloud and masking later, instead of filtering at the source.
- Retrying forever without a size limit on the buffer, or dropping data silently when it fills.
- Assuming mTLS works through a TLS-inspecting proxy.
- Treating the VPN as reliable and having no reconciliation to prove nothing was lost.
What is a canonical data model in system integration? Explain its benefits, its drawbacks, and the basic process for creating and maintaining one for customer and event data shared across several vendor systems.
Sample Answer
The idea in plain words
A canonical data model is one agreed, system-neutral description of a shared business concept, such as "customer" or "order placed event". Instead of translating directly from every system's format to every other system's format, each system translates only to and from the canonical form. The middle format is the shared language; each system needs one translator for it.
Why it helps: the counting argument
If N systems must exchange data and each direction needs its own mapping, direct (point-to-point) integration needs N(N−1) mappings. With a canonical model each system needs one mapping into it and one out of it: 2N.
| Systems N | Direct mappings N(N-1) | Via canonical 2N |
|---|---|---|
| 3 | 6 | 6 |
| 4 | 12 | 8 |
| 5 | 20 | 10 |
| 8 | 56 | 16 |
| 12 | 132 | 24 |
At 3 systems they tie; from 4 upward the canonical model needs fewer mappings, and the gap widens quickly. Adding a ninth system costs 2 new mappings, not 16. This assumes every system really needs to talk to every other; if the flows are few, direct links are cheaper.
Benefits
- Fewer mappings to build, test and fix when a vendor changes its format: only that vendor's two mappings change.
- One shared vocabulary: "customer" means the same thing to every team.
- A single place to put validation and policy (required fields, allowed values).
- New systems join by writing two mappings.
Drawbacks
- Lowest common denominator or bloat: a model that must satisfy everyone either drops fields some system needs or carries many rarely used ones. Example: the CRM stores a contact's preferred call time, the billing system has no such field, and a model cut down to what every system shares would drop it on the way through; the
extensionsobject in the design steps below is how it is carried instead. - Two translations per hop: data goes source to canonical to target, so a field that does not survive the first mapping cannot be recovered in the second.
- A governance bottleneck: someone must own changes, and slow change approval blocks every project that needs a new field.
- Semantic disagreement is hidden, not solved: two systems may use "active customer" differently; a shared field name does not make the meaning shared.
- Versioning work: a change to the model affects all mappings.
Creating and maintaining one, step by step
Scope: customer and event data shared across several vendor systems.
- Pick the shared entities only. Start with the few entities that cross systems (customer, account, order placed, subscription changed). Do not model every field of every system.
- Write a glossary with owners. Define each term in a sentence, and name the system of record (the system whose value wins) for each attribute. For example, the billing system owns the billing address; the support tool owns the ticket count.
- Design the model. Choose stable identifiers (a canonical customer id plus the source system ids kept as a list), UTC timestamps (UTC is the single worldwide reference time; a value like
2026-03-01T09:30:00Zends inZto say so, and each system converts to local time only for display), money as integer minor units plus a currency code (a price of 12.50 USD is stored as the integer 1250 with the codeUSD, which avoids fractional rounding errors), and enumerated values for statuses (a fixed list of allowed values, such asactive,inactiveandsuspended, instead of free text). Keep anextensionsobject for source-specific fields so they are carried, not lost. - Write the mapping tables. For every vendor field state the target field, the transformation and the default. Test each with sample records from the real system.
- Publish a schema and validate at the edge. Store the model as a schema file (JSON Schema is a standard format for describing which fields a JSON document must have and what values they may hold) in version control, and validate messages when they enter the integration layer. An illustrative fragment:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["event_id", "event_type", "occurred_at", "customer"],
"properties": {
"event_id": {"type": "string"},
"event_type": {"type": "string"},
"occurred_at": {"type": "string"},
"amount_minor": {"type": "integer"},
"currency": {"type": "string", "pattern": "^[A-Z]{3}$"},
"customer": {
"type": "object",
"required": ["customer_id"],
"properties": {
"customer_id": {"type": "string"},
"status": {"enum": ["active", "inactive", "suspended"]}
}
}
}
}
The fragment deliberately does not set additionalProperties to false, so a message that carries a field the schema does not list still validates. A message missing event_id, or carrying a customer.status of maybe, fails validation at the edge and is rejected before it reaches any consumer. The canonical event shown below passes this fragment.
6. Version with a compatibility rule. Adding an optional field is non-breaking only for consumers that ignore fields they do not know (a tolerant reader), so make that a rule of the model. A consumer whose own schema forbids unknown properties, or a change that makes the new field required, breaks. Removing, renaming, retyping or tightening a field is a new version. Support the old version for a stated period.
7. Govern lightly. A small review group, a change request template and a published change log. Review the model against real use every quarter and remove fields nobody reads.
An illustrative canonical event, with every field explained:
{
"event_id": "3f6c1a52-0d1e-4c7b-9b1a-6a2f4e9c1b10",
"event_type": "customer.updated",
"schema_version": "1.2",
"occurred_at": "2026-03-01T09:30:00Z",
"source_system": "crm",
"customer": {
"customer_id": "C-100234",
"source_ids": [{"system": "crm", "id": "0031A00001"}, {"system": "billing", "id": "88231"}],
"email": "alex@example.com",
"status": "active"
},
"extensions": {"crm": {"region_code": "EMEA-N"}}
}
event_id is a unique id so receivers can drop duplicates; event_type and schema_version tell consumers how to read the rest; occurred_at is in UTC; customer_id is the canonical id and source_ids link it back to each vendor; extensions carries source-specific data without changing the core schema.
Judgment
Use a canonical model when four or more systems share the same concepts and will change independently. Keep it small, own it like a product, and do not use it to model everything. For two or three systems with stable formats, direct mapping is simpler.
Common mistakes
- Trying to model every field of every system on day one.
- Having no owner, so the model drifts from the real systems.
- Assuming a shared field name means a shared meaning.
- Dropping source fields that were not modelled, with no way to carry them.
Two systems you must integrate use incompatible schemas. Where would you put the transformation (in the client, at the edge, or in a dedicated integration layer), and how would you handle schema mapping, validation, and change over time? When would you introduce a shared canonical model versus mapping each pair directly?
Sample Answer
The idea in plain words
Two systems store the same business thing (a customer, an order) in different shapes: different field names, formats, code lists and rules. Something has to translate. A schema mapping is the written rule set for that translation (this field maps to that field, with this conversion). The questions are where the translation runs, how you keep it correct as either schema changes, and whether every pair of systems gets its own mapping or all systems translate to one shared shape. That shared shape is a canonical data model: one agreed, system-neutral definition of the entity that every system maps to and from.
Where the transformation lives
| Place | Good for | Problem |
|---|---|---|
| In the client (each caller translates) | nothing beyond a single caller | every caller repeats the mapping and drifts; a schema change means redeploying all clients |
| At the edge (an API gateway, a front-door service that routes and reshapes requests, or a proxy) | small, stateless changes (needing no memory of earlier messages): rename a field, change a date format, add a header | no place for lookups, enrichment (adding data fetched from another source, such as a customer's region from a reference table) or multi-step logic; business logic hides in gateway configuration |
| In a dedicated integration layer (a service, or a middleware flow: a configured chain of steps in an integration product, that owns the mapping) | anything with lookups, enrichment, splitting or merging, several targets, error handling, versioned mappings | one more component to run; must not turn into a place where business rules for other teams pile up |
I would put non-trivial mapping in the dedicated integration layer, keep trivial reshaping at the edge, and keep it out of clients. Reason: the mapping is knowledge about two systems' schemas, and it should live in one owned, tested, versioned place that both can change independently of.
Handling mapping, validation and change
- Write the mapping as data or a small declarative table, not scattered code. Example (invented systems): the CRM stores
cust_nmas"DOE, JANE",dobasDDMMYY(070385) andcntryas a full name; the ERP wantsgivenName,familyName,birthDateas1985-03-07andcountryCodeas ISO 3166-1 alpha-2 (the standard two-letter country codes).
| Source field | Rule | Target field |
|---|---|---|
cust_nm "DOE, JANE" | split on the first comma, trim, swap | familyName "DOE", givenName "JANE" |
dob 070385 | parse DDMMYY, choose the century with a stated rule (a two-digit year of 85 read as 1985 because dates of birth are in the past), emit an ISO 8601 date (the international year-month-day format) | birthDate 1985-03-07 |
cntry "Germany" | lookup in a maintained code table; unknown value goes to the reject queue, never guessed | countryCode DE |
The program below applies exactly these three rules, then shows the change rules from step 3 on real messages and counts the mappings compared in the next section.
from datetime import date
TODAY = date(2027, 1, 1) # fixed so the century rule repeats exactly
COUNTRIES = {"Germany": "DE", "France": "FR"}
def map_customer(src):
family, given = [p.strip() for p in src["cust_nm"].split(",", 1)]
dd, mm, yy = int(src["dob"][:2]), int(src["dob"][2:4]), int(src["dob"][4:])
year = 2000 + yy
if date(year, mm, dd) > TODAY: # birth dates are in the past
year -= 100
code = COUNTRIES.get(src["cntry"])
if code is None:
raise ValueError(f"unknown country {src['cntry']!r}: send to reject queue")
return {"givenName": given, "familyName": family,
"birthDate": date(year, mm, dd).isoformat(), "countryCode": code}
REQUIRED = ("givenName", "familyName", "birthDate", "countryCode")
def read_customer(msg):
"""Tolerant reader: take the fields it needs, ignore any others."""
missing = [k for k in REQUIRED if k not in msg]
if missing:
raise KeyError(f"missing {missing}")
date.fromisoformat(msg["birthDate"]) # type and format check
return {k: msg[k] for k in REQUIRED}
ok = map_customer({"cust_nm": "DOE, JANE", "dob": "070385", "cntry": "Germany"})
print("mapped:", ok)
try:
map_customer({"cust_nm": "ROE, RICK", "dob": "010190", "cntry": "Atlantis"})
except ValueError as e:
print("rejected:", e)
cases = {
"extra field added": {**ok, "loyaltyTier": "gold"},
"field renamed": {k if k != "birthDate" else "dateOfBirth": v for k, v in ok.items()},
"field retyped": {**ok, "birthDate": 19850307},
}
for name, msg in cases.items():
try:
read_customer(msg)
print(f"{name}: accepted")
except (KeyError, TypeError, ValueError) as e:
print(f"{name}: BREAKS ({type(e).__name__}: {e})")
flows = [("CRM", "ERP"), ("CRM", "Billing"), ("CRM", "Support"),
("ERP", "Billing"), ("ERP", "Warehouse")]
sources = {s for s, _ in flows}
targets = {t for _, t in flows}
print("direct mappings:", len(flows), "| canonical mappings:", len(sources) + len(targets))
for n in (3, 4, 5):
print(n, "systems, all pairs both ways:", n * (n - 1), "direct vs", 2 * n, "canonical")
Output:
mapped: {'givenName': 'JANE', 'familyName': 'DOE', 'birthDate': '1985-03-07', 'countryCode': 'DE'}
rejected: unknown country 'Atlantis': send to reject queue
extra field added: accepted
field renamed: BREAKS (KeyError: "missing ['birthDate']")
field retyped: BREAKS (TypeError: fromisoformat: argument must be str)
direct mappings: 5 | canonical mappings: 6
3 systems, all pairs both ways: 6 direct vs 6 canonical
4 systems, all pairs both ways: 12 direct vs 8 canonical
5 systems, all pairs both ways: 20 direct vs 10 canonical
The first line is the table's three rows applied to the invented CRM record. The second shows an unknown country rejected with a reason instead of guessed. The next three lines send changed versions of the ERP message to a reader that needs givenName, familyName, birthDate and countryCode: an added field is ignored and the message is accepted, while a renamed field and a retyped field both fail. The last four lines are the mapping counts from the next section.
- Validate twice. Check input against the source schema (reject what the source itself should not have sent), and check the output against the target schema before sending. A failed record goes to a dead-letter queue (a holding area for messages that could not be processed) with the reason and the original payload, so it can be fixed and replayed. Never silently drop or coerce.
- Plan for change. Treat each schema as a contract with a version. Be tolerant when reading (a tolerant reader takes the fields it needs and ignores unknown ones, so a sender adding a field breaks nobody) and strict when writing (a message you send always matches the target schema exactly). Adding an optional field is usually safe; removing, renaming, retyping or making a field required is a breaking change and needs a new mapping version running beside the old one. In the program's output, renaming
birthDatetodateOfBirthleaves the reader with nothing under the name it asks for, and sendingbirthDateas the number 19850307 instead of the text1985-03-07fails the date check. Making a field required breaks in the opposite direction: senders that never included it now have their messages rejected. Keep a set of sample messages per mapping version as automated tests, run them whenever either schema changes, and have the mapping's owner subscribed to the source and target teams' change announcements.
Canonical model versus mapping each pair directly
Count the mappings. If every one of N systems must exchange data in both directions with every other, direct mappings number N(N-1) (each direction separate); with a canonical model each system needs one mapping into it and one out of it, so 2N.
| Systems N | Direct, both directions N(N-1) | Canonical 2N |
|---|---|---|
| 2 | 2 | 4 |
| 3 | 6 | 6 |
| 4 | 12 | 8 |
| 5 | 20 | 10 |
| 6 | 30 | 12 |
| 7 | 42 | 14 |
Break-even is at three systems, because N(N-1) = 2N gives N = 3. But the table is the worst case. Real estates have only some flows. Worked example (assumed flows for one customer record): CRM to ERP, CRM to Billing, CRM to Support, ERP to Billing, ERP to Warehouse. That is 5 flows, so 5 direct mappings. With a canonical model: CRM and ERP are sources (2 mappings into canonical), and ERP, Billing, Support and Warehouse are targets (4 mappings out of canonical), so 2 + 4 = 6. Here direct mapping is cheaper (5 against 6), even with five systems. The canonical model starts to pay when flows keep being added (each new consumer costs 1 mapping, not 1 per source it needs), when a source changes often (one mapping to fix instead of one per consumer), or when many teams must agree on vocabulary anyway.
Costs of a canonical model that candidates forget: it needs an owner and a change process; it tends to become the union of every system's fields or the lowest common denominator; every message goes through two translations, which adds latency and two places to lose information. So I would commit to this rule: direct mapping (through the integration layer) while there are fewer than about three systems exchanging the same entity or the flows are one-off; introduce a canonical model for the entities that three or more systems share and that change over time (customer, product, order), keep it small (only fields at least two systems need, with an extension area for the rest), and version it like any API.
Common mistakes
- Putting the translation in every client.
- Proposing a canonical model for two systems.
- A canonical model with no owner, so it becomes whatever the last project needed.
- Coercing bad data silently instead of rejecting it with a reason.
- Treating a type or format change as non-breaking.
Running the code
Save the program as mapping_demo.py and run python mapping_demo.py (Python 3.12, standard library only).
You must deliver a new checkout service that depends on a customer's SOAP-based legacy ERP, and nobody on the team knows the ERP well. Lay out a phased integration plan: what you learn and deliver in each phase, the smallest interfaces that prove the integration, who owns what, the main risks and how you mitigate them, and how you validate end to end.
Sample Answer
The idea in plain words
When you depend on a system nobody on your team understands, the biggest risk is not the code you write but the things you do not know yet: what the operations really do, which are safe to repeat, how often the system is down, and what its data means. So the plan is to learn cheaply first, prove the integration end to end with the smallest possible interface (a walking skeleton: a thin, working path from checkout to the ERP and back that does little but runs for real), and only then build breadth. SOAP (an XML message protocol described by a WSDL file, a machine-readable list of the service's operations and message shapes) is a detail; what matters is that the ERP is an unfamiliar system of record (the authority for orders, stock and prices).
Phased plan (assumed 10 weeks: 2 + 3 + 3 + 2)
Phase 0: Discover (weeks 1 to 2).
- Learn: get the WSDL, a test or sandbox ERP, sample data, the list of operations the checkout actually needs, authentication method, maintenance windows, rate and volume limits, and a named ERP expert who answers questions within a day.
- Deliver: a one-page map of the needed operations (for example look up price and stock, create order, read order status, cancel), a recorded set of real request and reply examples, and a risk log.
- Characterisation tests (tests that pin down what the system actually does today, not what the document says): call each needed operation with good and bad input and record the replies, including fault messages. The program under "Seeing the pieces work" shows what a recording looks like.
- Exit: every needed operation called successfully once from our code against the test ERP.
Phase 1: Walking skeleton (weeks 3 to 5).
- Smallest interfaces that prove the integration: (1)
GetPrice/Stockread, (2)CreateOrderwrite in the test ERP, (3)GetOrderStatusread. Wrap them behind our own small interface inside an adapter (an anti-corruption layer: code that translates between the ERP's vocabulary and ours so ERP quirks stay out of checkout). - Build in from the start: timeouts, a unique client reference on every order (a key the checkout generates and the ERP stores, so a lost reply can be resolved by looking the order up), and logging of request ids.
- Exit: one test order goes from checkout to the test ERP and its status returns, repeatably, in a pipeline run.
Phase 2: Real checkout path (weeks 6 to 8).
- Add the rest: cancellation, partial stock, tax and price rules, error mapping, retry with backoff and jitter on reads (waits that grow after each failure, with random variation so many callers do not retry together), a stored idempotency record for writes (a saved note of each order's unique key and outcome, so a repeat returns the same result instead of creating a second order), and a reconciliation job (a scheduled comparison of checkout orders with ERP orders that lists differences).
- Run in shadow mode: for real checkouts, send orders to the ERP test system in parallel with the old process and compare results.
- Exit: shadow comparison matches on an agreed share of orders, differences explained. Example values to negotiate with the customer: at least 98 percent of orders match and every difference has a known cause.
Phase 3: Harden and launch (weeks 9 to 10).
- Load test up to the ERP's stated limits, failure drills (ERP down, slow, returns a fault mid-order), a feature flag (a setting that turns the ERP path on or off without a deploy), a runbook (step-by-step instructions for whoever is on call), alerts, then a pilot with a small share of traffic, then ramp up.
- Exit: pilot runs without unexplained mismatches for an agreed number of days (for example 10 consecutive days); rollback rehearsed.
Check of the span: 2 + 3 + 3 + 2 = 10 weeks, and every phase has an exit condition, not just an end date.
Who owns what
| Area | Owner |
|---|---|
| Checkout service and the adapter code | our team (a named tech lead) |
| ERP behaviour, data meaning, test environment, change calendar | customer's ERP owner (named person) |
| Credentials and network access | customer's security/IT with our requester |
| Business rules (prices, cancellation policy) | customer's business owner, decisions written down |
| Acceptance of end-to-end results | joint: our product owner and customer's business owner |
Write this down in week 1; most delays in these projects trace to a question with no owner.
Main risks and mitigations
| Risk | Mitigation |
|---|---|
| Documentation does not match behaviour | characterisation tests; keep recordings as regression tests |
| Create call times out and the outcome is unknown | client reference on every order; look up before any resend; never blind retry |
| Test ERP differs from production | compare configuration with the ERP owner; run shadow mode against production-like data; pilot before ramp |
| ERP maintenance windows or slowness | queue orders in checkout during windows; timeouts and a circuit breaker (stop calling a failing dependency for a while) |
| Only one person knows the ERP | pair on every phase-0 call; record decisions in a shared log |
| Data quality (duplicate customers, odd codes) | validate at the adapter, reject with reason, sample real data early |
| Scope growth | the interface list in phase 0 is the scope; additions go through the owner |
Validating end to end
- Contract tests at the adapter (tests that check the adapter still sends and understands the message shapes the ERP really uses, by replaying the recorded replies from phase 0).
- One automated scenario per business path (happy order, out of stock, cancel, ERP fault, ERP down) from checkout API to ERP status and back.
- Reconciliation: after each day, compare order counts and totals between checkout and ERP; any difference opens a ticket.
- Traces with one correlation id (an identifier passed along with the order through every system) across checkout, adapter and ERP request, so any order can be followed.
Seeing the pieces work
The program uses a simulated ERP test system (illustrative; the operations and codes are invented). It shows three things: recorded request and reply pairs from characterisation, including faults; a create call whose reply is lost, resolved by looking the order up by client reference instead of sending it again; and a shadow comparison whose exit check uses the example thresholds above and fails when a difference has no known cause.
class TestErp:
"""Simulated ERP test system (illustrative, not a real product)."""
def __init__(self):
self.orders = [] # (order id, client reference); this ERP does not dedupe on the reference
self.drop_next_reply = False
def call(self, op, req):
if op == "GetPrice":
prices = {"P-1": "12.50"}
if req["sku"] not in prices:
return {"fault": "Client", "code": "SKU_UNKNOWN"}
return {"price": prices[req["sku"]], "stock": 7}
if op == "CreateOrder":
if req["qty"] <= 0:
return {"fault": "Client", "code": "QTY_INVALID"}
oid = "A-%04d" % (len(self.orders) + 1)
self.orders.append((oid, req["clientRef"])) # every create makes a new order
if self.drop_next_reply: # order stored, reply lost
self.drop_next_reply = False
raise TimeoutError("no reply")
return {"orderId": oid, "status": "created"}
if op == "GetOrderByRef":
for oid, ref in self.orders:
if ref == req["clientRef"]:
return {"orderId": oid, "status": "created"}
return {"fault": "Client", "code": "NOT_FOUND"}
erp = TestErp()
print("-- characterisation: good and bad input, replies recorded")
recordings = []
for op, req in [("GetPrice", {"sku": "P-1"}), ("GetPrice", {"sku": "X-9"}),
("CreateOrder", {"sku": "P-1", "qty": 0, "clientRef": "r-0"})]:
reply = erp.call(op, req)
recordings.append((op, req, reply))
print(op, req, "->", reply)
print("-- skeleton: create with a client reference, survive a lost reply")
def create_order(erp, req):
try:
return erp.call("CreateOrder", req)
except TimeoutError:
found = erp.call("GetOrderByRef", {"clientRef": req["clientRef"]}) # look up before any resend
return found if "orderId" in found else erp.call("CreateOrder", req)
erp.drop_next_reply = True
print(create_order(erp, {"sku": "P-1", "qty": 2, "clientRef": "r-1"}))
print("orders held by the ERP:", len(erp.orders))
blind = TestErp() # contrast: resend at once, with no lookup
blind.drop_next_reply = True
try:
blind.call("CreateOrder", {"sku": "P-1", "qty": 2, "clientRef": "r-1"})
except TimeoutError:
blind.call("CreateOrder", {"sku": "P-1", "qty": 2, "clientRef": "r-1"})
print("blind resend instead, orders held by the ERP:", len(blind.orders))
print("-- shadow comparison")
old_total = {i: 1000 + i for i in range(1, 201)} # old process, cents
new_total = {i: v + (1 if i % 66 == 0 else 0) for i, v in old_total.items()} # ERP path: tax rounding
known_causes = {66: "tax rounding", 132: "tax rounding", 198: "tax rounding"} # triaged by hand with the ERP owner
def shadow_exit(old, new, causes):
diffs = [i for i in old if old[i] != new[i]]
unexplained = [i for i in diffs if i not in causes]
rate = (len(old) - len(diffs)) / len(old)
return rate, len(diffs), len(unexplained), rate >= 0.98 and not unexplained
rate, differing, unexplained, ok = shadow_exit(old_total, new_total, known_causes)
print("match rate:", round(rate * 100, 1), "percent; differing:", differing, "; unexplained:", unexplained)
print("exit met (example thresholds: at least 98 percent matching, 0 unexplained):", ok)
new_total[7] += 40 # one order differs for a reason nobody has triaged
rate, differing, unexplained, ok = shadow_exit(old_total, new_total, known_causes)
print("with one untriaged difference: match rate", round(rate * 100, 1), "percent; unexplained:", unexplained, "; exit met:", ok)
Output:
-- characterisation: good and bad input, replies recorded
GetPrice {'sku': 'P-1'} -> {'price': '12.50', 'stock': 7}
GetPrice {'sku': 'X-9'} -> {'fault': 'Client', 'code': 'SKU_UNKNOWN'}
CreateOrder {'sku': 'P-1', 'qty': 0, 'clientRef': 'r-0'} -> {'fault': 'Client', 'code': 'QTY_INVALID'}
-- skeleton: create with a client reference, survive a lost reply
{'orderId': 'A-0001', 'status': 'created'}
orders held by the ERP: 1
blind resend instead, orders held by the ERP: 2
-- shadow comparison
match rate: 98.5 percent; differing: 3 ; unexplained: 0
exit met (example thresholds: at least 98 percent matching, 0 unexplained): True
with one untriaged difference: match rate 98.0 percent; unexplained: 1 ; exit met: False
The first section shows one recording per line: the operation, the request sent and the reply or fault received, which later become regression tests. The second shows the order stored in the ERP even though the reply never arrived; the adapter found it by its reference, so the ERP holds one order, not two. The simulated ERP makes a new order on every create call, so the contrast line shows what a blind resend does: two orders for one checkout. The third compares 200 orders between the old process and the ERP path: three differ by a one-cent tax rounding difference, and each is in the list of causes triaged by hand, so the match rate is 98.5 percent and the example exit check passes. When one more order differs for a reason nobody has triaged, the match rate is 98.0 percent, exactly on the 98 percent line and so still passing it, yet the exit fails because that difference has no known cause: the percentage alone would not have caught it.
Common mistakes
- Building the whole checkout first and integrating last.
- Trusting the WSDL as the full truth.
- No named ERP contact.
- Retrying order creation without a way to detect that it already exists.
Running the code
Save the program as erp_demo.py and run python erp_demo.py (Python 3.12, standard library only).
A marketplace platform needs to integrate with thousands of merchant point-of-sale systems: receive orders, keep menus and item availability in sync, and push order status back. Some POS systems are modern and some are legacy with no inbound connectivity. Design the integration approach, including how you choose between push and pull per merchant, authentication, idempotency and error handling.
Sample Answer
The idea in plain words
A marketplace sits between customers and thousands of merchants. Each merchant runs a point-of-sale (POS) system, the till software that holds the menu, stock and orders. The marketplace must send orders to the POS, keep menus and item availability in step, and get order status back. The key insight is that modern and legacy merchants differ in one thing above all: whether the marketplace can reach the POS. If it can, push to it. If it cannot, the POS side must reach out, so the marketplace holds work for pick-up. Everything else (authentication, idempotency, errors) is designed once and applied through an adapter per merchant type.
Design
1. One internal model, many adapters. The marketplace core speaks one order model. Each merchant is attached through an adapter (a translator for one POS type or integration style) that converts to and from that POS's format. The core never contains POS-specific code. Each merchant has a stored integration profile (the record of how that merchant is connected): type, capabilities, credentials, polling or push settings, health.
2. Choose push or pull per merchant, by capability.
| Merchant type | Orders to merchant | Status/menu from merchant |
|---|---|---|
| Modern POS with an API and a reachable endpoint | push: marketplace calls the POS API | POS pushes webhooks (HTTP callbacks) to the marketplace |
| Modern POS, no inbound access but outbound HTTPS | pull: POS or an on-site agent polls the marketplace | agent posts updates |
| Legacy POS, no inbound connectivity | on-site agent or tablet app polls and acknowledges | agent reads the POS (file, database or screen export) and uploads |
| Legacy, nothing installable | fallback: tablet app where staff accept orders manually, and phone confirmation for outages | manual |
Rule: prefer push when the merchant is reachable and has a stable API, because it is faster and cheaper; use pull for everyone else. Probe at onboarding and record the choice; allow switching without changing the core.
Polling load, with assumed numbers. Suppose 5,000 merchants and 20 percent are pull-only: 1,000 agents. One poll every 5 seconds is 1 / 5 = 0.2 polls per second per agent, so 1,000 agents x 0.2 = 200 requests per second even when nothing happens. Long polling (the request is held open until an order exists or 30 seconds pass) cuts the idle rate to 1,000 / 30 = about 33 requests per second, and an order is delivered the moment it arrives. Use jittered reconnects so agents do not all reconnect together.
3. Order delivery as a lifecycle with acknowledgement. States: created, sent, acknowledged (merchant accepted), preparing, ready, completed, rejected, timed_out. For pull merchants the order waits in that merchant's outbox (a per-merchant holding queue of messages waiting to be fetched) until it is fetched and acknowledged. A timer matters: if no acknowledgement arrives within a set time (assume 90 seconds), the marketplace retries delivery, then marks timed_out, tells the customer, and escalates (alert the merchant by another channel, pause the merchant's listing). Timeline for the assumed 90 seconds, with attempts spaced evenly for clarity (real retries use backoff with jitter inside the same deadline): attempt 1 at 0 s, retry at 30 s, retry at 60 s, timed_out and customer notice at 90 s. The last block of output below prints this timeline. An order the merchant never accepted must not stay pending forever.
4. Menus and availability. Menu sync is the more frequent, more error-prone flow. For modern POS: webhooks on change plus a nightly full sync to heal drift (state that webhooks can be lost). For legacy: the agent uploads a menu snapshot with a content hash (a fingerprint of the menu data: if the hash equals the last one, nothing changed and nothing needs processing); the marketplace applies only changes. Availability ("sold out") is time-sensitive: it needs a short path (event, or a short polling interval) and an expiry, so a stale "available" does not sell something that is gone. Let the merchant mark items unavailable in one tap.
5. Authentication.
- Modern API access: OAuth 2.0 client credentials (a flow in which a program, with no person involved, exchanges its client id and secret for a short-lived access token) or per-merchant API keys, scoped to that merchant only.
- Webhooks from the merchant: an HMAC signature (a keyed hash proving the sender knows a shared secret) over the raw body in a header, with a timestamp to limit replay (an attacker re-sending a captured valid message later), compared in constant time (a comparison that takes the same time wherever the values differ, so response timing leaks nothing about the signature); per-merchant secrets with rotation. The program below shows it: the timestamp and the HMAC of
timestamp.rawbodytravel in two headers (X-Webhook-TimestampandX-Webhook-Signatureare illustrative custom names; the platform defines its own), and the receiver rejects stale timestamps and signature mismatches. - Webhooks or calls from the marketplace: signed the same way so the POS can verify them.
- Agents: a per-device credential, revocable individually (mutual TLS, where both sides present certificates, or a token); a lost tablet is cut off without touching others.
- Everything checks that the merchant id in the credential matches the merchant id in the data.
6. Idempotency. Retries cause duplicates, so every state-changing message carries a stable identifier: the marketplace order id is the idempotency key when sending an order, and the POS's accept for the same id returns the same result. Status updates carry a sequence number or version so a late preparing arriving after ready is ignored. In the output below the lifecycle numbers are acknowledged 1, preparing 2, ready 3: ready (3) is applied, then a late preparing (2) is ignored because 2 is not above the stored 3, and a duplicate ready (3) is ignored for the same reason. The marketplace stores processed message ids for a window and dedupes.
7. Error handling.
- Retry with exponential backoff and full jitter, bounded by the order's acknowledgement deadline, since retrying after the customer was told it failed is harmful.
- Isolate per merchant: a separate queue and concurrency limit each, plus a circuit breaker (stop calling a failing target for a while), so one dead POS cannot use all workers.
- Dead-letter queue (a holding area for failed messages) with alerts, and replay tools.
- Merchant health score (ack rate, latency, error rate) drives automatic pausing and support outreach.
- A daily reconciliation: orders the marketplace says were completed against what the POS shows.
The program runs the signature check, the sequence rule, the polling arithmetic and the acknowledgement timeline. Illustrative values throughout.
import hashlib
import hmac
import json
SECRET = b"merchant-42-shared-secret" # illustrative value
def sign(ts, raw):
return hmac.new(SECRET, str(ts).encode() + b"." + raw, hashlib.sha256).hexdigest()
def verify(headers, raw, now, window=300):
ts = int(headers["X-Webhook-Timestamp"])
if abs(now - ts) > window:
return "reject: timestamp outside the window (possible replay)"
if not hmac.compare_digest(sign(ts, raw), headers["X-Webhook-Signature"]):
return "reject: signature does not match"
return "accept"
raw = b'{"orderId":"O-901","status":"ready","seq":3}'
ts = 1_800_000_000
headers = {"X-Webhook-Timestamp": str(ts), "X-Webhook-Signature": sign(ts, raw)}
print("headers:", headers)
print("on time:", verify(headers, raw, now=ts + 10))
print("replayed 10 min later:", verify(headers, raw, now=ts + 600))
print("one byte changed:", verify(headers, raw.replace(b"ready", b"readx"), now=ts + 10))
reserialised = json.dumps(json.loads(raw)).encode() # same data, different bytes
print("re-serialised JSON:", verify(headers, reserialised, now=ts + 10))
state = {}
def apply(msg):
have = state.get(msg["orderId"], {"seq": 0})["seq"]
if msg["seq"] <= have:
return f"ignored {msg['status']} (seq {msg['seq']} <= stored {have})"
state[msg["orderId"]] = {"status": msg["status"], "seq": msg["seq"]}
return f"applied {msg['status']} (seq {msg['seq']})"
arrivals = [("acknowledged", 1), ("ready", 3), ("preparing", 2), ("ready", 3)]
for status, seq in arrivals:
print(apply({"orderId": "O-901", "status": status, "seq": seq}))
print("final:", state["O-901"])
print("1 poll per 5 s per agent =", 1 / 5, "polls/s; x 1000 agents =", round(1000 / 5), "requests/s")
print("long poll held 30 s:", round(1000 / 30, 1), "requests/s")
ack_deadline = 90
events = [(0, "send order (attempt 1)"), (30, "no ack: retry (attempt 2)"),
(60, "no ack: retry (attempt 3)"),
(ack_deadline, "no ack: mark timed_out, tell customer, alert merchant by phone, pause listing")]
for t, what in events:
print(f"t={t:>3} s {what}")
Output:
headers: {'X-Webhook-Timestamp': '1800000000', 'X-Webhook-Signature': 'f4c3981453055f9a21315227ffae1e8bf43c18a4c3da9acb90b80337b53c9c25'}
on time: accept
replayed 10 min later: reject: timestamp outside the window (possible replay)
one byte changed: reject: signature does not match
re-serialised JSON: reject: signature does not match
applied acknowledged (seq 1)
applied ready (seq 3)
ignored preparing (seq 2 <= stored 3)
ignored ready (seq 3 <= stored 3)
final: {'status': 'ready', 'seq': 3}
1 poll per 5 s per agent = 0.2 polls/s; x 1000 agents = 200 requests/s
long poll held 30 s: 33.3 requests/s
t= 0 s send order (attempt 1)
t= 30 s no ack: retry (attempt 2)
t= 60 s no ack: retry (attempt 3)
t= 90 s no ack: mark timed_out, tell customer, alert merchant by phone, pause listing
Read it in four groups. Headers: the two values a sender would attach. The four verification lines: an on-time message is accepted, the same message replayed 10 minutes later falls outside the 300 second window, a single changed byte fails, and so does the same data re-serialised with different spacing, which is why the HMAC is computed over the raw bytes received. Sequence lines: applied, applied, ignored, ignored, ending at ready with sequence 3. The last lines: 200 requests per second for 5 second polling, about 33 for 30 second long polling, and the timeline.
Recommendation
Commit to the one-model, adapters, push-when-possible, pull-with-long-poll-otherwise design, with acknowledgement deadlines and per-merchant isolation. What flips it: if almost every merchant is legacy, build the agent first and treat push as the special case; if volume per merchant is tiny, polling every 15 to 30 seconds is simpler than long polling.
Common mistakes
- Assuming every POS can receive a callback.
- Polling every few seconds from thousands of agents without long polling or jitter.
- Retrying past the point the customer was told the order failed.
- No sequence number on status updates.
- One shared queue where a single failing merchant uses up the workers and the other merchants get none.
Running the code
Save the program as pos_demo.py and run python pos_demo.py (Python 3.12, standard library only).
Unlock Full Question Bank
Get access to all 15 Enterprise Application Integration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.