Demonstration

Multi-tenant commerce platform

A demonstration of a multi-tenant commerce core: tenant-scoped catalogs and pricing, a checkout that reserves stock atomically, and an order pipeline that stays correct under retries and partial failures.
Demonstration · fictional data
Next.jsTypeScriptNestJSPostgreSQL (RLS)RedisStripeSNS / SQSOpenTelemetry
Type
Demonstration · fictional data
Domain
E-commerce, SaaS
Problems
Data consistency, Multi-tenancy, Peak load
Year
2026

This is a demonstration, not client work. It was built for this portfolio with fictional companies and data to show how I approach this kind of system. Outcomes below are illustrative targets, not achieved results.

01Interactive preview

Try it. Everything here works.

A working product preview with fictional data. State changes, events and edge cases are simulated in your browser; nothing is sent anywhere.
Democommerce-core · Multi-tenant commerce core

Every query runs with tenant_id = alder; row-level security hides other tenants’ rows.

Oak serving board

AP-OAK-01

$48.00

On hand 14 · reserved 0 · available 14

Linen throw

AP-LIN-02

$129.00

On hand 6 · reserved 0 · available 6

Stoneware mug set

AP-MUG-03

$56.00

On hand 2 · reserved 0 · available 2

Cast iron skillet

AP-SKL-04

$85.00

On hand 9 · reserved 0 · available 9

Scenarios
  1. Cart

  2. Reserved

  3. Paid

  4. Fulfilled

Cart

Your cart is empty. Add a product to begin.

Total$0.00

Domain events

0 events
  1. No events yet. Add something to the cart, check out, or try a scenario.

02Context & constraints

The situation

Three fictional retail brands (Alder & Pine home goods, Kestrel Cycle Works and Lumen Botanics) share one commerce platform. Each needs its own catalog, prices, branding and stock, but the operator wants one codebase, one deployment and one on-call rotation.

The scenario is typical of groups that run several storefronts, and of B2B platforms that offer white-label shops to their own customers.

Role

A self-initiated demonstration, not client work. In a real engagement of this shape I would own the architecture, data model, backend services, storefront and deployment.

  1. Tenancy model and row-level security policies
  2. Catalog, checkout, inventory and order services
  3. Stock reservation design
  4. Payment integration and webhook handling
  5. Storefront performance and SEO
  6. CI/CD, observability and runbooks

Constraints

  • Hard tenant isolation

    A bug in one query must not expose another tenant's orders or prices. Isolation is enforced by the database, not only by application code.

  • No oversells at peak

    Limited-stock drops attract concurrent buyers. Two customers must never both be sold the last unit.

  • At-least-once infrastructure

    Payment webhooks, queues and client retries can all deliver the same message twice. Every step must be safe to repeat.

  • Small operating team

    One shared deployment and observability stack, with per-tenant dashboards but no per-tenant infrastructure.

03Architecture & data flow

Follow the data, one step at a time.

Pick a flow and step through it, or press play. Each step highlights the connection involved and explains what happens there and why.

Step 1 / 6

Scroll sideways to see the whole diagram →

Architecture diagram: Multi-tenant commerce platformComponents: Storefronts, Edge cache, Payment provider, API gateway, Catalog, Checkout, Inventory, Orders, Redis, PostgreSQL, Event bus. Highlighted path: Checkout reserves stock, step 1 of 6: Shopper starts checkout.SHARED CORE · TENANT_ID ON EVERY ROWStorefrontsNext.js · per tenantUIEdge cacheTenant-scoped keysEDGEPayment providerStripe · simulatedEXTAPI gatewayAuth · tenant contextSVCCatalogProducts · pricingSVCCheckoutCart · reservationsSVCInventoryStock ledgerSVCOrdersState machine · outboxSVCRedisHot catalog · sessionsDATAPostgreSQLRow-level securityDATAEvent busSNS + SQS · DLQQUEUE

Checkout reserves stock

How a checkout holds inventory without overselling, even when many shoppers want the last unit.

Checkout reserves stock, step 1 of 6: Shopper starts checkout. The storefront posts the cart with an idempotency key generated in the browser.

04Engineering decisions

Decisions, with their costs.

Written as short decision records: what was chosen, what it costs, and what else was considered.

ADR-01

Shared schema with PostgreSQL row-level security

Decision
Every tenant-owned table carries tenant_id. RLS policies filter on a session setting established per request from the authenticated tenant.
Trade-off
Cheapest to operate and simplest to migrate, but tenants share resources; very large tenants may later need dedicated databases.
Alternatives considered
Schema per tenant (migration effort grows with tenant count) or database per tenant (strongest isolation, highest cost).

ADR-02

Reservations with expiry, not decrement at payment

Decision
Checkout creates reservation rows with a TTL inside a transaction that checks available stock as on-hand minus active reservations.
Trade-off
Extra writes and a sweeper job, in exchange for no oversells and a clear record of who held what.
Alternatives considered
Decrementing stock when payment succeeds (oversells under concurrency) or Redis-only counters (fast, but harder to reconcile).

ADR-03

Idempotency keys on every write

Decision
Clients and webhooks send an idempotency key; the first response is stored and replayed for duplicates.
Trade-off
A small table and middleware, versus duplicate orders and double charges during retries.
Alternatives considered
Unique constraints alone, which block duplicates but return confusing errors to legitimate retries.

ADR-04

Transactional outbox for domain events

Decision
Order and inventory changes write events to an outbox table in the same transaction; a relay publishes them to the bus.
Trade-off
Slight publish latency, but events are never lost and never published for rolled-back changes.
Alternatives considered
Publishing right after commit (events lost on a crash) or distributed transactions (complex and poorly supported).

05Implementation

Where the details live

Atomic reservation

The reservation runs inside one transaction under the tenant's RLS policy. Locking the SKU row makes concurrent checkouts for the same item wait their turn, so the availability check and the insert can't interleave.

Reserve stock only if enough remains — runs in a single transactionSQL
-- Concurrent reservations for the same SKU queue behind this lock.
SELECT on_hand FROM inventory WHERE sku_id = $1 FOR UPDATE;

INSERT INTO reservations (tenant_id, sku_id, cart_id, qty, expires_at)
SELECT current_setting('app.tenant_id')::uuid, $1, $2, $3,
       now() + interval '15 minutes'
WHERE (
  SELECT i.on_hand - COALESCE(SUM(r.qty), 0)
  FROM inventory i
  LEFT JOIN reservations r
    ON r.sku_id = i.sku_id AND r.expires_at > now()
  WHERE i.sku_id = $1
  GROUP BY i.on_hand
) >= $3
RETURNING id;  -- no row returned means "not enough stock"

Idempotent webhook handling

Payment webhooks are verified, recorded by event ID and processed once. Replays return the stored result, so a provider retry can never create a second paid order.

Webhook handler, NestJS-style (simplified)TypeScript
@Post("webhooks/payments")
async handle(@Req() req: RawBodyRequest<Request>) {
  const event = this.payments.verify(req.rawBody, req.headers["stripe-signature"]);

  return this.db.transaction(async (tx) => {
    const first = await tx.processedEvents.insertIfAbsent(event.id);
    if (!first) return { status: "duplicate" };

    if (event.type === "payment_intent.succeeded") {
      const order = await tx.orders.markPaid(event.data.object.metadata.orderId);
      await tx.outbox.add("OrderPaid", { orderId: order.id, tenantId: order.tenantId });
    }
    return { status: "processed" };
  });
}

Tenant-aware caching

Catalog pages are cached at the edge with the tenant in the cache key and purged by surrogate keys when a product changes, so one tenant's update never invalidates another tenant's pages.

06Deployment

Running it for real

Proposed topology for a production version of this design.
Runtime
Containerized services on AWS ECS Fargate behind an application load balancer; storefronts on a CDN-backed Next.js deployment.
Data
Amazon RDS for PostgreSQL with Multi-AZ, point-in-time recovery and a read replica for catalog queries; ElastiCache Redis for sessions and hot catalog data.
Messaging
SNS topics fanning out to one SQS queue per consumer, with dead-letter queues and redrive alarms.
Delivery
Terraform for infrastructure, GitHub Actions for build and deploy, database migrations gated in the pipeline.
Observability
OpenTelemetry traces carry tenant_id as an attribute, so latency and errors can be sliced per tenant.

07Outcomes & lessons

What this shows, honestly labeled.

Nothing below is a client result. These are the capabilities the demonstration exercises and how success would be measured in a real engagement.
  • What the demo shows

    Illustrative — not a client result

    Tenant switching with isolated catalogs, stock reservation with expiry, an order state machine and the domain events each step emits.

  • How success would be measured

    Illustrative — not a client result

    Zero oversells and zero duplicate orders in reconciliation reports; p95 checkout latency and error rate tracked per tenant against agreed budgets.

  • What is simulated

    Illustrative — not a client result

    Payments, fulfillment and email are simulated in the browser. No real transactions or customer data are involved.

Design notes

  • Row-level security has to be checked with every migration: a new table without a policy is the most likely isolation bug.
  • Reservation expiry needs product input. Too short frustrates slow shoppers; too long locks stock during a drop.
  • Per-tenant observability is cheap to add on day one and expensive to retrofit.

Next step

Tell me what you’re building. I’ll tell you how I’d approach it.

Send a short brief. You’ll get a written reply from me within two business days — either a few clarifying questions, a suggested first step, or an honest “I’m not the right fit” with a pointer elsewhere.

Parth Patel

Senior full-stack engineer