Skip to content
Back to Projects
Flagship Production Case Study

KashmirStag

A production B2C e-commerce platform built from the ground up for Kashmiri crafts and local artisans.

Next.js 15 App RouterTypeScriptReact 19MongoDB AtlasMongoose 8Zod ValidationJWT (jose)bcryptjsRazorpay SDKTailwind CSSNodemailerVercel Analytics

1. Overview

KashmirStag connects Kashmiri products, artisans, and local sellers with customers through an online marketplace. The project was engineered as a serious full-stack commerce system rather than a cosmetic frontend demo, addressing complex operational requirements including atomic inventory reservations, payment idempotency, state machine transitions, and historical order resilience.

2. Why I Built It

I wanted to build a real commerce system to thoroughly understand software architecture where mistakes have tangible consequences:

  • 01.Preventing overselling under high concurrency through atomic operations.
  • 02.Handling payment webhooks that retry, arrive out of order, or fail mid-flight.
  • 03.Preserving order history integrity when products are modified or archived in the future.
  • 04.Designing an operational back-office where catalog changes propagate accurately across the system.

3. Product Architecture

The application is built on Next.js 15 App Router using React Server Components for the storefront, ensuring minimal client-side JavaScript, immediate Time-to-First-Byte, and zero layout shift.

Storefront (Next.js 15)

Server Components
React 19
Edge Middleware JWT Guard
Tailwind CSS

API Layer

REST Endpoints
Zod Input Validation
Sliding-Window Rate Limiting
HTTP-only Cookies

Service Layer (14 Services)

Inventory Service
Payment Service
Order Service
Checkout Service
Catalog Service

Data Layer

MongoDB Atlas
Mongoose 8
19 Normalized Models
Atomic Transactions

4. Commerce Architecture & Relational Flow

In KashmirStag, catalog and order relationships are strictly modeled to decouple public discovery from fulfillment:

CategoryCollectionProductProductVariant (Source of Truth)InventoryCartCheckoutOrderPayment

ProductVariant is the Source of Truth

Products act as catalog containers, while ProductVariant holds actual SKUs, pricing in integer paise, dimensions, and inventory levels.

Historical Order Line-Item Snapshots

When an order is created, complete title, SKU, variant, and price snapshots are written into the order document so future product edits or deletions never corrupt past order history.

5. Two-Phase Inventory System

Core Invariant:availableQty = onHand - reservedQty

To guarantee zero overselling during flash sales or competing checkout sessions, the inventory service implements atomic reservation semantics:

Atomic Reservation

Stock is atomically reserved upon checkout initiation using conditional database increments only if availableQty >= requestedQty.

Concurrency Protection

Verified via concurrency regression suites: exactly 1 purchaser succeeds when 10 concurrent requests compete for a single available unit.

Audit Ledger

Every reservation, release, manual adjustment, and purchase commits an immutable InventoryTransaction ledger record.

6. Payment Architecture & Webhook Idempotency

Payments are orchestrated through Razorpay with end-to-end server verification and deterministic state machine transitions:

Payment Lifecycle Pipeline:
1. Customer initiates checkout → Inventory validation & atomic stock reservation
2. Server creates Razorpay Order with integer paise precision (no float rounding errors)
3. Customer completes checkout modal in client
4. Server receives payment payload → verifies HMAC signature via crypto.timingSafeEqual
5. Webhook listener processes asynchronously with idempotency key deduplication
6. Inventory reservation commits to permanently deducted on-hand stock
7. Order transitions deterministically to CONFIRMED and sends customer receipt email

7. Security Architecture

Role-Based Access Control (RBAC)

Granular permissions restricting admin routes and mutations from customer accounts.

IDOR Protection

Strict ownership validation on customer addresses, order details, and account records.

HTTP-Only JWT Cookies

Stateless session tokens signed with jose, eliminating XSS token theft vectors.

Sliding-Window Rate Limiting

Protects authentication, search, and checkout endpoints from abuse and brute-force attacks.

Magic-Byte Validation

Inspects binary file headers on image uploads to prevent disguised executable uploads.

Path Traversal Protection

Sanitizes dynamic upload serving paths against relative traversal attacks.

Timing-Safe Payment Verification

Uses crypto.timingSafeEqual to verify Razorpay HMAC signatures, preventing timing side-channel attacks.

Centralized Error Handling

AppError class hierarchy preventing raw database error leakage to client responses.

8. Operational Back-Office Admin System

The admin system was built as an operational control center rather than a static UI shell. It directly controls:

KPI Analytics Dashboard
Product & Variant CRUD
SKU Stock Adjustments
Category Management
Collection Curator
Order Fulfillment Tracking
Customer LTV Metrics
Coupon Engine
Review Moderation
Image Magic-Byte Manager
Immutable Audit Logs
Storefront Settings

9. Data Models (19 Mongoose Schemas)

UserAddressProductProductVariantCategoryCollectionInventoryTransactionCartOrderPaymentCouponCouponUsageReviewAuditLogNotificationWishlistSettingShipmentUploadedImage

10. Verified Testing Evidence

All Verified Regression Suites Passed

Verified Workflows & Testing

  • TypeScript 0 errors, production build verified
  • 67+ routes audited and verified in production state
  • Atomic concurrency testing: exactly 1 successful purchase when competing for single stock unit
  • Two-phase inventory reservation and release lifecycle testing
  • Order state machine transition integrity tests
  • Payment idempotency and duplicate webhook suppression tests
  • Security test suite: sliding-window rate limiter, path traversal, magic-byte validation
  • Catalog soft-archiving vs hard-deletion rules
  • Archive → restore without duplicate variant SKU conflicts
  • Product image reordering and thumbnail selection tests

Audited 28-Step Admin End-to-End Workflow

The connected admin regression suite validated this complete lifecycle without manual interventions:

  1. 01.Create product category in admin back-office
  2. 02.Create seasonal or curated collection
  3. 03.Create product with title, description, and base metadata
  4. 04.Assign product to verified category
  5. 05.Assign product to collection
  6. 06.Create product variant (size, colorHex, SKU)
  7. 07.Assign unique inventory SKU
  8. 08.Set initial stock level to 10 units
  9. 09.Admin inventory ledger reflects exact on-hand quantity of 10
  10. 10.Public storefront reflects in-stock status in real time
  11. 11.Execute manual stock adjustment to 7 units via admin interface
  12. 12.Public storefront instantly updates available stock to 7
  13. 13.Rename parent category in admin
  14. 14.Product automatically reflects renamed category association
  15. 15.Remove product from collection
  16. 16.Collection product count aggregates update accordingly
  17. 17.Re-add product back to collection
  18. 18.Collection listing dynamically restores product card
  19. 19.Soft-archive product from active catalog
  20. 20.Storefront catalog hides archived product from search and browsing
  21. 21.Inventory ledger continues accurately tracking physical stock for archived product
  22. 22.Restore product from archive
  23. 23.Storefront restores product availability without SKU duplicates
  24. 24.Place authenticated test order through customer checkout
  25. 25.Two-phase inventory reservation is recorded (availableQty drops accordingly)
  26. 26.Order accurately references immutable product and variant line-item snapshot
  27. 27.Server verification & webhook processing commits inventory reservation
  28. 28.Immutable audit records and inventory transaction ledgers are created

11. Production Performance

"Performance is part of the product." · Clean Deployed Lighthouse Results

0.0s
FCP
0.0s
LCP
0.0s
Speed Index
0
CLS
0
Accessibility
0
Best Practices
0
SEO

12. Production Deployment

Hosted on the Vercel Edge Network for the Next.js 15 application, with MongoDB Atlas providing multi-region managed database replication. Vercel Edge Middleware executes lightweight cryptographic checks and routing rules before reaching origin nodes, maximizing TTFB and availability.

13. Engineering Lessons Learned

01.Concurrency must be handled at the database engine level

Application-level state checks cannot prevent race conditions during simultaneous requests. Using atomic conditional updates (e.g. availableQty >= reqQty) is essential for inventory correctness.

02.External webhooks require mandatory idempotency

Payment gateways frequently dispatch duplicate webhook notifications or deliver events out of order. Verifying signatures with timingSafeEqual and deduplicating via transaction records prevents duplicate order processing.

03.Domain service boundaries keep server components clean

Isolating business logic into 14 domain services allowed API route handlers and server actions to remain minimal, while ensuring the exact same validation and audit logging rules apply across both storefront and admin operations.

Browse Other Projects