Back to Library
Tech Deep DiveEngineering

[Case Study] Veloryc E-Commerce Operations System

Alfaz Mahmud Rizve
Alfaz Mahmud Rizve
@whois_alfaz
November 15, 2024
10 min read
Veloryc E-Commerce: High-Performance Architecture Using Supabase RLS and Pure CSS Modules

This technical breakdown contains affiliate links. If you deploy this stack using my links, I earn a commission at no extra cost to you.

By Alfaz Mahmud Rizve | RevOps & Full Stack Automation Architect


The Executive Problem: The Bloat of Commercial E-Commerce

Veloryc is a custom headless e-commerce platform engineered for luxury skincare that dropped Time to First Byte (TTFB) to 18ms and achieved a 100/100 mobile Lighthouse performance score by replacing Shopify's liquid runtime with Next.js 15, zero-dependency CSS Modules, and Supabase PostgreSQL Row Level Security (RLS).

When architecting Veloryc, the engineering requirements were stringent:

1
The brand identity demanded a fluid, luxury user experience characterized by frictionless page transitions (PageTransition.tsx), immersive micro-interactions (SkinQuiz.tsx, IngredientAccordion.tsx), and a zero-delay StickyATC (Add to Cart) interface.
2
Standard e-commerce platforms like Shopify Plus charge upwards of $2,500/month plus transaction fees and third-party app subscriptions, while obscuring backend database logic and introducing massive client-side script bloat (averaging 1.8MB to 3.2MB of uncompressed JavaScript).
3
Flash sales and limited edition serum drops frequently cause race conditions in traditional relational databases, resulting in stock overselling and manual customer support remediation.

To achieve absolute control over DOM execution, crawlability, and atomic transactional integrity, we built Veloryc from the ground up without third-party page builders or heavy runtime CSS frameworks. For luxury brands where organic search visibility is critical for customer acquisition, we continuously audit crawl budgets and schema using free browser-based SEO audit tools to prevent indexing bloat.


The Architecture Decision: Next.js 15 + Supabase + Pure CSS Modules

Architecture LayerVeloryc Custom StackStandard Shopify Plus / WooCommerce
Frontend FrameworkNext.js 15 (App Router, React Server Components)Liquid / PHP monolithic server templates
Styling EngineZero-dependency Pure CSS Modules (14KB total CSS)Tailwind CSS / Emotion / Theme asset dumps (450KB+)
Database & AuthSupabase PostgreSQL 15 with native Row Level SecurityProprietary closed API / MySQL with table locks
Global TTFB18ms (Vercel Edge Network + Stale-While-Revalidate)380ms – 850ms (Origin server dynamic compilation)
Mobile Lighthouse100 / 100 Performance38 – 62 Performance
Monthly Hosting Cost$45 / month (Supabase Pro + Vercel Pro)$2,500+ / month (Shopify Plus base subscription)
JSON Payload
+-----------------------------------------------------------------------------------+
|                        VELORYC SYSTEM ARCHITECTURE                                |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  [ Client Browser ] <==== (18ms TTFB / HTTP/3) ====> [ Vercel Edge CDN ]          |
|         |                                                   |                     |
|         | Pure CSS Modules                                  | Server Actions      |
|         | (Zero Runtime JS)                                 | & Data Fetching     |
|         v                                                   v                     |
|  +---------------------+                             +-------------------------+  |
|  | Hardware-Accelerated|                             | Next.js 15 App Router   |  |
|  | CSS Transforms      |                             | (React Server Component)|  |
|  +---------------------+                             +-------------------------+  |
|                                                                  |                |
|                                                     Postgres RLS | Signed JWT     |
|                                                                  v                |
|                                                      +-------------------------+  |
|                                                      | Supabase PostgreSQL DB  |  |
|                                                      | - profiles / orders     |  |
|                                                      | - FOR UPDATE row locks  |  |
|                                                      | - Realtime Stock Alerts |  |
|                                                      +-------------------------+  |
|                                                                  |                |
|                                                     Database     | Database       |
|                                                     Webhook      | Trigger        |
|                                                                  v                |
|                                                      +-------------------------+  |
|                                                      | Self-Hosted n8n Ops     |  |
|                                                      | - Telegram low stock    |  |
|                                                      | - Brevo receipt dispatch|  |
|                                                      +-------------------------+  |
+-----------------------------------------------------------------------------------+

1. Zero-Dependency Styling: Pure CSS Modules

Instead of adopting Tailwind CSS or a heavy CSS-in-JS library like Styled-Components (which forces runtime style calculation and blocks the main thread during hydration), I engineered the entire storefront using scoped CSS Modules.

JSON Payload
/* Example from SkinQuiz.module.css */
.quizContainer {
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  background: rgba(18, 18, 20, 0.75);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 16px;
  transform: translateZ(0); /* Hardware GPU layer promotion */
  transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), 
              opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1);
  will-change: transform, opacity;
}

.stickyAtcButton {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 50;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 28px;
  background: var(--color-accent-gold);
  color: var(--color-surface-dark);
  font-family: var(--font-mono);
  font-size: clamp(0.875rem, 1.5vw, 1rem);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
  cursor: pointer;
}

This design pattern maps animations directly to GPU compositing layers without shipping utility CSS classes or layout-thrashing style injections. Cumulative Layout Shift (CLS) was measured at an absolute 0.000 across both desktop and mobile viewports.

2. The Database Layer: Supabase PostgreSQL & Row Level Security

The data architecture relies on a normalized PostgreSQL database managed through Supabase. The schema is organized into four core relational tables: profiles, products, orders, and order_items.

Rather than relying on application-level authorization (where a single forgotten where user_id = ... clause can expose customer PII), security is enforced directly at the SQL engine level using PostgreSQL Row Level Security (RLS).

JSON Payload
-- 1. Enable RLS across transaction tables
ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.order_items ENABLE ROW LEVEL SECURITY;

-- 2. Customer policy: Users can only select their own order records
CREATE POLICY "Users can view own orders" 
ON public.orders FOR SELECT 
TO authenticated
USING (auth.uid() = user_id);

-- 3. Customer profile policy: Strict identity isolation
CREATE POLICY "Users can update own profile" 
ON public.profiles FOR UPDATE 
TO authenticated
USING (auth.uid() = id)
WITH CHECK (auth.uid() = id);

-- 4. Admin override: Service role key bypasses customer restrictions
CREATE POLICY "Service role full access" 
ON public.orders FOR ALL 
TO service_role
USING (true)
WITH CHECK (true);

3. Solving Flash-Sale Race Conditions with PostgreSQL FOR UPDATE Locks

In limited edition skincare drops, 100+ customers often click "Checkout" at the exact same second for the last 5 bottles of serum. If your application reads inventory, verifies availability, and updates stock across separate queries, duplicate orders will slip through.

To guarantee atomic stock deductions, we implemented a dedicated PostgreSQL stored procedure using row-level locking:

JSON Payload
CREATE OR REPLACE FUNCTION process_atomic_order(
  p_user_id UUID,
  p_items JSONB, -- Array of [{ product_id: UUID, quantity: INT }]
  p_total_amount NUMERIC
) RETURNS UUID AS $$
DECLARE
  v_order_id UUID;
  v_item RECORD;
  v_current_stock INT;
BEGIN
  -- Create the master order record
  INSERT INTO public.orders (user_id, total_amount, status)
  VALUES (p_user_id, p_total_amount, 'pending')
  RETURNING id INTO v_order_id;

  -- Iterate through items and lock stock rows exclusively
  FOR v_item IN SELECT * FROM jsonb_to_recordset(p_items) AS x(product_id UUID, quantity INT)
  LOOP
    -- Lock the specific product row to block concurrent checkout mutations
    SELECT stock_quantity INTO v_current_stock
    FROM public.products
    WHERE id = v_item.product_id
    FOR UPDATE;

    IF v_current_stock < v_item.quantity THEN
      RAISE EXCEPTION 'Insufficient stock for product ID % (Available: %, Requested: %)', 
        v_item.product_id, v_current_stock, v_item.quantity;
    END IF;

    -- Decrement stock atomically
    UPDATE public.products
    SET stock_quantity = stock_quantity - v_item.quantity,
        updated_at = NOW()
    WHERE id = v_item.product_id;

    -- Insert order item record
    INSERT INTO public.order_items (order_id, product_id, quantity)
    VALUES (v_order_id, v_item.product_id, v_item.quantity);
  END LOOP;

  RETURN v_order_id;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

If any item in the cart lacks sufficient inventory, PostgreSQL aborts the entire transaction, throwing a descriptive exception back to the Next.js Server Action without leaving partial orders or corrupted stock counts.


Technical Blueprint: The Admin Command Center & Real-Time Sync

While the customer-facing storefront prioritizes aesthetic restraint, the operations command center (/admin) is built for operational velocity.

When an authenticated user has the is_admin flag enabled in their profiles record, the dashboard unlocks direct real-time database feeds via Supabase Realtime WebSocket listeners.

The Command Center aggregates four critical operational streams:

1
Gross Revenue & Net Margin: Computed directly from finalized orders records using database views.
2
Real-Time Fulfillment Queue: Dynamic order cards categorized by Pending, Paid, Shipped, and Cancelled.
3
Active Shopper Sessions: Real-time presence tracked via Supabase Realtime channels.
4
Low Stock Alert Automation: To ensure serum bottles never run out unannounced, an automated database trigger monitors stock_quantity. Any product dropping below 15 units dispatches an asynchronous HTTP webhook to our self-hosted n8n instance, sending immediate push notifications to our Telegram operations channel and updating vendor procurement spreadsheets.
JSON Payload
// Next.js 15 Server Action for Instant Admin Price & Inventory Updates
'use server';

import { createServerActionClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { revalidateTag } from 'next/cache';

export async function updateProductInventory(productId, newPriceCents, newStock) {
  const supabase = createServerActionClient({ cookies });
  
  // Verify administrator privilege
  const { data: { session } } = await supabase.auth.getSession();
  if (!session) throw new Error('Unauthorized');

  const { data: profile } = await supabase
    .from('profiles')
    .select('is_admin')
    .eq('id', session.user.id)
    .single();

  if (!profile?.is_admin) throw new Error('Forbidden: Admin access required');

  const { error } = await supabase
    .from('products')
    .update({ 
      price_cents: newPriceCents, 
      stock_quantity: newStock,
      updated_at: new Date().toISOString() 
    })
    .eq('id', productId);

  if (error) throw new Error(error.message);

  // Invalidate Next.js edge cache tags immediately
  revalidateTag('products');
  revalidateTag(`product-${productId}`);

  return { success: true };
}

Zero-Friction Authentication & Session Persistence

Veloryc features a Dual-Auth system powered by GoTrue. Shoppers can check out silently as guests or create a persistent account via Google OAuth or magic email links.

When a guest converts to a registered customer post-purchase, a database trigger automatically executes:

JSON Payload
-- Automatically attach guest orders to newly registered customer accounts
CREATE OR REPLACE FUNCTION link_guest_orders_on_signup()
RETURNS TRIGGER AS $$
BEGIN
  UPDATE public.orders
  SET user_id = NEW.id
  WHERE customer_email = NEW.email
    AND user_id IS NULL;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE PROCEDURE link_guest_orders_on_signup();

This eliminates the friction of forced registration while ensuring zero loss of customer order history.


Results & Operational Metrics

Deploying Veloryc on this custom decoupled stack produced definitive gains across performance, security, and unit economics:

  • Time to First Byte (TTFB): 18ms on edge CDN, representing a 96% latency reduction compared to Shopify Plus origin servers.
  • Client Bundle Size: 42KB initial JS bundle and 14KB CSS, compared to 1.8MB+ on commercial luxury themes.
  • Infrastructure Savings: Replaced a projected $2,500/month Shopify Plus enterprise subscription with $45/month in fixed cloud compute ($25/mo Supabase Pro + $20/mo Vercel Pro). That represents $29,460 saved annually in SaaS overhead.
  • Stock Integrity: Zero inventory race conditions recorded across three high-traffic flash sale launches.

Frequently Asked Questions

How do you prevent inventory overselling during flash sales on Supabase?

We execute order processing inside a PostgreSQL stored procedure (process_atomic_order) utilizing SELECT ... FOR UPDATE row-level locks. This locks the specific product rows for the duration of the transaction. If two shoppers submit orders simultaneously for the last stock unit, the second transaction is blocked until the first finishes, detects the zero stock balance, and safely rolls back the order with an out-of-stock exception.

Why choose Pure CSS Modules over Tailwind CSS or CSS-in-JS for luxury e-commerce?

High-end retail storefronts require nuanced micro-interactions, custom easing curves (cubic-bezier), and hardware-accelerated 3D transforms that quickly bloat Tailwind utility classes into unmaintainable HTML markup. CSS-in-JS libraries like Emotion or Styled-Components inject styles dynamically at runtime, blocking the browser's main thread and degrading Core Web Vitals (specifically Interaction to Next Paint / INP). Pure CSS Modules compile to static scoped CSS files at build time with zero JavaScript runtime overhead.

How does the guest checkout reconciliation trigger preserve user data privacy?

The link_guest_orders_on_signup() PostgreSQL trigger runs with SECURITY DEFINER permissions inside the database engine. It matches the verified email string from Supabase Auth (auth.users) with orphaned records in public.orders where user_id IS NULL. Because Row Level Security prevents unauthenticated clients from reading foreign order records, guest transaction history can only be accessed once the shopper successfully verifies email ownership via magic link or OAuth.


Related Technical Services

In this Article

Ready to automate your agency?

Skip the manual grunt work. Let's build a custom system that runs your business on autopilot 24/7.