# Architecture and invariants ## Components Next.js serves public SSR pages and authenticated admin/API routes. PostgreSQL owns commerce state; object storage/CDN owns sanitized product images. A worker processes persisted jobs, payment reconciliation, reservation expiry and notifications. Jobs must continue when no visitors are present. Separate modules: catalog, inventory, checkout/orders, payments, fulfillment/refunds, themes, sharing, analytics and identity. Use migrations and transactional constraints, not browser state, for correctness. Store money as integer paise with INR currency; timestamps in UTC and reporting in the configured shop time zone. Use safe integer bounds. Taxes and coupon allocation have deterministic rounding and documented examples. ## Minimal data model Products + variants (SKU, price, tax category, active version); inventory balances + immutable movements; collections; media; cart/share records; orders + immutable line/price/address snapshots; reservation groups + lines; checkout idempotency records; payment attempts + provider order/payment IDs; received webhook events; fulfillment lines; refund requests + allocations; coupons + reserved/consumed uses; theme versions; staff/roles; audit events; outbox + jobs. Add foreign keys, uniqueness and indexes for every frequent lookup and identity boundary. ## Checkout and inventory 1. Client sends variant IDs, quantities, coupon, delivery details and a unique checkout key. Server validates and calculates all prices. Repeated identical key returns the same result; different payload with the same key returns conflict. 2. In one database transaction, lock affected inventory rows in a stable order, validate `on_hand - reserved >= requested`, reserve stock/coupon usage, create pending local order and a payment-attempt intent. Default reservation is 15 minutes, configurable. Persist quote and expiry. 3. Create the Razorpay order server-side, outside the stock transaction. Record its identity uniquely. Do not assume the provider supports an idempotency key it does not document. If the create result is ambiguous, reconcile by recorded provider metadata/receipt where supported; otherwise pause that attempt for investigation instead of blindly creating repeated payable orders. 4. Issue checkout parameters only for a persisted attempt. A retry must not create concurrent payable attempts unknowingly. If multiple payments nevertheless succeed, accept at most one for fulfillment and route extra captures to a refund exception. 5. Verified captured/paid status transitions the order exactly once, consuming reserved stock and coupon usage transactionally. Inventory movement unique key includes the order and transition. Authorized-only payment is not captured money. 6. Expiry, cancellation and payment settlement lock the same order/reservation records and apply conditional state transitions. Expiry releases reservations once. A late payment atomically reacquires every item and coupon eligibility against the original financial snapshot, or enters `paid_exception` for refund/manual resolution; never silently oversell or change what the customer paid. Payment failure cannot downgrade a successful order. Inventory adjustment cannot reduce physical stock below currently reserved quantities without an explicit exception workflow. API actions use version checks to reject stale edits. There is no external network call inside a held database transaction. ## Payment verification Razorpay Standard Checkout uses current supported intent/QR behavior; provider controls app/device compatibility. Verify checkout signatures server-side, using the server-recorded provider order ID. Verify raw-body webhook HMAC before parsing/trusting fields, with separate webhook secret and documented secret rotation. Validate account/mode, order, amount and currency; fetch authoritative provider status as needed. A browser callback, UPI return, screenshot or buyer-supplied reference is never sufficient to fulfill. Persist verified webhook events durably with unique provider event ID before acknowledging; process idempotently. Duplicate/reordered events, worker crashes and replay after timeout must converge to the same state. Reconcile pending/ambiguous orders periodically through provider APIs with backoff/rate limits. Alert on unresolved paid exceptions, reconciliation age and failed jobs. Webhook outage recovery must not depend on the customer returning. Payment attempts: `created`, `pending`, `authorized`, `captured`, `failed`, `unknown`. Orders: `awaiting_payment`, `paid`, `paid_exception`, `cancelled`, `closed`. Fulfillment and refunds are separate line-level records with their own lifecycle; UI may derive combined badges. A refund does not erase capture history. Refund intent is persisted with a unique operation key and amount allocation. Concurrent requests lock captured/refunded/reserved-refund totals. After provider timeout, reconcile rather than issuing another refund blindly. Pending refunds reserve refundable balance. Only verified processed refunds count as complete. Provider rejection or lost response remains visible. Define who may approve refunds and log the actor/reason. ## Access and safety Use a maintained authentication implementation, secure cookies, CSRF protection, session revocation and rate limits. Owner bootstrap is one-time, and never a public fixed password. Owner MFA is required before live payments. Enforce permissions server-side on every endpoint and export. Keep customer PII out of logs, metrics, QR codes and public previews. Private order tokens have high entropy, expiry/revocation, no-referrer and no-store policies; do not expose full addresses through bearer links alone. Validate uploads by decoded format, byte size and dimensions, strip metadata and re-encode supported raster formats. No executable uploads. Use safe redirect/tracking URL schemes; protect SSRF and open redirects. Secrets stay server-side in the host's secret store. Apply a CSP compatible with the verified payment integration. Redact exports and backups to authorized roles and define retention/deletion with merchant policy. ## Operations and deployment Transactional outbox separates committed commerce changes from notifications; at-least-once delivery plus stable message keys prevents duplicate customer messages where provider support permits. Do not promise exactly-once external delivery. Background processing uses retry budgets, leases, dead letters and observable status. Before live launch: migrations tested, backup restore demonstrated, HTTPS/domain configured, image storage access scoped, worker/reconciliation scheduled, merchant activation confirmed, live webhook verified, policies/contact/returns/shipping/tax settings reviewed, staff access audited and a merchant-approved real-device payment/refund test performed. Never charge or refund real money without the owner's approval. Backups include database and object references; document RPO/RTO and how inventory/payment state is reconciled after restore. ## Provider references Verify current provider behavior during implementation; this spec's references were consulted 2026-11-15. - https://razorpay.com/docs/payments/payment-methods/upi/ - https://razorpay.com/docs/payments/payment-gateway/web-integration/standard/integration-steps/ - https://razorpay.com/docs/webhooks/validate-test/ Use the chosen product's test mode, not assumptions from another Razorpay product. Report sandbox checks separately from real-device/live checks and merchant-account eligibility.