Skip to content

Cart, Checkout & Concurrency Locks ​

Introduction ​

During high-volume traffic events (such as flash sales, Black Friday, or product drops), thousands of concurrent shoppers may attempt to purchase the same inventory item simultaneously. Without strict concurrency guards, standard database queries result in Race Conditions and overselling inventory beyond physical warehouse stock.

Reyhan Commerce implements an enterprise Two-Tier Concurrency & Locking Architecture that guarantees zero inventory overselling while maintaining sub-millisecond response times.


The Two-Tier Concurrency Architecture ​

Tier 1: Redis Sorted Set Stock Reservations ​

When a customer proceeds to checkout, Reyhan executes an atomic Lua script that creates a temporary reservation in a Redis Sorted Set (ZSET).

  • Member: reservationId:quantity
  • Score: Expiration timestamp (Unix timestamp + 15 minutes)
  • Self-Purging: Expired reservation entries are automatically purged during every reservation check without leaving ghost locks.

Tier 2: PostgreSQL Pessimistic Row Locking ​

When the payment gateway returns a verified payment callback, the VerifyPaymentAction enters a database transaction and applies a pessimistic row lock:

php
DB::transaction(function () use ($order) {
    foreach ($order->items as $item) {
        /** @var \Reyhan\Core\Models\ProductVariant $variant */
        $variant = ProductVariant::query()
            ->lockForUpdate()
            ->findOrFail($item->variant_id);

        if ($variant->stock < $item->quantity) {
            throw new InsufficientStockException('Physical stock deficit detected.');
        }

        $variant->decrement('stock', $item->quantity);
    }

    $order->markAsProcessing();
});

Shopping Cart Management ​

Guest to Authenticated Synchronization ​

Reyhan supports seamless guest browsing. When a guest customer authenticates via OTP SMS, the client application issues a synchronization request to merge guest session items into the authenticated account:

http
POST /api/v1/cart/sync
Content-Type: application/json
Authorization: Bearer <sanctum_token>

{
  "items": [
    { "variant_id": 42, "quantity": 2 }
  ]
}

Reyhan merges item quantities, verifies current stock availability, re-evaluates promotional discounts, and returns the updated cart.


The Order Lifecycle & State Machine ​

Orders transition through a strictly guarded lifecycle powered by PHP 8.4 Backed Enums:

php
namespace Reyhan\Core\Enums\Order;

enum OrderStatus: string
{
    case PendingPayment = 'pending_payment';
    case Processing     = 'processing';
    case Shipped        = 'shipped';
    case Delivered      = 'delivered';
    case Cancelled      = 'cancelled';
    case Refunded       = 'refunded';
}
TransitionAllowed FromTriggered By
ProcessingPendingPaymentBank payment verification webhook or admin manual approval
ShippedProcessingWarehouse barcode scan and shipping label dispatch
DeliveredShippedCarrier API delivery confirmation or customer confirmation
CancelledPendingPayment, ProcessingPayment timeout (15m) or customer cancellation
RefundedProcessing, DeliveredStaff refund via Ledger service

Testing Concurrency & Stock Locks ​

You can assert concurrency protection in Pest 4:

php
<?php

declare(strict_types=1);

use Reyhan\Core\Exceptions\InsufficientStockException;
use Reyhan\Core\Facades\Inventory;
use Reyhan\Core\Models\ProductVariant;

it('prevents overselling when stock is depleted', function () {
    $variant = ProductVariant::factory()->create(['stock' => 1]);

    // Reserve only available item
    $firstReserve = Inventory::reserve($variant->id, 1, 'order-1', 900);
    expect($firstReserve)->toBeTrue();

    // Second customer attempts to reserve
    $secondReserve = Inventory::reserve($variant->id, 1, 'order-2', 900);
    expect($secondReserve)->toBeFalse();
});

Released under the MIT License.