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
Domain
Systems & Architecture
Deployment
Production ApplicationKey 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:
- Customers: Browsing fast-loading, visually rich infinite catalogs with embedded product videos, complex subcategory filters, and dynamic delivery scheduling.
- 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 Mode | Root Cause | Impact on Users |
|---|---|---|
| Infinite Scroll Memory Bloat | Flat array appending without client-side deduplication | Memory usage grew linearly with scroll depth; browser crashed on low-RAM mobile devices |
| Video Player Thrashing | Autoplaying multiple full-resolution MP4s simultaneously | Network saturation, main-thread blocking, and dropped frames during rapid scroll |
| Fulfillment Race Conditions | Vendor prep times calculated via naive client timestamps | Customers selected delivery slots that vendors could not physically fulfill |
| Origin Database Spikes | Scrapers hitting invalid/deprecated category URLs | Uncached 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:
[ 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:
interface CatalogPagePayload {
items: NormalizedProduct[];
pagination: {
nextCursor: string | null;
hasMore: boolean;
totalCount: number;
};
}- Missing / Malformed Payloads: If the backend returns
nullor a non-arraydatafield, the normalizer falls back to an empty collection rather than propagating runtime exceptions. - Cursor Boundary Safety: If
nextCursorrepeats 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:
- Lightweight Sentinel Node: An invisible DOM node positioned 400px above the catalog footer.
- RootMargin Buffering: The
IntersectionObservertriggersfetchNextPage()when the sentinel is within 400px of entering the viewport, ensuring products load just before the user reaches the bottom. - 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 Strategy | Playback Behavior | Asset Format |
|---|---|---|---|
| High Speed (4G / WiFi, RTT < 100ms) | preload="auto" | Autoplay on 50% viewport visibility | High-definition WebP / MP4 |
| Constrained (3G, RTT > 300ms) | preload="metadata" | Tap-to-play with animated poster | Compressed WebP poster |
Data Saver Active (saveData: true) | preload="none" | Static poster image only | Static 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:
[ 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
- Weekend & Holiday Skipping: If the preparation window crosses vendor non-working days, the calculation automatically advances to the start of the next business day.
- Buffer Margin: A mandatory 30-minute dispatch buffer is appended to the prep completion time before evaluating delivery slots.
- No Retroactive Slots: Any delivery slot whose start time is earlier than
PrepCompletionTime + DispatchBufferis 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:
| Scenario | State Condition | System Resolution |
|---|---|---|
| Single-Vendor Storefront | Cart has items from Vendor A; user adds item from Vendor B | Prompt modal: "Clear existing cart and start new order from Vendor B?" |
| Vendor Closes Mid-Session | Vendor goes offline while customer is in checkout | Inactive items partitioned into "Saved for Later"; valid items proceed |
| Guest-to-Authenticated Merge | Guest cart in localStorage merges with account cart on login | Server-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
- 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. - 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
| Layer | Solution Used | Engineering Rationale |
|---|---|---|
| Server State & Cache | @tanstack/react-query | Handles window focus refetching, background revalidation, and garbage collection out of the box. |
| Data Normalization | Custom Boundary Middleware | Shielded React components from inconsistent schema shapes across heterogeneous microservices. |
| Adaptive Video Engine | Custom useNetworkStatus Hook | Standard video players do not adapt preloading strategies based on client bandwidth and battery/data-saver modes. |
| Fulfillment Calendar | Custom Calendar Walk Engine | Commercial 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.