All articles
E-commerceNovember 1, 2026 6 min read

Debouncing the Shopify Cart: How We Fixed a Storefront That Lost Items at Checkout

A war story about a Shopify storefront that quietly dropped line items under load, why the Cart Ajax API was the villain, and the debounce pattern we now ship by default.

A client pinged us on a Tuesday morning with a sentence no e-commerce engineer wants to read: "Customers are checking out with fewer items than they added." Not a pricing bug, not a tax bug — items were literally missing from the cart at the payment step. The culprit turned out to be a race condition in the Shopify Ajax Cart API that nobody on the team had thought to defend against, because the storefront "worked fine" in every manual test.

This is the breakdown of how we found it, why it happens on almost every custom Shopify theme we audit, and the debounce + queue pattern we now install by default.

The symptom: carts that silently shrink

The store sold bundles — think "build your own 6-pack" where a shopper clicks six variants in quick succession. On desktop with fast connections, everything looked fine. On mid-range Android devices over 4G, roughly one in twelve carts arrived at checkout with 4 or 5 items instead of 6. No error toast. No console error. The cart drawer showed the right count for a split second, then quietly corrected itself.

Support had been refunding the difference for weeks before anyone escalated it as an engineering issue. The merchant assumed shoppers were changing their minds.

Why manual QA missed it

When a human clicks "Add to cart" six times, there's a 300–800ms gap between clicks. When a motivated shopper on a bundle builder taps six tiles in a flow, the gap can collapse to 40–120ms. That's well inside the window where overlapping POST /cart/add.js requests start stepping on each other.

What's actually happening inside Shopify's Ajax Cart

Shopify's Cart API is stateful but not transactional in the way most engineers assume. Every mutation — /cart/add.js, /cart/change.js, /cart/update.js — reads the current cart, applies a change, and writes a new state. There is no built-in optimistic locking at the storefront layer. If two requests land close enough together, the second can be computed against a stale snapshot and overwrite the first.

The failure mode we saw looked roughly like this:

  1. Shopper taps variant A. Theme fires POST /cart/add.js with A.
  2. ~60ms later, shopper taps variant B. Theme fires POST /cart/add.js with B.
  3. Both requests reach Shopify. Request B's write lands after A's, which is fine.
  4. The theme's drawer then fires GET /cart.js to refresh UI — but it fires it after the first add.js response resolves, not after the second.
  5. The drawer renders a cart snapshot that reflects only A, caches it in a local store, and a later interaction (quantity bump, note update) writes that stale snapshot back via /cart/update.js, clobbering B.

The root cause isn't Shopify — it's the theme code assuming requests resolve in the order they were fired, and that the local JS cart state is the source of truth. Under network jitter, neither assumption holds.

Reproducing it reliably

Before fixing anything, we needed a repro. Chrome DevTools' network throttling isn't aggressive enough; the "Slow 3G" preset is too uniform. We used the following approach:

// Inject into the page to simulate jittery network for cart endpoints
const originalFetch = window.fetch;
window.fetch = async (url, opts) => {
  if (typeof url === 'string' && url.includes('/cart/')) {
    const jitter = 200 + Math.random() * 1500;
    await new Promise(r => setTimeout(r, jitter));
  }
  return originalFetch(url, opts);
};

With that in place, clicking the bundle builder quickly reproduced the drop in under a minute. If you can't reproduce a race condition on demand, you can't verify a fix.

The fix: a serialized mutation queue

The pattern that worked is boring and old: a single-flight queue that serializes all cart mutations and treats the server response as the only source of truth. No optimistic UI writes to a local store that the next mutation reads from.

class CartQueue {
  constructor() {
    this.chain = Promise.resolve();
    this.latestCart = null;
    this.subscribers = new Set();
  }

  enqueue(mutationFn) {
    const run = this.chain.then(async () => {
      const response = await mutationFn();
      // Always re-fetch canonical cart after a mutation
      const cart = await fetch('/cart.js').then(r => r.json());
      this.latestCart = cart;
      this.subscribers.forEach(fn => fn(cart));
      return { response, cart };
    });
    // Keep the chain alive even if one step rejects
    this.chain = run.catch(() => {});
    return run;
  }

  subscribe(fn) {
    this.subscribers.add(fn);
    return () => this.subscribers.delete(fn);
  }
}

const cartQueue = new CartQueue();

export function addToCart(items) {
  return cartQueue.enqueue(() =>
    fetch('/cart/add.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ items })
    }).then(r => r.json())
  );
}

Two rules make this work:

  • Every mutation goes through enqueue. Add, change, update, clear. No exceptions, no "this one's quick, we'll just call fetch directly."
  • After every mutation, re-fetch /cart.js and treat that as the canonical state. Yes, it's an extra round trip. Yes, it's worth it.

Debouncing high-frequency inputs

The queue solves correctness. Debouncing solves cost. If a shopper hammers a quantity stepper from 1 to 8, you don't want eight /cart/change.js calls — you want one. Pair the queue with a per-line-item debouncer:

const debouncers = new Map();

export function setQuantity(lineKey, quantity) {
  clearTimeout(debouncers.get(lineKey));
  const t = setTimeout(() => {
    cartQueue.enqueue(() =>
      fetch('/cart/change.js', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: lineKey, quantity })
      }).then(r => r.json())
    );
    debouncers.delete(lineKey);
  }, 250);
  debouncers.set(lineKey, t);
}

250ms is our default. Below ~150ms you're not really debouncing; above ~400ms the UI feels sluggish on the stepper.

Edge cases we hit in production

Cart drawer opening mid-mutation

When the drawer opens, most themes fire /cart.js to render. If a mutation is in flight, the drawer renders the pre-mutation state and then flickers. Fix: have the drawer subscribe to cartQueue instead of fetching directly.

Shopify's sections rendering API

If you're using sections on the cart endpoints to re-render the drawer in one round trip, the same race applies — and the HTML you get back can be stale relative to what the next queued mutation needs. We still re-fetch /cart.js after and reconcile. The extra request is 2–5kb; the correctness is non-negotiable.

Discount codes and cart attributes

/cart/update.js can modify attributes and notes alongside line items. In older theme code we found attribute updates firing in parallel with line-item updates and clobbering them. Route everything — attributes, notes, discount application — through the same queue.

Multiple tabs

Shopify's cart is session-scoped on the server, so two tabs share one cart. The queue only serializes within a tab. For stores where multi-tab usage is common (B2B portals especially), broadcast cart updates via BroadcastChannel and have each tab refetch on receipt.

How we verified the fix

We left the fetch-jitter shim in place and ran a scripted test that fired 20 add-to-cart calls with random 20–150ms gaps, repeated 100 times. Before the fix: average final cart contained ~17.2 items. After the fix: 20.0, every run. In production, the merchant's support tickets about "missing items" went to zero within a week, and checkout-step completion on the bundle builder ticked up noticeably — we won't quote a specific percentage because the sample window was short and there were other changes in flight.

Where we'd start on your storefront

If you run a custom or heavily-modified Shopify theme, do three things this week:

  1. Grep your theme for direct fetch('/cart/ calls. Every one of them is a potential race. Count them. If it's more than one call site per mutation type, you have a problem.
  2. Add the jitter shim in a staging session and try to break your own cart with fast clicks on PDPs, bundle builders, upsell modals, and quantity steppers. If anything drops or duplicates, you've found your bug.
  3. Introduce a single queue module and migrate call sites to it one at a time. Don't try to rewrite the cart in a day; the queue is additive and safe to roll out behind a feature flag.

If you'd rather have someone else do the archaeology, this is the kind of work our team does on Shopify engagements — audit, fix, and leave the client with a storefront that behaves the same at 40ms as it does at 400ms. Race conditions don't show up in Lighthouse scores, but they show up in refund tickets, and those are the ones that quietly eat margin.

#Shopify#CRO#Frontend#Performance

Want a team like ours?

72Technologies builds production software for the kind of teams who actually read this blog.

Start a project