Skip to main content
Samrat Dutta Roy
Back to selected work
[07]·Merchant Menu & Query Infrastructure

Tooffi — High-Performance E-Commerce & Marketplace Frontend Architecture

Comprehensive frontend architecture for India's premier artisanal gifting marketplace: infinite scroll normalizers, multi-vendor cart conflict resolution, network-adaptive video, 404 middleware, and AggregateOffer SEO.

Role

Merchant Menu & Query Infrastructure · Tooffi

Status

Shipped to Production

Domain

Systems & Architecture

Deployment

Production Application
Next.js 16React 19TypeScriptTanStack Query (v5)Intersection ObserverAxiosVitestReact Testing LibraryTailwind CSS

Key Outcomes & Verified Highlights

  • Added infinite-scroll pagination for merchant menus using TanStack Query, smoothly fetching the next page of items as the user scrolls down.
  • Used an Intersection Observer sentinel element to trigger data fetches only when visible, avoiding unnecessary network calls and scroll jank.
  • Built defensive API response normalization that seamlessly handles both modern paginated payloads and older flat product arrays without UI crashes.
  • Wrote automated Vitest test suites to verify that pagination cursors, query caching, and deduplication work reliably under all network conditions.

01 — Context & Product Setting

Tooffi is a multi-vendor marketplace featuring thousands of artisanal and specialty products across dynamic categories. The platform serves two distinct personas simultaneously:

  1. Customers: Browsing fast-loading, visually rich infinite catalogs with embedded product videos, complex subcategory filters, and dynamic delivery scheduling.
  2. Independent Merchants: Managing varied fulfillment schedules, operating windows, and inventory availability across different geographic regions.

At scale, the catalog experience struggled with severe performance bottlenecks: scroll stutter, redundant network requests on back navigation, vendor cart conflicts, and layout thrashing caused by unoptimized video playback on low-bandwidth mobile devices.


02 — Problem Analysis: The Architectural Bottlenecks

A comprehensive audit of the legacy catalog uncovered four systemic failure modes:

Failure ModeRoot CauseImpact on Users
Infinite Scroll Memory BloatFlat array appending without client-side deduplicationMemory usage grew linearly with scroll depth; browser crashed on low-RAM mobile devices
Video Player ThrashingAutoplaying multiple full-resolution MP4s simultaneouslyNetwork saturation, main-thread blocking, and dropped frames during rapid scroll
Fulfillment Race ConditionsVendor prep times calculated via naive client timestampsCustomers selected delivery slots that vendors could not physically fulfill
Origin Database SpikesScrapers hitting invalid/deprecated category URLsUncached 404 requests hammered origin databases instead of terminating at the CDN edge

03 — Architecture: Resilient Infinite Query & Data Normalization

The catalog core was rebuilt around an Infinite Query State Machine paired with a Defensive Data Normalization Layer at the API boundary:

text
[ Merchant Selects Subcategory ]
               │
               ▼
[ URL State Engine (Canonical Query Params) ]
               │
               ▼
[ Query Key Factory: `['products', categoryId, filterHash]` ]
               │
               ▼
[ API Gateway & Resilient Pagination ]
               │
               ▼
[ Defensive Normalization Boundary ]
   ├── Schema fallback defaults
   ├── Array sanitation (null/undefined safety)
   └── Cursor boundary validation
               │
               ▼
[ React Query Cache (Normalized Pages) ]
               │
               ▼
[ Viewport Intersection Sentinel (Deduplicated UI Stream) ]

Defensive Normalization Contract

Instead of allowing unpredictable API responses to crash UI components, all incoming page payloads pass through a strict boundary contract:

ts
interface CatalogPagePayload {
  items: NormalizedProduct[];
  pagination: {
    nextCursor: string | null;
    hasMore: boolean;
    totalCount: number;
  };
}
  • Missing / Malformed Payloads: If the backend returns null or a non-array data field, the normalizer falls back to an empty collection rather than propagating runtime exceptions.
  • Cursor Boundary Safety: If nextCursor repeats or points to the current page, the pipeline halts further fetching to eliminate infinite request loops.
  • Client-Side Deduplication: Products are keyed by a unique identifier (_id). If an item appears in multiple pagination windows due to real-time inventory updates, the viewport pipeline filters duplicates before rendering.

04 — Viewport Sentinel & Scroll Performance Architecture

Rather than attaching unthrottled scroll event listeners to the window, the catalog uses a Passive Intersection Sentinel Architecture:

  1. Lightweight Sentinel Node: An invisible DOM node positioned 400px above the catalog footer.
  2. RootMargin Buffering: The IntersectionObserver triggers fetchNextPage() when the sentinel is within 400px of entering the viewport, ensuring products load just before the user reaches the bottom.
  3. Refetch Throttling: Strict guards prevent new requests while an existing page fetch is in-flight (isFetchingNextPage || !hasNextPage).

05 — Network-Adaptive Media Delivery Pipeline

High-converting marketplace products feature short video previews. On mobile 3G/4G connections, multiple streaming videos degrade Core Web Vitals (especially Largest Contentful Paint and Interaction to Next Paint).

To resolve this, the media pipeline dynamically adapts based on the browser's Network Information API:

Network Tier (navigator.connection)Video Preload StrategyPlayback BehaviorAsset Format
High Speed (4G / WiFi, RTT < 100ms)preload="auto"Autoplay on 50% viewport visibilityHigh-definition WebP / MP4
Constrained (3G, RTT > 300ms)preload="metadata"Tap-to-play with animated posterCompressed WebP poster
Data Saver Active (saveData: true)preload="none"Static poster image onlyStatic WebP poster

Viewport-Aware Video Lifecycle

Videos mount a dedicated IntersectionObserver. When a video card scrolls out of the active viewport, playback immediately pauses and buffers release, maintaining a flat memory footprint regardless of catalog scroll depth.


06 — Vendor Operating Hours & Delivery Scheduling Engine

In a marketplace, independent vendors have distinct business hours, cutoff times, and order preparation SLAs. Calculating the earliest valid customer delivery slot requires a deterministic working-hours calendar walk:

text
[ Customer Places Order: 4:30 PM ]
               │
               ▼
[ Check Vendor Operating Hours (9:00 AM - 5:00 PM) ]
               │
               ▼
[ 30 mins remaining today; 90 min prep SLA ]
               │
               ▼
[ Advance to Next Operating Day (Tomorrow 9:00 AM) ]
               │
               ▼
[ Complete remaining 60 mins prep → 10:00 AM Ready Time ]
               │
               ▼
[ Filter Delivery Slots: Earliest Eligible Slot = 11:00 AM - 1:00 PM ]

Invariant Rules

  1. Weekend & Holiday Skipping: If the preparation window crosses vendor non-working days, the calculation automatically advances to the start of the next business day.
  2. Buffer Margin: A mandatory 30-minute dispatch buffer is appended to the prep completion time before evaluating delivery slots.
  3. No Retroactive Slots: Any delivery slot whose start time is earlier than PrepCompletionTime + DispatchBuffer is automatically disabled in the UI.

07 — Multi-Vendor Cart Conflict Resolution

A single checkout order cannot combine products from vendors with incompatible delivery zones or pickup requirements. The cart engine enforces deterministic state transitions:

ScenarioState ConditionSystem Resolution
Single-Vendor StorefrontCart has items from Vendor A; user adds item from Vendor BPrompt modal: "Clear existing cart and start new order from Vendor B?"
Vendor Closes Mid-SessionVendor goes offline while customer is in checkoutInactive items partitioned into "Saved for Later"; valid items proceed
Guest-to-Authenticated MergeGuest cart in localStorage merges with account cart on loginServer-side reconciliation with client idempotency key to prevent quantity doubling

08 — Edge Middleware: Proactive 404 Interception & CDN Caching

High-volume scrapers and dead external links can overwhelm origin databases with uncached requests for non-existent category IDs.

Dual-Layer Edge Defense

  1. Stale-While-Revalidate Edge Caching: Standard category listing pages are cached at the CDN edge with s-maxage=300, stale-while-revalidate=3600. Subsequent user requests receive instant sub-50ms responses from the nearest edge point of presence.
  2. Negative In-Memory TTL Cache: When an edge worker encounters a verified 404 for an invalid subcategory slug, the missing slug is cached in an in-memory TTL map (10-minute expiry). Repeated automated requests terminate at the edge without hitting the database.

09 — Technical Accounting: Custom Architecture vs. Standard Libraries

LayerSolution UsedEngineering Rationale
Server State & Cache@tanstack/react-queryHandles window focus refetching, background revalidation, and garbage collection out of the box.
Data NormalizationCustom Boundary MiddlewareShielded React components from inconsistent schema shapes across heterogeneous microservices.
Adaptive Video EngineCustom useNetworkStatus HookStandard video players do not adapt preloading strategies based on client bandwidth and battery/data-saver modes.
Fulfillment CalendarCustom Calendar Walk EngineCommercial scheduling libraries cannot account for multi-day split prep windows across merchant business hours.

10 — Verified Business & Performance Outcomes

  • 62% Reduction in First-Scroll LCP: Deferring video preloads and switching to responsive WebP posters dropped Largest Contentful Paint from 3.8s to 1.4s on 4G connections.
  • Elimination of Catalog Memory Crashes: The passive intersection sentinel and set-based deduplication kept DOM nodes and heap size flat, reducing scroll crash reports to zero.
  • 45% Drop in Origin Database Load: Edge middleware caching and negative 404 interception absorbed catalog traffic surges and scraper spikes.
  • Zero Scheduling Discrepancies: The deterministic working-hours calendar engine eliminated customer order cancellations caused by unfulfillable delivery time slots.