Imagine an online store with a beautiful product page. A shopper clicks Buy Now. It feels like one action.
Behind the monitor, imagine a factory staffed by hundreds of tiny, overworked gnomes. One checks stock. Another calls a bank. Another argues with customs. One is trying to print a shipping label; another is shouting that the food batch has been recalled. The security gnome suspects the coupon is fraudulent. The tax gnome wants to know where the buyer lives. And a very nervous gnome is asking whether the payment actually went through.
The customer sees a spinner.
An online purchase is not a button. It is a promise coordinated across organizations that do not share a database, a clock, a legal system, or even a definition of success.
In 2026, AI can generate the storefront in hours. It cannot make the supply chain, financial ledger, product law, or incident response disappear.
Scope: Global patterns, with examples from the EU, US, Latin America, and cross-border trade. Laws differ by product, seller location, buyer destination, fulfillment route, and business model. This is an engineering and business primer, not jurisdiction-specific legal advice. The stories below are illustrative scenarios, not documented incidents.
1. Your product chooses your architecture
Two shops may use the same checkout and have radically different businesses.
| What you sell | The hidden difficulty | What software must remember |
|---|---|---|
| Fashion | Size exchanges, seasonal stock, returns | Variant-level SKUs, reservations, reverse logistics |
| Electronics | Serial numbers, warranties, batteries, recalls | Unit traceability, RMA, restricted shipping |
| Packaged food | Allergens, expiry, imported ingredients | Lots, FEFO, labeling, quarantine, recall |
| Refrigerated food | Time and temperature | Cold-chain events, delivery windows, spoilage |
| Cosmetics | Ingredients and market-specific rules | Claims, registration or notification where required |
| Digital goods | Fraud, licenses, territorial rights | Entitlements, activation, revocation |
| Marketplace | Many sellers, one customer payment | Seller onboarding, commissions, settlement ledger |
| Subscriptions | Renewals, cancellations, payment failures | Mandates, billing cycles, dunning, consent |
Scene: The T-shirt that existed but could not be sold. A warehouse has 80 shirts. The site confidently displays “In stock.” Unfortunately, all 80 are size XL, while the buyer wants M. The inventory count is correct; the domain model is wrong.
The first lesson is not about databases. It is about understanding what a sellable unit actually means.
2. A product can be physically present and legally unsellable
Picture a merchant sourcing specialty coffee from one country and selling it in another. The cartons arrive. The website is ready. But importing, storing, labeling, and selling are distinct permissions and obligations.
In the United States, the FDA explains that food importers are responsible for compliant, safe, properly labeled food, and relevant facilities and shipments may face registration, prior-notice, verification, and inspection requirements. FDA does not simply “pre-approve” every food importer or product. FDA guidance.
In the European Union, the General Product Safety Regulation applies to many non-food consumer products sold online and offline, while food has its own extensive legal framework. The GPSR has applied since December 2024. EU Council overview.
In Latin America, sanitary registration or authorization, labeling, importer responsibilities, invoicing, and consumer rules vary by country. A product approved for one market is not automatically approved for another.
Therefore quantity > 0 is not a safe definition of availability:
Physical inventory
├─ in transit
├─ received, pending inspection
├─ quarantined / recalled
├─ legally cleared, available
├─ reserved for orders
├─ picked / dispatched
└─ expired / damaged
For food, keep lotId, expiry, allergens, supplier, storage conditions, and the connection between shipped lots and customers. FEFO (first-expiring, first-out) can matter more than FIFO (first-in, first-out).
Scene: The recall email. A supplier reports contamination in lot K-482. The business needs to identify which customers received it. If fulfillment only recorded the product SKU, not the shipped lot, the team may know what was sold but not to whom the risky units went.
This is why compliance changes the data model, not just the terms-and-conditions page.
3. Cross-border e-commerce: the border is part of checkout
Suppose a seller in São Paulo ships to Berlin, New York, and Mexico City. The same product can have different duties, indirect taxes, labeling requirements, returns expectations, and restrictions at each destination.
A global commerce model must distinguish:
- Seller of record: Who contracts with the buyer?
- Importer of record: Who is responsible for import formalities?
- Merchant of record: Who accepts payment and assumes associated obligations?
- Incoterms / delivery terms: Who bears shipping costs and risks at each stage?
- Tax jurisdiction: Where does VAT, GST, sales tax, or a similar obligation arise?
- Product jurisdiction: Is this item legally marketable at the destination?
These roles can overlap, but they are not interchangeable.
The EU's OSS/IOSS mechanisms simplify certain cross-border VAT reporting. In September 2026 the European Commission reported more than €125 billion collected through its e-commerce VAT schemes over five years. European Commission.
The EU also introduced major 2026 customs changes affecting low-value e-commerce imports, with additional reforms scheduled later. A price engine that assumes last year's import threshold can become a financial liability. EU customs reform.
In the US, sales-tax obligations depend on states and nexus rules; marketplaces may have facilitator responsibilities. Across the world, tax and customs rules must be modeled as versioned, jurisdiction-dependent policies, not a single hardcoded percentage.
Scene: Free shipping wasn't free. The store offers a global flat rate. A heavy parcel crosses a customs threshold and requires special handling. The conversion dashboard celebrates; the margin dashboard quietly catches fire.
4. Revenue is not margin, and a payment is not cash
Consider a hypothetical $100 order. The seller might owe consumption tax, pay for the item, fund shipping, pay a payment processor, acquire the customer through ads, and later handle a return. The merchant may not receive settlement until days after the order.
Contribution per order ≈
net sales revenue (excluding applicable pass-through taxes)
− landed product cost
− payment and platform fees
− packaging and fulfillment
− shipping subsidy
− expected refunds / returns / fraud losses
− attributable acquisition cost
This is contribution, not accounting profit. Fixed overhead, financing, income taxes, and other items remain.
The CFO cares about cash conversion; marketing watches CAC and conversion; operations watches stockouts and returns; engineering watches checkout reliability. These metrics describe the same system from different angles.
Scene: The record-breaking loss. A company doubles sales with aggressive discounts and free returns. Revenue rises; contribution falls. The software did exactly what it was told. The commercial assumptions were the bug.
5. The cart is a wish; the order is a commitment
The words cart, quote, order, payment, shipment, and refund describe different states and responsibilities.
sequenceDiagram
actor Customer
participant Checkout
participant Stock as Inventory
participant PSP as Payment provider
participant Orders
participant Warehouse
Customer->>Checkout: Buy
Checkout->>Stock: Reserve units (with expiry)
Stock-->>Checkout: Reservation confirmed
Checkout->>Orders: Create pending order
Checkout->>PSP: Create payment attempt
PSP-->>Customer: Hosted payment flow
PSP-->>Checkout: Signed webhook
Checkout->>PSP: Verify payment status
Checkout->>Orders: Confirm once (idempotent)
Orders->>Warehouse: Release for fulfillment
The customer's browser returning to a success page is not proof of payment. The backend must verify authoritative payment status, amount, currency, and order identity. See OWASP payment integration guidance.
Scene: The spinner that cost $200. A customer clicks Pay twice. The first response times out; the bank approved the charge. The second click creates another charge. You now have two payment attempts, one intended purchase, and a support ticket.
Use idempotency keys, durable operation records, uniqueness constraints, and reconciliation. Exactly-once delivery is not something you should casually assume from an HTTP request or message broker.
6. The last item: where concurrency becomes customer service
Two customers simultaneously buy the final pair of shoes. Both browsers previously read available = 1.
Naively reading, then decrementing, allows overselling. A reservation should be atomic, constrained by available stock, and expire if checkout is abandoned. The exact mechanism might be a conditional SQL update, locking, or a dedicated inventory service.
But physical stock is messier than database stock: a warehouse worker can damage an item, a shop can sell it offline, or a return can be unsellable. A robust model distinguishes on-hand, reserved, allocated, damaged, and available-to-promise quantities.
The interesting design question is not “Can Redis make this faster?” It is “Which system is authoritative, and how does it recover when reality disagrees?”
7. Sagas: a distributed transaction is a business story
A saga coordinates multiple local transactions when one atomic database transaction cannot cover the whole workflow. A coordinator may orchestrate the steps, or services may react to events. Both approaches trade simplicity for flexibility and require careful state management. Microsoft's saga pattern.
Scene: The order that cannot be un-shipped. The customer pays, the warehouse dispatches, and then the seller learns the item was recalled. You cannot roll back a truck with ROLLBACK;. You need a new process: stop delivery if possible, contact the customer, arrange a return or recall, refund appropriately, and preserve the audit trail.
A refund is not the inverse of history. It is a new financial event. A shipment recall is not an inverse SQL operation. Compensation is a domain action, sometimes requiring humans.
| Failure | Sensible recovery |
|---|---|
| Stock reservation fails | Do not initiate payment; explain unavailability |
| Payment definitively declined | Release reservation and close attempt |
| Payment outcome unknown | Query provider, wait for verified events, reconcile |
| Shipment creation fails after payment | Retry safely, change carrier, or initiate exception workflow |
| Product recalled after dispatch | Trace affected shipments, initiate recall and customer response |
Don't introduce a saga because the architecture diagram looks impressive. Introduce it when real transactional boundaries and business recovery requirements justify the complexity.
8. Circuit breakers protect services, not business truth
A timeout bounds waiting. Retries with exponential backoff and jitter help with transient failures. A circuit breaker stops hammering an unhealthy dependency. A bulkhead limits how much of your system one failing dependency can consume.
None of these patterns can tell you whether an ambiguous card charge actually succeeded.
Combine resilience mechanisms with verified webhooks, deduplication, transactional outbox where needed, dead-letter handling, audit trails, and reconciliation. OWASP emphasizes signature verification, replay protection, idempotent handlers, and safe treatment of out-of-order events. Webhook Security Cheat Sheet.
Scene: The helpful retry storm. A shipping API slows down. Every worker retries immediately. Traffic multiplies, the provider slows further, and unrelated checkouts begin to time out. The system wasn't attacked; it attacked itself.
9. Security means defending commercial invariants
TLS and authentication are the beginning, not the end. Think about:
- Price tampering: the browser must never define the authoritative total.
- Broken object-level authorization: customer A must not see customer B's orders or addresses.
- Coupon abuse: promotions need transactional eligibility and redemption limits.
- Webhook forgery/replay: external notifications need verified provenance and idempotent effects.
- Credential stuffing: rate limiting, bot defenses, and appropriate MFA.
- Sensitive data: minimize collection, control retention, encrypt appropriately, and restrict access.
- Card data: hosted/tokenized payment flows can reduce PCI DSS exposure, but integration and compliance scope still require assessment.
Privacy requirements differ internationally: GDPR in the EU, a patchwork of federal/state rules in the US, LGPD in Brazil, and other national frameworks. Design for consent or other lawful bases where relevant, data subject rights, retention, breach response, and cross-border transfers—not just a cookie banner.
10. Consumer protection and returns are product features
A returns policy is not just a paragraph in the footer. It requires eligibility rules, labels, warehouse inspection, replacement or refund decisions, inventory disposition, tax adjustments, and support communication.
The EU has distance-selling consumer protections and platform obligations; the US has a different mix of federal and state consumer rules; other countries have their own withdrawal, warranty, and refund frameworks. European Commission e-commerce overview.
Scene: The refund button that does nothing. Support marks an order REFUNDED. Finance sees no corresponding processor transaction. The customer sees no money. A status label is not a financial operation.
Model requested, approved, submitted, settled, and failed refund states when the provider supports those distinctions. Reconcile against the payment processor and settlement records.
11. Marketplaces are not just stores with more products
A marketplace introduces multiple parties: buyer, seller, platform, payment provider, carrier, and sometimes tax authorities. The platform may need identity verification, seller eligibility checks, payout schedules, reserves, dispute management, and a ledger that explains who owns each cent.
Scene: One order, three sellers. A buyer pays $120 for items from three merchants. One cancels, one ships late, and one disputes a fee. A single orders.total field cannot explain the resulting refunds, commissions, shipping adjustments, and payouts.
This is where double-entry-style financial ledgers, explicit obligations, and durable event histories become valuable. A database table called transactions is not automatically an accounting system.
12. Build or buy? The AI-era trap
In 2026, AI-assisted development can generate a storefront, cart, admin panel, and integration scaffolding quickly. It cannot validate supplier reliability, write your return policy for every market, own the on-call rotation, or prove that your ledger reconciles.
For many businesses, Shopify, WooCommerce, or another maintained commerce platform is a better starting point than a custom distributed system. Build differentiated components when the business genuinely requires unusual inventory, pricing, fulfillment, marketplace settlement, or integrations.
| Stage | Default posture | Reason to evolve |
|---|---|---|
| Test demand | Hosted platform and proven payment integrations | Need evidence that anyone wants the product |
| Operational complexity | Modular monolith, relational DB, background jobs | Workflows exceed platform capabilities |
| Multiple independent domains | Selective services, messaging, sagas, tracing | Independent ownership and scaling justify overhead |
| Global platform | Regional compliance, multi-warehouse, ledger, governance | Organization and business complexity demand it |
There is no magic customer-count threshold for microservices. Complexity is earned by the problem, not awarded by traffic forecasts.
13. What should a healthy commerce system measure?
| Signal | Why it matters |
|---|---|
| Checkout conversion and abandonment | Commercial friction |
| p95 checkout/payment latency | Repeated clicks and failed conversions |
| Oversell / reservation conflicts | Broken promises |
| Paid but unconfirmed orders | Financial and customer risk |
| Unreconciled settlements | Cash and accounting uncertainty |
| Orders past promised dispatch date | Fulfillment quality |
| Return rate and contribution margin | Actual unit economics |
| Recall traceability coverage | Ability to protect customers |
Correlate cartId, quoteId, orderId, paymentAttemptId, shipmentId, and, where relevant, lotId. Logs must avoid unnecessary personal and payment data.
14. The tabletop exercise that reveals the architecture
Try this with engineering, finance, operations, and support:
A customer in Germany buys the last two bags of imported coffee from a cross-border seller. The payment provider times out but later confirms the charge. The webhook arrives twice. The warehouse then quarantines the lot. A tax document has been issued. The customer demands a refund. Who owns the decision, which systems must change, and what evidence proves that the customer got their money back?
A good answer names authoritative states, legal and operational responsibilities, idempotency, compensation, reconciliation, customer communication, and a human owner. “We use Kafka” is not an answer.
Closing: the real product begins after Pay
An online purchase is a promise made by a business and implemented through software. That promise has to survive imperfect data, failed dependencies, customs borders, product restrictions, accounting realities, and human mistakes.
The cheerful Buy Now button is easy to draw. The gnomes behind the screen are doing the real work.
Primary sources and further reading
- European Commission — e-commerce rules
- EU Council — General Product Safety Regulation
- European Commission — EU VAT e-commerce schemes, September 2026
- European Commission — EU customs reform
- FDA — Importing food into the United States
- WTO — E-commerce agreement implementation discussions
- Microsoft — Saga design pattern
- OWASP — Third-party payment gateway integration
- OWASP — Webhook security
All scenes are fictional examples designed to illustrate recurring business and engineering failure modes.