Skip to content
Allen Jones

Back to blog

How to Build a Shopping Cart System That Handles Real-World Checkout Problems

Allen Jones.

Posted on Oct 11, 2026

Adding products to a shopping cart is easy. You store the product ID, quantity, and price in the browser, display the total, and send everything to checkout.

That works until two customers try to buy the last available item. Or someone clicks Pay twice. Or a payment succeeds after the inventory reservation has expired. Or a customer returns to their cart after a week, and the product's price has changed.

These are the kinds of problems that turn a simple shopping cart into a much more interesting backend engineering problem.

I ran into them while building Shoprivet, an ecommerce platform where merchants can sell products through hosted storefronts, embeddable widgets, or their own websites using a REST API.

Initially, the cart lived entirely in the browser. It worked, and for a simple storefront, that approach is perfectly reasonable. But as I added more ways for merchants to sell, I needed something more reliable: one cart backend that could serve different storefront experiences, validate prices and inventory, and integrate with checkout and payment processing.

I built the new system using NestJS, Prisma, PostgreSQL, and TypeScript.

The interesting part wasn't creating a Cart table or writing an endpoint to add products. It was deciding who should be trusted, what happens when requests arrive concurrently, and how to recover when a payment doesn't go according to plan.

Here's how I approached it, including the tradeoffs and failure scenarios worth understanding if you're building something similar.

The Problem With a Browser-Only Cart

A common shopping cart implementation starts with localStorage.

const cart = JSON.parse(
  localStorage.getItem("cart") || "[]"
);

function addToCart(product) {
  const existing = cart.find(
    (item) => item.id === product.id
  );

  if (existing) {
    existing.quantity += 1;
  } else {
    cart.push({
      id: product.id,
      name: product.name,
      price: product.price,
      quantity: 1,
    });
  }

  localStorage.setItem("cart", JSON.stringify(cart));
}

Nothing is inherently wrong with this code. For a small application or prototype, it gets the job done.

The browser remembers the cart after a refresh, the customer can update quantities, and you don't need a database request every time someone clicks Add to Cart.

But there are some important limitations.

First, localStorage belongs to a particular browser origin. A cart stored on shop.example.com isn't automatically available on another-example.com.

Second, anything stored in the browser can be modified by the customer. That includes the price.

Third, the browser doesn't know whether a product is still available. A customer might add a product today, return next week, and discover that the merchant has changed its price or removed it entirely.

And finally, a browser-only cart doesn't solve checkout concurrency. It can remember what someone wants to buy, but it cannot guarantee that the product will still be available when they pay.

Here's an example of why trusting browser cart data is dangerous.

{
  "productId": "product_123",
  "quantity": 2,
  "price": 10
}

Suppose the product actually costs €100.

If the checkout endpoint accepts that JSON and calculates the order using the submitted price, a customer can modify the request and potentially pay €20 instead of €200.

The browser is controlled by the customer. It should never be the authority on how much the customer owes.

That gives us our first rule:

The browser can tell the server what the customer wants to buy. The server must decide what those products cost and whether they can be purchased.

Designing the Cart Architecture

Shoprivet supports three ways to sell products:

  1. A hosted storefront on a Shoprivet subdomain or merchant custom domain.
  2. An embeddable catalogue or cart widget on an external website.
  3. A custom storefront built by a developer using the public REST API.

I didn't want three different implementations of product pricing, inventory validation, and checkout.

That would mean fixing the same bug three times, potentially with different results.

Instead, I wanted every selling experience to communicate with one Cart API.

flowchart TD
    A["Hosted storefront"] --> D["Cart API"]
    B["Embedded widget"] --> D
    C["Custom storefront"] --> D

    D --> E["Cart Service"]
    E --> F[("PostgreSQL")]

    E --> G["Checkout Service"]
    G --> H["Orders + Inventory"]
    H --> I["Payment Provider"]
    I --> J["Payment Verification"]

The storefronts are different, but the business rules are the same.

A product that costs €50 should cost €50 whether the customer buys it through a hosted storefront, an embedded widget, or a custom React application.

The same applies to product availability, variants, stock, and checkout validation.

This is one of the advantages of designing a backend around reusable business capabilities rather than individual frontend screens.

Step 1: Store Carts in PostgreSQL

The first decision was how to represent a cart in the database.

At a minimum, we need two models:

  • Cart, representing the shopping session.
  • CartItem, representing a product and quantity within that cart.

Here's a simplified Prisma example. It illustrates the relationship rather than reproducing every field from Shoprivet's implementation.

model Cart {
  id         String     @id @default(cuid())
  storeId    String
  tokenHash  String     @unique
  status     CartStatus @default(ACTIVE)
  expiresAt  DateTime
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt

  items      CartItem[]

  @@index([storeId])
  @@index([expiresAt])
}

model CartItem {
  id        String   @id @default(cuid())
  cartId    String
  productId String
  variantId String?
  lineKey   String
  quantity  Int
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  cart      Cart     @relation(
    fields: [cartId],
    references: [id],
    onDelete: Cascade
  )

  @@unique([cartId, lineKey])
}

enum CartStatus {
  ACTIVE
  COMPLETED
  REVOKED
  EXPIRED
}

The relationship looks like this:

erDiagram
    STORE ||--o{ CART : owns
    CART ||--o{ CART_ITEM : contains
    PRODUCT ||--o{ CART_ITEM : referenced_by
    PRODUCT_VARIANT ||--o{ CART_ITEM : selected_by

    CART {
        string id PK
        string storeId FK
        string tokenHash
        string status
        datetime expiresAt
    }

    CART_ITEM {
        string id PK
        string cartId FK
        string productId FK
        string variantId FK
        string lineKey
        int quantity
    }

One cart can contain multiple items. Each item references a product, and optionally a particular variant.

For example, a customer might add:

Product Variant Quantity
T-shirt Black, Medium 2
T-shirt Black, Large 1
Sneakers Size 42 1

Even though the first two rows reference the same product, they're different cart lines because their selected variants differ.

That's why simply enforcing uniqueness on cartId and productId isn't enough.

The cart needs a stable way to distinguish different selections. A canonical line key can represent the product, variant, and relevant selected options.

Another important decision: I didn't make the cart's stored price authoritative.

The product database remains the source of truth.

If a merchant changes a product's price from €40 to €45, the cart should reflect the current price rather than blindly trusting a value saved days earlier.

Historical order prices are different. Once an order is created, its line items need appropriate price snapshots so the transaction can be understood later, even if the merchant changes the catalogue.

A cart represents purchasing intent. An order represents a transaction.

Those are different responsibilities.

Step 2: Let Customers Have Carts Without Creating Accounts

One requirement was that customers shouldn't need to register or log in just to buy something.

Guest checkout removes a step from the buying process, but it introduces an authentication question:

How does the server know which cart belongs to a returning guest?

The simplest approach might be to expose a cart ID:

GET /api/carts/cart_123

But a cart ID alone shouldn't grant access.

If identifiers are predictable, leaked, or exposed in logs, another person might be able to retrieve or modify someone else's cart.

Instead, I used a separate high-entropy guest credential.

In Node.js, generating a random credential looks like this:

import { randomBytes, createHash } from "node:crypto";

const token = randomBytes(32).toString("hex");

const tokenHash = createHash("sha256")
  .update(token)
  .digest("hex");

randomBytes(32) generates 256 bits of randomness.

The raw token is given to the customer as a credential. Only its hash is stored in the database.

Later, when the customer makes another request, the backend hashes the supplied token and looks up the matching cart.

Customer
   |
   | Guest cart token
   v
Cart API
   |
   | SHA-256
   v
Token hash
   |
   | Database lookup
   v
Matching cart

This means the database doesn't need to store the raw credential.

Hashing doesn't make a stolen browser token harmless. Anyone holding a valid Bearer token can still use it until it expires or is revoked. But storing only the hash reduces the exposure of usable credentials if the database contents are leaked.

I also made credentials store-scoped.

A token for Store A cannot be used to access Store B's cart, even though both stores use the same backend.

That matters in a multi-tenant SaaS. Tenant isolation isn't something you can enforce only in the frontend.

Step 3: HTTP-Only Cookies or Bearer Tokens?

This was one of the more interesting decisions because Shoprivet supports both hosted storefronts and external websites.

A common recommendation for browser authentication is to use HTTP-only cookies.

That's sensible, but it doesn't automatically work for every deployment architecture.

Consider these storefronts:

fashion.shoprivet.io

www.merchant.com

merchant.webflow.io

The first storefront is on a Shoprivet subdomain. The others may be completely unrelated domains.

A cookie issued for api.shoprivet.io doesn't magically become a first-party cookie on www.merchant.com.

Modern browsers also restrict third-party cookies, so relying on them for embedded widgets would be fragile.

I ended up supporting two credential transports.

Hosted storefronts: HTTP-only cookies

For hosted storefronts where cart requests can use the storefront's own origin, the backend issues a cookie.

In production, the cookie uses a configuration like:

Set-Cookie: __Host-shoprivet-cart=<token>; Path=/; Secure; HttpOnly; SameSite=Lax

The important attributes are:

  • HttpOnly prevents frontend JavaScript from reading the cookie.
  • Secure restricts transmission to HTTPS.
  • SameSite=Lax provides some cross-site request protection.
  • Path=/ makes the cookie available across the storefront.
  • No Domain attribute keeps it host-only.

For cookie-authenticated mutations, I also require an appropriate request header and validate the request origin.

That's important because SameSite alone shouldn't be the entire CSRF defense.

The hosted storefront can then call a same-origin route:

await fetch("/api/public/stores/my-shop/carts", {
  method: "POST",
  credentials: "same-origin",
  headers: {
    "Content-Type": "application/json",
    "X-Shoprivet-Cart-Request": "1",
  },
});

The browser sends the cookie automatically on subsequent same-origin requests.

Frontend JavaScript doesn't need to read or store the raw credential.

For custom domains, this depends on the proxy routing cart requests through the storefront's origin and preserving the host information needed for store validation.

That routing requirement matters just as much as the cookie configuration.

Embedded widgets: Bearer credentials

Now imagine a merchant embeds a Shoprivet catalogue on a WordPress website.

The widget is running on a third-party origin.

Instead of depending on cookies, it can use the guest Bearer credential.

const response = await fetch(
  `${API_URL}/public/stores/${storeSlug}/carts`,
  {
    headers: {
      Authorization: `Bearer ${cartToken}`,
    },
    credentials: "omit",
  }
);

The widget can save its guest token in browser storage, using a key scoped to the store.

For example:

const storageKey = `shoprivet_cart_token_${storeId}`;

localStorage.setItem(storageKey, cartToken);

This has a tradeoff.

Unlike an HTTP-only cookie, a token in localStorage can be read by JavaScript running on the embedding website.

If that website has an XSS vulnerability or loads a malicious script, the token could be stolen.

That's why the guest credential must have limited privileges. It should only access the appropriate guest cart, not merchant administration, payment secrets, or unrelated customer data.

The widget also needs a fallback when browser storage is unavailable. An in-memory cart session can still work during the current page visit, even if it won't survive a browser restart.

The lesson here is that authentication design depends on where the application actually runs.

There's no universal cookie configuration that solves every cross-domain embedding problem.

Step 4: Keep Prices and Inventory on the Server

Once the cart is persisted, the next question is what the API should accept from the frontend.

A reasonable add-to-cart request contains something like:

{
  "productId": "product_123",
  "variantId": "variant_black_medium",
  "quantity": 2
}

Notice what's missing.

There's no price.

There's no subtotal.

There's no total.

The server looks up the product and variant, checks that they belong to the requested store, validates the selection, and calculates the current price.

A simplified flow looks like this:

async function addItem(input: AddCartItemInput) {
  const product = await productRepository.findById(
    input.productId
  );

  if (!product) {
    throw new Error("Product not found");
  }

  if (product.storeId !== input.storeId) {
    throw new Error("Product unavailable");
  }

  if (product.status !== "ACTIVE") {
    throw new Error("Product unavailable");
  }

  // Validate selected variant and options.
  // Validate quantity and stock.
  // Insert or update the cart line transactionally.
}

The real implementation needs more validation than this example, particularly around variants, options, and concurrent updates.

But the principle is straightforward: the API accepts identifiers and quantities, not financial authority.

When retrieving a cart, the server calculates totals using current product data.

Suppose a customer adds two shirts at €25 each.

2 × €25 = €50

Tomorrow, the merchant changes the price to €30.

The current cart total becomes:

2 × €30 = €60

The UI should communicate the change where appropriate, rather than silently displaying the old total.

For money calculations, another consideration is floating-point precision.

JavaScript numbers are binary floating-point values. Calculations such as 0.1 + 0.2 can produce surprising results.

A safer long-term approach is to use integer minor units or an appropriate decimal representation, with currency-aware rounding.

For example, €19.99 can be represented as 1,999 cents.

But changing monetary storage in an existing ecommerce system is a separate migration that requires careful consideration of historical orders, currency rules, and payment provider expectations.

I wouldn't casually mix that change into an unrelated cart migration.

Step 5: What Happens When Two Customers Buy the Last Item?

This is where a shopping cart becomes a concurrency problem.

Imagine a merchant has one laptop remaining.

Two customers open the storefront at almost the same time.

Both see:

Laptop
Price: €800
Available stock: 1

Customer A clicks Checkout.

Customer B clicks Checkout a few milliseconds later.

A naive implementation might do this:

const product = await prisma.product.findUnique({
  where: { id: productId },
});

if (product.stock >= quantity) {
  await prisma.product.update({
    where: { id: productId },
    data: {
      stock: product.stock - quantity,
    },
  });
}

It looks reasonable.

Check the stock. If there's enough, subtract the quantity.

But the problem is that checking and updating happen as separate operations.

Both requests might read stock = 1 before either update completes.

sequenceDiagram
    participant A as Customer A
    participant B as Customer B
    participant DB as Database

    A->>DB: Read stock
    DB-->>A: 1 available

    B->>DB: Read stock
    DB-->>B: 1 available

    A->>DB: Update stock to 0
    B->>DB: Update stock to 0

    Note over DB: Both requests may think they succeeded

Depending on the implementation, both customers could receive successful orders even though only one laptop exists.

This is a race condition.

The fix is to make the stock check and deduction atomic.

With PostgreSQL, a conditional update can do that in one statement:

UPDATE products
SET stock = stock - 1
WHERE id = $1
  AND stock >= 1
RETURNING id, stock;

If the update returns one row, the deduction succeeded.

If it returns no rows, there wasn't enough stock at the moment the database attempted the update.

In Prisma, a similar approach can use updateMany:

const result = await tx.product.updateMany({
  where: {
    id: productId,
    stock: {
      gte: quantity,
    },
  },
  data: {
    stock: {
      decrement: quantity,
    },
  },
});

if (result.count !== 1) {
  throw new Error("Insufficient stock");
}

The database performs the conditional update atomically.

Only a request that satisfies the stock condition can decrement it.

In a real checkout, this operation belongs inside a transaction that also records the corresponding order and inventory reservation.

If the transaction fails, its changes should roll back together.

Product variants make this more interesting

Suppose a merchant sells a shirt with three sizes.

Variant Available stock
Small 10
Medium 1
Large 5

The product might have 16 units across all variants, but that doesn't mean 16 medium shirts are available.

If the customer selects Medium, the system must validate and reserve stock for the Medium variant.

Checking only the product-level stock would be incorrect.

This is why variant identity needs to survive the entire journey:

Product selection
      ↓
Cart item
      ↓
Checkout validation
      ↓
Inventory reservation
      ↓
Order item

Losing the selected variant at any point can produce incorrect inventory deductions or fulfillment information.

Step 6: Why I Added Inventory Reservations

Atomic stock deduction solves one problem: two customers purchasing more units than are available.

But it introduces another question.

When should inventory actually be deducted?

Suppose a customer clicks Pay, and the backend creates an order.

The customer is redirected to a payment provider but never completes payment.

If the system permanently deducts stock when the order is created, that product can remain unavailable even though nobody paid for it.

For a merchant with limited inventory, abandoned payments could prevent legitimate customers from buying.

A better approach is to distinguish between reserved inventory and committed inventory.

The lifecycle looks something like this:

flowchart TD
    A["Checkout requested"] --> B{"Stock available?"}
    B -->|No| C["Reject checkout"]
    B -->|Yes| D["Reserve stock"]
    D --> E["Create pending order"]
    E --> F["Start payment"]
    F --> G{"Payment outcome"}
    G -->|Verified success| H["Commit reservation"]
    G -->|Failed or cancelled| I["Release reservation"]
    G -->|No result| J["Reservation expires"]
    J --> K["Release stock safely"]

One implementation strategy is to deduct available stock when the reservation is created and record the reservation separately.

That way, other checkouts cannot purchase the same unit.

If payment succeeds, the reservation becomes committed.

If payment fails or expires, the system releases the reserved quantity back into available stock.

The important part is that releasing stock must also be idempotent.

If two workers try to release the same reservation, stock must not be incremented twice.

A reservation record can have a status such as:

ACTIVE
COMMITTED
RELEASED
EXPIRED

A database transaction can conditionally transition the reservation from ACTIVE to RELEASED and restore inventory only when that transition succeeds.

Why an expiration timestamp isn't enough

You might store:

expiresAt = 2026-10-10T18:30:00Z

But the database won't automatically run your inventory-release business logic just because that time has passed.

Something needs to process expired reservations.

That could be a scheduled job, a background worker, or another reliable cleanup mechanism.

It also needs to work safely if multiple application instances run the cleanup simultaneously.

A timestamp tells you when something should expire.

It doesn't perform the cleanup.

What about cash on delivery?

Cash on delivery is different from an online payment.

A COD order can be legitimately accepted even though no payment has been collected yet.

You wouldn't want a generic "release all unpaid reservations after 15 minutes" job to restore inventory for every accepted COD order.

The reservation lifecycle has to consider the actual payment method and order status.

This is one reason payment and inventory logic shouldn't be scattered across individual frontend checkout implementations.

Step 7: What If Someone Clicks Pay Twice?

Here's another problem that looks harmless until it affects real transactions.

A customer fills in their checkout details and clicks Pay.

The request takes three seconds.

They don't see an immediate response, so they click again.

Now the backend receives two checkout requests.

sequenceDiagram
    participant Browser
    participant API
    participant DB

    Browser->>API: POST /checkout
    Browser->>API: POST /checkout again

    API->>DB: Create order
    DB-->>API: Order A

    API->>DB: Create another order
    DB-->>API: Order B

    Note over DB: One customer, two orders

Disabling the button in the frontend helps, but it doesn't solve the underlying problem.

Requests can be retried by browsers, mobile networks, proxies, or client applications.

A customer can also open two tabs.

The backend needs to recognize when two requests represent the same logical checkout attempt.

This is where idempotency comes in.

What idempotency means

An operation is idempotent when repeating it has the same intended effect as performing it once.

For checkout, that means retrying the same logical request shouldn't create another order.

A common approach is to generate an idempotency key:

const idempotencyKey = crypto.randomUUID();

The frontend sends it with the checkout request.

POST /api/public/stores/my-shop/checkout
Idempotency-Key: 1e6f6c39-91a7-4dd0-a23e-41e8e3d908a7

The backend associates that key with the checkout operation.

If the same request arrives again, it can return the existing result rather than creating another order.

But there's an important detail.

An idempotency key must be enforced by the database, not just checked in application memory.

Consider this code:

const existing = await findCheckoutByKey(key);

if (!existing) {
  await createOrder();
}

It still has a race condition.

Two concurrent requests can both check for the key before either inserts it.

Both see that it doesn't exist.

Both create orders.

A unique database constraint is one part of the solution.

model CheckoutAttempt {
  id             String   @id @default(cuid())
  storeId        String
  idempotencyKey String
  requestHash    String
  orderId        String?
  status         String
  createdAt      DateTime @default(now())

  @@unique([storeId, idempotencyKey])
}

This is a simplified conceptual model. A real implementation also needs to account for cart identity, attempt state, and concurrent processing.

The database constraint prevents two records from claiming the same scoped key.

The checkout transaction then needs to coordinate the idempotency record, order creation, and inventory reservation.

What if the same key is used with different details?

Imagine the first request contains:

{
  "paymentMethod": "stripe",
  "email": "customer@example.com"
}

Then another request arrives using the same key but a different payment method or different checkout details.

The backend shouldn't blindly return an unrelated previous result.

That's why it's useful to associate the key with a canonical request fingerprint.

Same key, same logical request: return or recover the existing attempt.

Same key, different request: reject the conflict.

What if payment initialization fails?

This is another subtle case.

Suppose the backend successfully creates the order but fails while contacting the payment provider.

If the customer retries, you don't want a completely new order.

You want to recover the existing checkout attempt and safely retry or reconcile payment initialization.

That requires thinking about order creation and payment initialization as separate stages.

Database transactions cannot make a remote payment provider participate atomically in your PostgreSQL transaction.

The application has to handle the gap between them.

Step 8: Payment Webhooks Can Arrive More Than Once

A successful payment redirect doesn't necessarily prove that a customer paid.

The customer could close the page, lose connectivity, or manipulate the URL.

For online payments, the backend should rely on the provider's supported verification mechanisms.

Often, that includes webhooks.

A webhook is an HTTP request sent by the payment provider to your backend when a payment event occurs.

For example:

Payment provider
       |
       | Payment succeeded
       v
POST /payment/webhook
       |
       v
Verify provider signature
       |
       v
Find the matching order
       |
       v
Confirm payment state
       |
       v
Update order and inventory

The problem is that webhook delivery is not necessarily exactly once.

A provider may retry delivery when your server responds slowly or encounters an error.

Your backend could receive the same payment-success event twice.

If the webhook handler blindly executes fulfillment logic every time, you might:

  • Mark an order paid multiple times.
  • Send duplicate fulfillment notifications.
  • Release or deduct inventory incorrectly.
  • Trigger duplicate digital product delivery.

The handler needs to be idempotent.

A simplified pattern is:

await prisma.$transaction(async (tx) => {
  const result = await tx.order.updateMany({
    where: {
      id: orderId,
      paymentStatus: "PENDING",
    },
    data: {
      paymentStatus: "PAID",
    },
  });

  if (result.count !== 1) {
    return;
  }

  // Record the successful transition.
  // Commit the corresponding inventory reservation.
  // Persist any fulfillment work that must happen once.
});

The important part isn't the exact code. It's the conditional state transition.

Only the request that successfully changes the order from the expected previous state should perform the corresponding one-time database effects.

For external side effects such as sending emails or delivering digital products, a durable outbox or equivalent mechanism may be needed to prevent work from being lost between database commit and external delivery.

You also need to verify the webhook signature and match the provider's payment reference, amount, currency, and order association as appropriate.

Idempotency doesn't replace payment verification.

Both are necessary.

Step 9: What If Payment Succeeds After the Reservation Expires?

This is one of the scenarios I found particularly interesting.

Imagine this sequence:

  1. A customer checks out the last available laptop.
  2. The system reserves the laptop.
  3. The customer starts an online payment.
  4. The reservation expires before payment confirmation arrives.
  5. The system releases the laptop back into available stock.
  6. Another customer buys it.
  7. The original payment provider finally reports that the first customer paid.

Now you have a successful payment but potentially no inventory available to fulfill the order.

You cannot simply mark the first order as ready for fulfillment.

And you cannot ignore the payment.

This is why I introduced a payment-review path for late payment outcomes.

The system needs to preserve evidence that the payment succeeded while recognizing that the original inventory reservation is no longer valid.

sequenceDiagram
    participant Customer
    participant API
    participant Inventory
    participant Provider

    Customer->>API: Start checkout
    API->>Inventory: Reserve last item
    API->>Provider: Initialize payment

    Note over API,Inventory: Reservation expires

    API->>Inventory: Release reservation
    Provider-->>API: Late payment success

    API->>API: Flag payment for review
    Note over API: Do not silently fulfill

The eventual resolution might involve confirming replacement stock, arranging fulfillment, or issuing a refund through the provider's supported process.

The important architectural lesson is that payment success and fulfillment readiness aren't always the same thing.

A payment system needs to account for events arriving late or out of order.

This is also why inventory reservation periods should be chosen with the actual payment provider's behavior in mind.

A short reservation timeout might work for one payment method and be completely unsuitable for another.

Step 10: Migrating Existing Carts Without Losing Customer Data

When I moved Shoprivet from browser-only carts to server-managed carts, I couldn't simply delete the old implementation and start fresh.

Some customers might already have products saved in localStorage.

The old format used store-scoped keys similar to:

shoprivet_cart_my-store

The new storefront needed to recognize those existing carts and import their items into PostgreSQL.

At first, the migration sounds straightforward:

  1. Read the old cart.
  2. Send its items to the API.
  3. Delete the old data.

But there's a failure scenario hidden in step two.

Suppose the API successfully imports the cart, but the browser loses connectivity before receiving the response.

The customer refreshes.

The browser still has the legacy cart because it never received confirmation.

If it sends the same items again, the server could double the quantities.

A customer who originally wanted two shirts might now have four.

That's why I added a transactional, idempotent import mechanism.

The backend records whether the legacy import has already been completed for that cart.

If the same import is retried, it doesn't blindly add the quantities again.

The browser removes the old data only after receiving confirmation that the import completed.

The migration also revalidates products, variants, quantities, and current prices.

It doesn't trust the old browser-stored price.

This is a good example of a feature that looks like a simple data migration but becomes a distributed systems problem once network failures and retries are involved.

Step 11: Sharing One Cart Across Multiple Widgets

Embedded widgets introduced another interesting challenge.

Imagine a merchant adds two Shoprivet catalogue widgets to the same WordPress page.

One displays clothing.

The other displays accessories.

Both belong to the same store.

If each widget creates and manages its own cart independently, the customer could end up with two different cart states.

They add a shirt in the first widget, but the second widget's cart drawer doesn't know about it.

I wanted widgets belonging to the same store to share cart state.

A useful approach is a client-side cart manager keyed by store identity.

const cartManagers = new Map<string, CartManager>();

function getCartManager(storeId: string) {
  let manager = cartManagers.get(storeId);

  if (!manager) {
    manager = createCartManager(storeId);
    cartManagers.set(storeId, manager);
  }

  return manager;
}

This is a simplified illustration of the pattern.

Widgets from the same store use the same manager.

Widgets from different stores use separate managers.

That shared manager can coordinate:

  • Cart creation and restoration.
  • Product additions.
  • Quantity updates.
  • Cart totals.
  • Loading states.
  • Error handling.
  • Checkout state.

It can also prevent duplicate cart creation when multiple widgets initialize at almost the same time.

For multiple browser tabs, you can use browser synchronization mechanisms such as BroadcastChannel to notify other tabs that cart state has changed.

But you shouldn't broadcast raw guest credentials.

A notification that says "the cart changed, refresh your state" is usually safer than sending the credential or copying entire authoritative cart responses between unrelated components.

The server remains the source of truth.

Step 12: Keeping the Old Checkout API Working

Another decision was backward compatibility.

Shoprivet already had a checkout endpoint that accepted product IDs, quantities, and selected options.

The new cart-based checkout could simply replace it, but that would risk breaking existing embedded widgets or developer integrations.

Instead, I preserved the legacy item-based checkout route while introducing the new cart-based flow.

The difference is where the authoritative items come from.

Legacy checkout

Client submits item identifiers and quantities
                 |
                 v
Backend validates products and current prices
                 |
                 v
Order creation

Cart-based checkout

Client submits checkout details
                 |
                 v
Backend authenticates guest cart
                 |
                 v
Backend reads cart items from PostgreSQL
                 |
                 v
Backend validates products and current prices
                 |
                 v
Order creation

Both paths should share the same underlying product validation, inventory safety, and payment rules.

The legacy endpoint must never trust client-submitted prices just because it accepts item lists.

Backward compatibility doesn't mean preserving unsafe behavior.

It means keeping the documented interface working while enforcing the same backend guarantees.

This matters particularly for developer tools.

When other developers build on your API, changing a request contract can break applications you don't control.

A migration strategy is part of API design.

The Full Checkout Lifecycle

After connecting the pieces, the intended lifecycle looks like this:

flowchart TD
    A["Customer adds product"] --> B["Server-managed cart"]
    B --> C["Checkout request"]
    C --> D["Authenticate cart"]
    D --> E["Validate products, variants and prices"]
    E --> F{"Inventory available?"}

    F -->|No| G["Return availability error"]
    F -->|Yes| H["Create idempotent checkout attempt"]

    H --> I["Create order and reserve inventory"]
    I --> J{"Payment method"}

    J -->|Online payment| K["Initialize provider payment"]
    J -->|Cash on delivery| L["Accept COD order"]

    K --> M{"Verified payment outcome"}
    M -->|Success| N["Commit reservation"]
    M -->|Failure| O["Release or recover reservation"]
    M -->|Late success| P["Payment review"]

    N --> Q["Complete order and cart"]
    L --> Q

The diagram looks more complicated than a basic Add to Cart implementation.

But each additional step exists because something can go wrong in the real world.

Customers retry requests.

Networks fail.

Payment providers send duplicate callbacks.

Inventory changes.

Browsers close.

Merchants update prices.

And different websites need to interact with the same backend.

A reliable system has to define what happens in those situations, not just what happens when everything works perfectly.

What I'd Test Before Calling This Production-Ready

Building the architecture is only part of the work.

The next step is proving that it behaves correctly under realistic conditions.

Here are some of the scenarios I consider important:

Scenario Expected behavior
Two customers buy the last item Only one checkout reserves the stock
Customer clicks Pay twice No duplicate order
Browser retries checkout Same logical checkout attempt is recovered
Product price changes Server uses current authoritative pricing
Product variant becomes unavailable Checkout rejects the unavailable selection
Payment fails Inventory is released or the order remains safely recoverable
Payment webhook arrives twice No duplicate payment-side effects
Payment succeeds after reservation expiry Order enters a safe reconciliation path
Customer refreshes the storefront Guest cart is restored
Two widgets belong to one store Both share the same cart
Widgets belong to different stores Credentials and carts remain isolated
Legacy cart import is retried Quantities aren't duplicated
Customer uses a custom domain Cookie and API routing respect the verified storefront host

Unit tests are useful, but they're not enough for some of these scenarios.

For example, a mocked stock repository might confirm that a function calls updateMany correctly. It doesn't necessarily prove that two real PostgreSQL transactions cannot oversell the last unit.

That requires concurrency testing against a database.

Payment integrations also need provider-specific test-mode verification.

In Shoprivet's case, the cart and checkout implementation has passed targeted builds and tests, but the final production-readiness audit, database migration verification, and some live integration scenarios are still outstanding.

I think it's important to make that distinction.

An implementation isn't production-verified just because the code compiles.

What Building This Taught Me

There are a few lessons I took away from designing this system.

1. The frontend should manage the experience, not financial truth

The frontend decides how to display a cart, when to show a loading indicator, and how to communicate errors.

The backend decides whether a product can be purchased, how much it costs, and whether stock can be reserved.

Keeping that boundary clear prevents a whole category of bugs.

2. Database constraints are part of application correctness

Application-level checks are useful, but they aren't enough when requests arrive concurrently.

Unique constraints, conditional updates, and transactions provide guarantees that an in-memory check cannot.

If two requests can both pass your validation before either writes to the database, you probably need to rethink where that validation happens.

3. Idempotency matters beyond payment APIs

It's easy to associate idempotency only with Stripe or other payment providers.

But the same principle applies to cart migrations, inventory release, order creation, and webhook processing.

Any operation that might be retried should have a clearly defined retry behavior.

4. One backend can support multiple selling experiences

Hosted storefronts, embedded widgets, and custom developer storefronts don't need separate pricing and inventory implementations.

They need appropriate authentication and client integrations around shared backend rules.

That reduces duplicated logic and makes future improvements easier to maintain.

5. Failure handling is part of the feature

A checkout flow isn't complete just because the happy path works.

What happens when payment initialization succeeds but the response is lost?

What happens when a reservation expires?

What happens when the provider sends the same webhook twice?

What happens when a payment succeeds after stock has been released?

Those questions are part of the system design, not edge cases to think about after launch.

Takeaway

A shopping cart starts as a simple collection of product IDs and quantities.

But once you introduce real payments, inventory, multiple storefronts, guest sessions, and external developers, it becomes a system that needs to coordinate state across browsers, databases, and payment providers.

The most important decisions aren't about which frontend state library to use or how to render the cart drawer.

They're about where authority lives, how concurrent requests are handled, how operations can be retried safely, and how the system recovers when something fails.

That's what I focused on while building the server-managed cart architecture for Shoprivet.

The broader lesson applies well beyond ecommerce: when software starts handling real business transactions, correctness and recovery become just as important as functionality.