DEV Community

Cover image for 4 Hard E-Commerce Engineering Problems We Solved Building a Self-Hosted Laravel Commerce Core
Mahadi Hasan
Mahadi Hasan

Posted on AI-assisted

4 Hard E-Commerce Engineering Problems We Solved Building a Self-Hosted Laravel Commerce Core

When growing DTC brands decide to leave Shopify or WooCommerce, engineering teams usually hit an uncomfortable choice:

  1. Plugin-heavy stacks (like WooCommerce or legacy Magento) where every checkout tweak feels like defusing a bomb.
  2. Barebones headless frameworks where you spend four months rebuilding basic commerce plumbing—tax invoices, multi-warehouse stock, returns, store credit, and product feeds—before taking a single order.

While building Knarra (a self-hosted Laravel e-commerce platform designed as a zero-app-tax alternative to Shopify), we ran into the same four engineering traps that quietly break custom e-commerce builds in production.

Here’s how we solved each one in Laravel—and the architectural patterns you can reuse in your own commerce projects.


1. Never Touch Floats for Money (Especially Across 32+ Currencies)

The fastest way to break reconciliation with Stripe, PayPal, or an accounting team is storing prices as float or doing percentage discount math directly on decimals.

Even DECIMAL(10,2) trips teams up once you support international stores:

  • USD / GBP / AUD / EUR use 2 decimal places (100 minor units).
  • JPY / KRW use 0 decimal places.
  • KWD / BHD use 3 decimal places.

Instead of hardcoding * 100 everywhere, we store monetary values as exact integers in minor units alongside the ISO-4217 currency code and run every cart subtotal, BOGO rule, tax zone calculation, and partial refund through brick/money:

use Brick\Money\Money;
use Brick\Math\RoundingMode;

// $49.95 stored as integer 4995 in minor units
$unitPrice = Money::ofMinor($variant->price_minor, $cart->currency);
$lineTotal = $unitPrice->multipliedBy($qty);

// Apply a 15% coupon with deterministic half-up rounding
$discount = $lineTotal->multipliedBy('0.15', RoundingMode::HALF_UP);
$finalTotal = $lineTotal->minus($discount);
Enter fullscreen mode Exit fullscreen mode

Why this matters in production:

  • Partial refunds + line-item tax calculations always sum back to the exact Stripe payment intent amount—no off-by-one-cent webhook mismatches.
  • Store credit ledgers stay immutable and auditable down to the exact minor unit per currency.

2. Atomic Stock Reservations (So Ghost Checkouts Don’t Freeze Inventory)

A classic e-commerce race condition: you have 1 unit left in your main warehouse, and two shoppers hit checkout at the same second.

  • If you only deduct stock after Stripe’s webhook fires, you oversell.
  • If you deduct stock as soon as someone enters checkout without an expiry mechanism, abandoned checkouts silently lock up your inventory until a staff member manually fixes it.

Our solution uses two pieces working together:

  1. Pessimistic row locking (lockForUpdate()) inside a DB transaction when creating a pending checkout reservation across warehouses:
DB::transaction(function () use ($warehouseId, $variantId, $qty, $order) {
    $stock = WarehouseStock::where('warehouse_id', $warehouseId)
        ->where('variant_id', $variantId)
        ->lockForUpdate()
        ->firstOrFail();

    $available = $stock->on_hand - $stock->reserved;

    if ($available < $qty) {
        throw new InsufficientStockException("Only {$available} left in stock.");
    }

    $stock->increment('reserved', $qty);

    StockReservation::create([
        'order_id'     => $order->id,
        'warehouse_id' => $warehouseId,
        'variant_id'   => $variantId,
        'quantity'     => $qty,
        'expires_at'   => now()->addMinutes(20),
    ]);
});
Enter fullscreen mode Exit fullscreen mode
  1. An hourly self-healing scheduler (orders:expire-stale) that finds unpaid/abandoned reservations past expires_at, releases reserved back to available inventory inside a transaction, and logs the release in the order timeline.

No overselling during flash sales, and no ghost carts freezing stock overnight.


3. Keep Private Per-SKU COGS Strictly Out of Public API Payloads

Most DTC founders end up paying $30–$100/month for a third-party profit analytics app just to see real gross margins per SKU—because platforms don't track Cost of Goods Sold (COGS) natively on variants.

Adding cost_amount to the variant table is trivial. The subtle bug is accidentally leaking supplier cost through a headless storefront endpoint, JSON-LD block, or toArray() serialization.

In Laravel, we enforce a strict boundary:

  • Sensitive fields (cost_amount, internal staff notes, audit metadata) are never exposed on public /api/v1 API Resources—storefront endpoints use dedicated StorefrontVariantResource classes with an explicit allowlist of public keys.
  • Margin badges ((price - cost) / price) are computed exclusively in the Admin layer, while ERP/3PL integrations use scoped, revocable integration API tokens isolated from customer authentication.

4. Migrating Live Stores Without Tanking SEO or Emailing 10,000 Past Customers

When teams migrate off Shopify or WooCommerce, the code is rarely what causes panic—it’s the cutover:

  • URL changes break rankings: Shopify uses /products/{handle} and /collections/{handle}. Changing slugs without automatic 301 redirects wipes out organic traffic.
  • Hotlinked images die on cancellation: If an importer copies image URLs instead of downloading and archiving media locally, every product photo breaks the day the old Shopify store closes.
  • Historical order imports trigger email storms: Firing standard OrderCreated events while importing 2 years of past orders will email thousands of past customers.
  • Cutover gaps: Running an initial import on Monday and switching DNS on Thursday misses 3 days of live orders unless your importer supports idempotent delta re-sync.

Building a proper migration pipeline meant treating it like a state machine: Pre-flight dry run → silent historical import (events muted, live stock untouched) → local media archiving → automatic 301 redirect registration → delta re-sync right before DNS switch.


Wrapping Up

If you’re evaluating self-hosted e-commerce in the PHP/Laravel ecosystem—whether you're comparing Bagisto, Lunar, Medusa, or building a custom stack—getting money math, stock locking, API data boundaries, and migration tooling right on day one saves months of painful rewrites later.

We built all of these patterns directly into Knarra (alongside native Returns/RMA, Store Credit, Waitlists, Abandoned Cart Recovery, and live Google Shopping/Meta feeds so merchants don't pay $260–$900+/mo in Shopify apps).

If you've built custom checkout or inventory systems in Laravel, I'd love to hear how you handled stock reservations or multi-currency rounding in the comments.

Top comments (0)