KashmirStag
A production B2C e-commerce platform built from the ground up for Kashmiri crafts and local artisans.
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)
API Layer
Service Layer (14 Services)
Data Layer
4. Commerce Architecture & Relational Flow
In KashmirStag, catalog and order relationships are strictly modeled to decouple public discovery from fulfillment:
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
availableQty = onHand - reservedQtyTo 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:
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:
9. Data Models (19 Mongoose Schemas)
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:
- 01.Create product category in admin back-office
- 02.Create seasonal or curated collection
- 03.Create product with title, description, and base metadata
- 04.Assign product to verified category
- 05.Assign product to collection
- 06.Create product variant (size, colorHex, SKU)
- 07.Assign unique inventory SKU
- 08.Set initial stock level to 10 units
- 09.Admin inventory ledger reflects exact on-hand quantity of 10
- 10.Public storefront reflects in-stock status in real time
- 11.Execute manual stock adjustment to 7 units via admin interface
- 12.Public storefront instantly updates available stock to 7
- 13.Rename parent category in admin
- 14.Product automatically reflects renamed category association
- 15.Remove product from collection
- 16.Collection product count aggregates update accordingly
- 17.Re-add product back to collection
- 18.Collection listing dynamically restores product card
- 19.Soft-archive product from active catalog
- 20.Storefront catalog hides archived product from search and browsing
- 21.Inventory ledger continues accurately tracking physical stock for archived product
- 22.Restore product from archive
- 23.Storefront restores product availability without SKU duplicates
- 24.Place authenticated test order through customer checkout
- 25.Two-phase inventory reservation is recorded (availableQty drops accordingly)
- 26.Order accurately references immutable product and variant line-item snapshot
- 27.Server verification & webhook processing commits inventory reservation
- 28.Immutable audit records and inventory transaction ledgers are created
11. Production Performance
"Performance is part of the product." · Clean Deployed Lighthouse Results
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.