Capstone: Noor’s Order Integration, Run Against Three Simulated Services
Combine the whole course: an order pipeline that asks a courier for a rate, takes a payment with an idempotency key, receives a signed webhook, and sends a confirmation email once, surviving injected failures, with every ledger checked independently.
In this lesson you will
- Orchestrate several APIs in one pipeline
- Combine retries, idempotency and signatures
- Run a scenario with injected faults
- Reconcile every ledger independently
About 28 minutes
One order, three services, many things that can go wrong
The capstone is the integration Noor wanted: when a customer places an order, the program asks the courier for the delivery price, charges the card, and sends a confirmation email, with each step surviving the failures of the earlier lessons. Three simulated services are involved. The courier is flaky: it answers 503 to the first calls of one order. The payment service is reachable but loses the reply to one charge, the double-charge trap, and declines one card. The email service delivers each message to a mailbox that the lesson can count. The pipeline uses an idempotency key for every charge, backs off on transient errors, verifies the signature on the payment webhook before it believes it, and sends the email only once per event, however many times the webhook is delivered.
The scenario then has five orders, one of which is a happy path and four of which hit a failure on purpose. Afterwards the lesson does what a careful engineer does and does not take the pipeline’s word for anything. The ledgers of the three services, which the pipeline cannot touch, are compared with the expected outcome computed separately from the scenario description: how many charges were created, how much money was collected, how many emails were sent and to whom, and how many courier calls were made. Any double charge, missing email or duplicate would show up as a number that differs.
import json, hmac, hashlib, random
# ---- simulated services: each keeps its own ledger ----
class Courier:
def __init__(self): self.calls = 0; self.fail_first = {"A-2": 2}
def rate(self, order_id, grams):
self.calls += 1
if self.fail_first.get(order_id, 0) > 0: self.fail_first[order_id] -= 1; raise ConnectionError("503")
return 450 + 12 * -(-grams // 100)
class Pay:
SECRET = b"whsec_cap"
def __init__(self): self.charges, self.by_key, self.lose_reply, self.declined = [], {}, {"A-3"}, {"A-4"}
def charge(self, order_id, key, amount):
if key in self.by_key: ch = self.by_key[key]
else:
ch = {"id": "ch_%d" % (len(self.charges) + 1), "order": order_id, "amount": amount, "ok": order_id not in self.declined}
self.charges.append(ch); self.by_key[key] = ch
if order_id in self.lose_reply: self.lose_reply.discard(order_id); raise TimeoutError("reply lost")
return ch
def webhook(self, ch, ts=1_700_000_000):
body = json.dumps({"id": "evt_" + ch["id"], "type": "payment.succeeded" if ch["ok"] else "payment.failed", "order": ch["order"]}).encode()
return body, "t=%d,v1=%s" % (ts, hmac.new(self.SECRET, ("%d." % ts).encode() + body, hashlib.sha256).hexdigest())
class Mail:
def __init__(self): self.sent = []
def send(self, to, subject): self.sent.append((to, subject))
courier, pay, mail = Courier(), Pay(), Mail()
log, sleeps, seen_events, results = [], [], set(), {}
def redact(s): return s.replace("whsec_cap", "[REDACTED]")
def retry(fn, tries=5):
for i in range(tries):
try: return fn()
except (ConnectionError, TimeoutError) as e: sleeps.append(min(8, 0.5 * 2 ** i)); log.append("retry after " + type(e).__name__)
raise RuntimeError("gave up")
def handle_webhook(body, header):
parts = dict(p.split("=", 1) for p in header.split(",")); ts = int(parts["t"])
good = hmac.new(Pay.SECRET, ("%d." % ts).encode() + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(good, parts["v1"]): return "rejected: bad signature"
ev = json.loads(body)
if ev["id"] in seen_events: return "duplicate ignored"
seen_events.add(ev["id"])
if ev["type"] == "payment.succeeded": mail.send("customer-" + ev["order"], "Order " + ev["order"] + " confirmed"); return "confirmed"
return "payment failed, customer told"
def place(order_id, grams, goods_cents):
shipping = retry(lambda: courier.rate(order_id, grams))
total = goods_cents + shipping
ch = retry(lambda: pay.charge(order_id, "key-" + order_id, total))
body, header = pay.webhook(ch)
outcome = handle_webhook(body, header)
handle_webhook(body, header) # the provider delivers every event twice
results[order_id] = (total, ch["ok"], outcome)
orders = [("A-1", 1250, 3000), ("A-2", 800, 4500), ("A-3", 300, 2000), ("A-4", 500, 1000), ("A-5", 2000, 6000)]
for o in orders: place(*o)
for k, (t, ok, out) in results.items(): print(k, "total", t, "| charged ok:", ok, "|", out)
print("courier calls:", courier.calls, "| charges on the provider:", len(pay.charges), "| collected:", sum(c["amount"] for c in pay.charges if c["ok"]), "cents")
print("emails sent:", mail.sent)
print("retries logged:", log, "| waits chosen:", sleeps)
print("log line check:", redact("secret was whsec_cap"))
print("DATA " + json.dumps({"results": results, "calls": courier.calls, "charges": len(pay.charges), "collected": sum(c["amount"] for c in pay.charges if c["ok"]), "mail": mail.sent, "sleeps": sleeps, "retries": len(log)}))
A-1 total 3606 | charged ok: True | confirmed
A-2 total 5046 | charged ok: True | confirmed
A-3 total 2486 | charged ok: True | confirmed
A-4 total 1510 | charged ok: False | payment failed, customer told
A-5 total 6690 | charged ok: True | confirmed
courier calls: 7 | charges on the provider: 5 | collected: 17828 cents
emails sent: [('customer-A-1', 'Order A-1 confirmed'), ('customer-A-2', 'Order A-2 confirmed'), ('customer-A-3', 'Order A-3 confirmed'), ('customer-A-5', 'Order A-5 confirmed')]
retries logged: ['retry after ConnectionError', 'retry after ConnectionError', 'retry after TimeoutError'] | waits chosen: [0.5, 1.0, 0.5]
log line check: secret was [REDACTED]
The five orders produced these outcomes. A-1 was the happy path: shipping for 1,250 grams is 450 + 12 x 13 = 606 cents, so with goods of 3,000 the total charged was 3,606 cents. A-2 met a courier that answered 503 twice, and the pipeline retried with waits of 0.5 and 1.0 seconds and then got the rate: the courier was called 7 times in all for five orders (5 + 2 failures). A-3 is the double-charge trap: the payment service created the charge and lost the reply, the pipeline retried with the same idempotency key, and the provider returned the existing charge. A-4 used a declined card, and A-5 was another normal order. The pipeline logged 3 retries, and its waits were [0.5, 1.0, 0.5] seconds.
The provider created exactly 5 charges for 5 orders, which means that no order was charged twice, even though one reply was lost, and the money collected on successful charges is 17,828 cents, the totals of A-1, A-2, A-3 and A-5. The email service holds 4 messages, one confirmation for each of the four paid orders and none for the declined one, although the pipeline delivered every webhook twice: the second delivery of each was recognised by its event id and ignored. The declined order generated a “payment failed” outcome and no email to confirm a payment that never happened. Signatures were verified before any of it, with the secret kept out of the log, as the line that shows the redaction demonstrates.
Independent check: the expected numbers were computed from the description of the scenario, not by the pipeline: the totals from the shipping formula, 5 charges for 5 orders because every order has one idempotency key, 7 courier calls because A-2 failed twice, and 4 emails for the 4 orders whose cards were accepted. The collected sum is the sum of those four totals, and the email list is the set of four confirmation messages. Each number comes from a ledger that belongs to a service, not from the pipeline, so a duplicate charge, a missing or duplicated email, or a skipped retry would have changed one of them.
Check by hand with A-3: 300 grams is 3 started hundreds, so shipping is 450 + 36 = 486, and with goods of 2,000 the total is 2,486. The reply was lost once, so the pipeline made two charge calls, but the provider keeps one charge because both calls carried the key “key-A-3”. The first failure for A-2 waits 0.5 seconds (attempt 0) and the second 1.0 (attempt 1).
Where to go next
- Read the documentation of a real provider in your area, courier, payments or email, and map each lesson of this course to its features: authentication, idempotency, webhooks, rate limits, test mode.
- Use the provider’s official client libraries where they exist, and keep the ideas of this course in mind: timeouts, retries, idempotency keys, signature checks and logging.
- Add monitoring: count errors, retries and latency per provider, and alert when they change.
- Practise with the free test modes of real services, never with live money.
- Take the Back-end development and Cybersecurity courses for the parts that surround an integration: the server that receives webhooks, and the threats to it.
Real providers differ in details that matter: error formats, retry policies, limits and fees. Test against the provider’s test mode, read the current documentation, and monitor in production.
Compare your records with each provider’s ledger every day, automatically. Differences are bugs, fraud or provider incidents, and finding them early is cheap.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. You have now completed the API integration course.
Practice
Add a fourth service, such as a stock system, and a compensation step that refunds the payment if the stock reservation fails. Add a daily reconciliation function that compares the shop’s orders with the payment ledger. Make the courier rate cached for an hour and test the cache.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why does one idempotency key per order matter?
- A retried charge returns the same charge
- It encrypts the charge
- It speeds up the call
- It makes emails faster
No double charge.
Why was only one email sent per paid order although every webhook arrived twice?
- Emails are limited by the provider
- The webhook was filtered
- The courier did it
- Processed event ids are remembered
Duplicates are ignored.
How were the results verified?
- By trusting the pipeline
- By reading the logs only
- Not verified
- Ledgers of the services versus numbers computed from the scenario
Independent expectations.
Why was no email sent for the declined payment?
- Emails are random
- The courier failed
- The event said payment.failed
- The log was redacted
Only confirmed payments get a confirmation.
What should a production integration add?
- More print statements
- Nothing
- Monitoring, reconciliation and provider-specific details
- Longer secrets in the code
See the list in the lesson.
Summary
- A pipeline combines retries, idempotency keys, signed webhooks and redacted logs.
- Run scenarios with injected failures.
- Reconcile every service’s ledger independently.
- Read the real provider’s documentation and test mode before going live.
Questions
Can I use this pipeline for real?
It shows the structure. For real use, take the provider's libraries and test mode, add persistence for orders and events, monitoring and security review, and follow current documentation.
What if a provider changes its API?
Contract tests against recorded responses, tolerant parsing, version pinning where the provider offers it, and a changelog subscription help you notice and adapt.
What should I learn next?
The details of one provider, a message queue for reliable background processing, and observability. Check current documentation and tools.
