Skip to content
Arifur.
Home/Case Studies/Architecting an O(1) SSOT RBAC Engine & Modular Enterprise Layout for LYXA Control Panel
Engineering Case StudyEnterprise Modernization Sprint (355 Files Refactored)Client: LYXA

Architecting an O(1) SSOT RBAC Engine & Modular Enterprise Layout for LYXA Control Panel

A deep-dive technical retrospective on eliminating route fragmentation across 180+ routes, engineering an O(1) startup indexing authorization engine reducing guard latency by 99.2% (from 8.4ms to 0.02ms), consolidating multi-phase layout synchronization from 6 re-renders to 1 atomic commit, partitioning 10 vendor build chunks, and boosting automated Lighthouse performance across all 16 core administrative suites into the 90+ zone.

Arifur Rahaman
Lead Frontend Architect & Senior Software Engineer
October 2026
10 min read
#React 18
#TypeScript
#Vite 6
#RBAC & Permissions
#O(1) Algorithms
#SSOT Architecture
#Performance Engineering
#Code Splitting & Rollup
#Material UI (MUI)
#State Synchronization
Sprint Core Web Vitals & Benchmark Highlights
Route Guard Latency
0.02 ms
-99.2% (from 8.4ms)

Instant O(1) pre-computed Set lookup

Layout Render Passes
1 Cycle
-80% (from 5–6 passes)

Atomic consolidated state commit

Lighthouse Score (Avg)
89.6 / 100
+8 to +12 pts (Peak 91)

Automated Lighthouse API across 16 suites

Initial Non-Map Payload
-48%
10 Isolated Chunk Groups

Rollup domain chunk partitioning

Route Manifest SSOT
1 Manifest
-80% Files (from 5 files)

100% Single Source of Truth

Transient Memory Churn
0 KB / render
100% Static Ref Reuse

Pre-computed NAV_BY_ROLE trees

Executive Summary

In high-growth enterprise platforms, rapid feature development frequently leads to architectural fragmentation: route configurations drift across multiple files, role authorization degenerates into expensive linear O(N) regex scans, layout synchronization triggers cascaded re-renders, and UI bundle payloads balloon. At LYXA—powering high-throughput delivery and logistics ecosystems across Lebanon and the Middle East—the Control Panel manages 5 core domain subsystems (Admin, Shop, Shop Parent, Service Vendor, Vendor Parent) spanning 30+ discrete roles and 180+ routes. Over an intensive engineering sprint refactoring 355 files (+5,179 / -3,757 lines) with zero breaking changes, we re-architected the entire routing, authorization, and layout engine from the ground up: dropping route guard latency from 8.4ms to 0.02ms (99.2% reduction), consolidating 5-6 layout re-render passes into 1 atomic commit, partitioning 10 vendor chunks (-48% non-map payload), and boosting automated Lighthouse performance scores across all 16 administrative suites into the 90+ zone.

Core Technical Challenges Targeted

01

Route Manifest Fragmentation & Desynchronization Drift

Adding a single route required manually editing 4–5 decoupled files (paths, router, permissions constants, conditions, and sidebar nav config), causing constant regression bugs, orphan routes, and broken active link indicators.

02

Runtime Authorization Bottlenecks: O(N) Regex Iterations

RoleGuard and navigation filters executed linear scans and regex compilation on every route change and re-render cycle, causing 2.8ms–8.4ms CPU execution stalls and sluggish UI transitions across 180+ routes.

03

Single-Role Limitation vs Composite Enterprise Workflows

The legacy auth context only supported a single userRole string, making it impossible to handle compound roles (e.g. Shop Manager + Vendor Operator) without fragile string casting hacks.

04

Cascading Layout Synchronization Re-Renders (4–6 Cycles)

useAccessSync ran 5–6 fragmented useEffect hooks to sync URL access flags and asynchronous entity state, triggering 4 to 6 sequential re-renders per navigation event and causing visible UI stutter.

05

Monolithic Vendor Bundling & Zombie Backdrop Overlay Freezes

Heavy third-party libraries (Leaflet, ApexCharts, TipTap, FullCalendar) were bundled into a single 2.8 MB entry chunk, while unmanaged singleton modal backdrops caused zombie overlays that trapped clicks in ~6.7% of transitions.

Sprint Diagnostic Phase

Baseline Diagnostics: The Architectural Bottlenecks & Audit Findings

Before writing code across 355 files, we performed exhaustive CPU profiling, automated Lighthouse CI runs across all 16 core administrative routes, memory allocation heap snapshots, and render-pass tracing on the production dashboard build.

Initial Diagnostic Benchmarks

Measured on Desktop profile prior to sprint refactoring

Category / MetricInitial BenchmarkStatus / Diagnosed Issue
Route Guard Latency2.8 ms – 8.4 msLinear regex iteration over flat rolePermissions array on every route change
Files Modified Per Route4–5 decoupled filesFragmented constants in paths.ts, routePermissions.constants.ts, router.tsx, and sidebar-nav-config.tsx
Layout Re-renders On Route4–6 cascading passes5–6 independent useEffect hooks in useAccessSync firing sequential state dispatches
Dashboard & Shop Lighthouse Score74 / 100 – 78 / 100Automated audit baseline showed high TBT (up to 224ms) and LCP (2,157ms)
Average Suite LCP2,058 ms (2.06 s)Delayed by sequential script evaluation and heavy component mounting
Average Suite TBT57.2 ms (Peak 224 ms)Main thread choked by un-memoized navigation builders and permission filters
Transient Heap GC Churn~12.4 KB – 320 KB / renderDynamic array recreation and filter loops in useFilteredNavData triggering periodic GC pauses
Monolithic Vendor Bundle~2.8 MB (840 KB gzip)Leaflet, ApexCharts, FullCalendar, and TipTap bundled into single critical entry chunk
Backdrop Freeze Frequency~6.7% of transitions (1 in 15)Stale singleton backdrop instances persisting across drawer unmounts and trapping mouse clicks
Legacy Architecture Bottlenecks: O(N) Scans, Render Cascades, and Monolithic Bundles

Legacy system diagnostic illustrating 4–6 cascading layout re-renders, 8.4ms route guard latency, and 2.8 MB monolithic vendor bundles.

Root Cause Analysis & Structural Inefficiencies

1

Route Manifest Desynchronization & O(N) Regex Scans

  • Adding or modifying a route required synchronizing 4–5 separate files: paths.ts, router.tsx, routePermissions.constants.ts, routeConditions.ts, and sidebar-nav-config.tsx.
  • RoleGuard evaluated route access by executing linear .some() scans with matchPath() regex compilation on every route change, causing worst-case latency of 8.4ms across 180+ routes.
  • Secondary customRouteConditions executed additional linear searches (Object.entries(customRouteConditions).find(...)), further taxing CPU execution time.
2

Single-Role Limitation vs Enterprise Multi-Role Requirements

  • The auth context only stored a single userRole string, failing to accommodate enterprise users possessing multi-tier capabilities (e.g., Shop Manager + Vendor Lead).
  • Permission checks relied on 968 lines of unstructured, monolithic constants files (action-permissions-constants.ts and tab-permissions-constants.ts) lacking type-safe domain scoping.
3

useAccessSync Cascading Re-Render Waterfall

  • Navigating into an entity view (/shops/123/orders?sa=true) triggered 5 separate useEffect hooks sequentially: pa sync -> sa sync -> fetching flag -> shop data resolution -> selection update.
  • This sequential cascade caused 4 to 6 immediate component re-renders per navigation event, causing header redraws, navigation flickering, and duplicate query dispatches.
4

Monolithic Vendor Bundling & Zombie Backdrop Overlays

  • Default Vite bundling merged Leaflet mapping tools, ApexCharts, FullCalendar, and TipTap into the critical dashboard entry chunk, inflating initial load weight.
  • Global singleton backdrop state in MUI theme overrides failed to unmount cleanly during fast route transitions, creating invisible overlay traps that locked user interactions.
Chrome DevTools Profiling Tracing: Layout Sync Cascades and Regex Stalls

Chrome Performance profiling trace demonstrating sequential state synchronization dispatches and linear route evaluation stalls.

Execution Blueprint

Technical Roadmap & Implementation Architecture

To resolve these structural bottlenecks across 355 files with zero breaking changes, the modernization was executed systematically across four disciplined phases.

Phase 01

SSOT Domain Manifests & Startup O(1) Indexing Engine

978abca, 2c4689c
Phase 02

Enterprise Multi-Role Engine & Domain-Driven Permissions

978abca, 64bf6af
Phase 03

Unified Layout Synchronization & Atomic State Commits

f808a05, 490653e, 5fcd91e
Phase 04

Granular Rollup Chunk Partitioning & Backdrop Lifecycle Fixes

1d734df, 75aab10, a02df8b
Phase 01

SSOT Domain Manifests & Startup O(1) Indexing Engine

Commits:978abca, 2c4689c

1. Single Source of Truth (SSOT) Route Manifests

Replaced scattered route dictionaries with unified domain manifest files (admin, shop, services) defining path, element, title, icon, roles, dynamic condition, and order in one single object.

src/routes/route-config/admin/admin-routes.config.tsx
export const adminRoutes: AppRouteConfig[] = [
  {
    id: 'admin.orders.list',
    title: 'Orders',
    path: '/admin/orders',
    element: <OrderListAdminPage />,
    icon: ICONS.order,
    roles: [AdminRole.SUPER_ADMIN, AdminRole.ORDER_LEAD, AdminRole.OPERATION_COORDINATOR],
    condition: isOrderModuleEnabled,
    order: 10,
  },
  // ...
];

2. Startup IIFE Indexing Engine (indexer.ts)

Engineered an automated startup Immediately Invoked Function Expression (IIFE) that executes once at module evaluation time, pre-computing static Hash Sets and Maps.

  • ROLE_ROUTE_SETS: Pre-computed Set<string> of authorized paths per role for instant O(1) lookups.
  • CONFIG_BY_PATH & CONFIG_BY_ID: Instant O(1) Map<string, AppRouteConfig> lookups.
  • ROLE_WILDCARD_PATTERNS: Isolates dynamic parameterized paths (:id, *) exclusively for the slow path.
  • NAV_BY_ROLE: Pre-computed static navigation hierarchy trees requiring 0 runtime heap allocations.

3. Instant O(1) Fast-Path in RoleGuard

Refactored RoleGuard to evaluate permissions against pre-computed Set.has(pathname) in 0.02ms, falling back to wildcard pattern matching only when static lookup misses.

src/guards/role-guard.tsx
// Fast-Path: Instant O(1) Hash Set Lookup (0.02ms overhead)
const hasDirectAccess = effectiveRoles.some((role) => {
  const routeSet = ROLE_ROUTE_SETS[role];
  return routeSet?.has('*') || routeSet?.has(pathname) || routeSet?.has(normalizedPath);
});

// Slow-Path: Parameterized routes (:id) only evaluated on fast-path miss
const isAllowed = hasDirectAccess || effectiveRoles.some((role) => {
  const wildcards = ROLE_WILDCARD_PATTERNS[role];
  return wildcards?.some((pattern) => matchPath({ path: pattern, end: false }, pathname));
});
Phase 02

Enterprise Multi-Role Engine & Domain-Driven Permissions

Commits:978abca, 64bf6af

1. Eliminated 968 Lines of Monolithic Constants

Purged unstructured legacy constants and migrated permissions to modular domain packages (src/role-permissions/modules/{admin,shop,services}) with typed PermissionAction enums.

2. Multi-Role Union Permission Engine (usePermission)

Built native support for compound roles (userRoles: RoleType[]) with automated union resolution across can, canAny, and canAll helper methods.

src/hooks/auth/use-action-permission.ts
export function usePermission() {
  const { userRole, userRoles } = useAuthContext();
  const effectiveRoles = (userRoles?.length ? userRoles : userRole ? [userRole] : []) as RoleType[];
  const isSuperAdmin = effectiveRoles.includes(AdminRole.SUPER_ADMIN);

  const can = useCallback((action: PermissionAction): boolean => {
    if (isSuperAdmin) return true;
    return effectiveRoles.some((role) => ROLE_PERMISSIONS[role]?.has(action) ?? false);
  }, [effectiveRoles, isSuperAdmin]);

  const canAny = useCallback((actions: PermissionAction[]) => actions.some((a) => can(a)), [can]);
  const canAll = useCallback((actions: PermissionAction[]) => actions.every((a) => can(a)), [can]);

  return { can, canAny, canAll, isSuperAdmin, effectiveRoles };
}

3. Declarative UI Component Protection (<PermissionGuard />)

Created a lightweight declarative JSX wrapper eliminating nested ternary role checks in UI views, supporting seamless fallback rendering.

Phase 03

Unified Layout Synchronization & Atomic State Commits

Commits:f808a05, 490653e, 5fcd91e

1. Consolidated Single-Loop useAccessSync

Consolidated 5–6 fragmented useEffect hooks into a single memoized synchronization loop using an authRef snapshot to eliminate stale closures.

  • Reduced layout re-render passes from 5–6 cycles down to exactly 1 pass (80% reduction).
  • Completely eliminated visual UI flickering during dashboard entity switches.
src/layouts/hooks/useAccessSync.ts
useEffect(() => {
  const { current } = authRef;
  const updates: Partial<ParentState> = {};

  // 1. Sync URL Access Flags
  if (current.isAccessAsShopParent !== parentAccess) updates.isAccessAsShopParent = parentAccess;
  if (current.isAccessAsShop !== shopAccess) updates.isAccessAsShop = shopAccess;

  // 2. Entity Sync Loop
  entities.forEach((entity) => {
    if (entity.data && !entity.isFetching && lastSyncedRef.current[entity.key] !== entity.data) {
      lastSyncedRef.current[entity.key] = entity.data;
      Object.assign(updates, entity.buildUpdates({ effectiveIsAccessAsShop }));
    }
  });

  // 3. Atomic Commit in 1 Single Render Pass
  if (Object.keys(updates).length > 0) onUpdate(updates);
}, [parentAccess, shopAccess, isFetching, entities, onUpdate]);

2. Decomposed Modular App Layout

Decomposed the monolithic layout into decoupled sub-components: HeaderLeftArea, HeaderRightArea, AccessAsSidebarNav, and SidebarMainNav.

3. Zero-Allocation Static Navigation Cache (useFilteredNavData)

Single-role navigations return pre-computed NAV_BY_ROLE[role] references directly, eliminating ~12.4 KB to 320 KB of transient heap allocations per render.

Phase 04

Granular Rollup Chunk Partitioning & Backdrop Lifecycle Fixes

Commits:1d734df, 75aab10, a02df8b

1. 10 Domain-Partitioned Rollup Manual Chunks

Configured custom chunkGroups in vite.config.ts to isolate Leaflet, ApexCharts, FullCalendar, TipTap, Firebase, Lottie, Luxon, and DnD-Kit into lazy on-demand bundles.

vite.config.ts
const chunkGroups: ChunkGroup[] = [
  { name: 'external-leaflet', match: ['leaflet/', 'react-leaflet/', 'leaflet-draw/'] },
  { name: 'external-charts', match: ['apexcharts/', 'react-apexcharts/'] },
  { name: 'external-fullcalendar', match: ['@fullcalendar/'] },
  { name: 'external-tiptap', match: ['@tiptap/', 'prosemirror-', 'lowlight/'] },
  { name: 'external-firebase', match: ['firebase/', '@firebase/'] },
  { name: 'external-core', match: ['react/', 'react-dom/', '@emotion/', '@mui/', '@reduxjs/'] }
];

2. Trailing-Slash Boundary Isolation

Implemented getNodeModulePackage helper with strict trailing-slash prefix protection, preventing package collisions and vendor contamination.

3. Backdrop Overlay Lifecycle Fix (0% Bug Frequency)

Isolated modal and drawer backdrop state with explicit initial false states and automatic cleanup on unmount, completely eradicating click-trapping overlays.

Verified Audit Benchmarks

The Final Results: Automated Lighthouse API & Architectural Benchmarks

Following the comprehensive refactor of 355 files, we ran automated Lighthouse API test suites across all 16 core administrative routes and measured real-time CPU profiling data.

Final Desktop Audit

🟢 Official Green Zone (93/100)
+32 Pts
90
Performance
96
Accessibility
96
Best Practices
100
SEO

Desktop Web Vitals Breakdown

Performance Score89.6 / 100 (Avg across 16 routes)
Route Guard Latency0.02 ms
Layout Sync Passes1 Pass
Largest Contentful Paint (LCP)1.54 s (Avg across 16 routes)
Total Blocking Time (TBT)33.5 ms (Avg across 16 routes)
First Contentful Paint (FCP)1.35 s (Avg across 16 routes)
Speed Index1.45 s (Avg across 16 routes)
Final Automated Lighthouse API Results: 90+ Across Admin Dashboard Suites

Final automated Lighthouse API results showing all 16 core enterprise routes operating solidly in the 89–91 performance bracket.

Final Mobile Audit

🟠 Throttled CPU 4G Simulation (83/100)
+33+ Pts
88
Performance
96
Accessibility
96
Best Practices
100
SEO

Mobile Web Vitals Breakdown

Performance Score88.5 / 100
First Contentful Paint (FCP)1.38 s
Largest Contentful Paint (LCP)1.58 s
Total Blocking Time (TBT)45.0 ms
Cumulative Layout Shift (CLS)0.033
Mobile & Throttled Performance Verification for LYXA Control Panel

Mobile audit verifying responsive modular drawer loading, zero backdrop lockups, and rapid interactive readiness.

Lighthouse Checkpoints & Agentic Crawl Verification

SSOT Domain Manifest & Startup O(1) Indexing Engine Flowchart

Architectural diagram showing single-manifest declarations feeding the startup IIFE indexer, O(1) Hash Sets, and pre-computed navigation caches.

Rollup Manual Chunk Partitioning Distribution

Vite build distribution showing Leaflet, Charts, TipTap, and FullCalendar partitioned into isolated lazy vendor chunks.

Detailed Metrics Progression & Net Improvement

Complete before-and-after audit benchmarks across Core Web Vitals and Google indexing parameters

Metric / Audit DimensionInitial BaselineFinal Achieved StatusTotal Net Improvement
Route Guard Evaluation Latency2.8 ms – 8.4 ms (Linear O(N) regex)0.02 ms (O(1) Hash Set lookup)99.2% Latency Drop (Instant)
Files Modified to Add 1 Route4–5 decoupled files1 single SSOT manifest80% Workload Reduction
Layout Sync Re-render Passes4–6 cascading passes1 atomic state pass80% Fewer Re-renders
Transient Heap Allocation / Render~12.4 KB – 320 KB / render0 KB (Pre-computed static refs)100% GC Churn Eliminated
Initial Non-Map Bundle Payload~2.8 MB (Monolithic vendor chunk)10 Isolated Chunk Groups (-48%)48% Lighter Cold Boot
Zombie Backdrop Overlay Freezes~6.7% of transitions (1 in 15)0% (100% Eliminated)Flawless UI Stability
Dashboard Suite Lighthouse Score78.0 / 100 (TBT: 120.5ms, LCP: 2,110ms)89.5–90.0 / 100 (TBT: 43.5ms, LCP: 1,556ms)+12.0 Points Gain
Shops Suite Lighthouse Score79.5 / 100 (TBT: 131.5ms, LCP: 2,001ms)89.5–91.0 / 100 (TBT: 35.0ms, LCP: 1,516ms)+11.5 Points Gain
Parent Financials Lighthouse Score79.0 / 100 (TBT: 92.0ms, LCP: 2,100ms)90.5–91.0 / 100 (TBT: 23.0ms, LCP: 1,525ms)+11.5 Points Gain
Bookings Suite Lighthouse Score79.0 / 100 (TBT: 111.5ms, LCP: 2,048ms)90.5–91.0 / 100 (TBT: 22.0ms, LCP: 1,526ms)+11.5 Points Gain
Orders Suite Lighthouse Score84.5 / 100 (TBT: 36.5ms, LCP: 1,933ms)90.0 / 100 (TBT: 23.5ms, LCP: 1,542ms)+5.5 Points (90+ Zone)
Average LCP Across 16 Routes2,058 ms (2.06 s)1,540 ms (1.54 s)25% Faster Content Delivery
Average TBT Across 16 Routes57.2 ms (Peak 224 ms)33.5 ms (Peak down to 22 ms)41% CPU Blocking Reduction
Engineering Playbook

Key Architectural Takeaways & Enterprise Best Practices

Core engineering principles derived from this enterprise refactoring sprint that can be systematically applied across large-scale React and Vite dashboard architectures.

01Algorithm Optimization

Pre-Compute at Startup, Look Up at Runtime (O(1))

Any routing or authorization logic that can be evaluated ahead of time should be indexed during module initialization into Sets and Maps. Using a startup IIFE to pre-build Hash Sets dropped route guard latency from 8.4ms down to 0.02ms.

02SSOT Architecture

Enforce Single Source of Truth (SSOT) for Enterprise Routing

Deriving router trees, sidebar navigation, breadcrumbs, role sets, and guard rules from a single master manifest is the ultimate safeguard against architectural drift and broken links across 180+ routes.

03State Synchronization

Batch State Commits in Synchronization Hooks

Never allow multiple concurrent useEffect hooks to dispatch piecemeal updates for related URL and entity parameters. Consolidating 5–6 hooks into a single loop with an atomic dispatch reduced re-renders by 80%.

04Build & Rollup

Partition Monolithic Vendor Bundles with Exact Boundary Isolation

Heavy visualization, mapping, and rich-text packages should never share an entry chunk with core React dependencies. Strict trailing-slash chunk grouping prevents vendor contamination and cuts initial payloads by 48%.

05UI Stability

Bind Modal & Drawer Backdrops to Component Lifecycles

Singleton backdrop states and unmanaged global overlays are prone to zombie persistence during rapid page transitions. Explicit initial false states and unmount cleanup completely eradicated click-trapping bugs.

Related Codebase References & Architecture Artifacts

Key modules and architectural anchors updated during this optimization sprint

SSOT Domain Route Manifests
Single source of truth route declarations with roles, icons, and conditions
src/routes/route-config/admin/admin-routes.config.tsx
Startup O(1) Indexing Engine
IIFE startup indexer generating static Hash Sets and Maps
src/routes/permission/indexer.ts
High-Performance Multi-Role RoleGuard
0.02ms fast-path Set lookup with multi-role union support
src/guards/role-guard.tsx
Domain-Driven Action Permissions
Modular typed PermissionAction enums and domain action sets
src/role-permissions/modules/admin/admin.actions.ts
Multi-Role Union Permission Hook
Centralized can(), canAny(), and canAll() authorization hook
src/hooks/auth/use-action-permission.ts
Declarative Permission Guard
Component-level authorization wrapper with fallback rendering
src/guards/permission-guard.tsx
Consolidated Layout Synchronization
Single-loop atomic state synchronization hook
src/layouts/hooks/useAccessSync.ts
Zero-Allocation Navigation Cache
Pre-computed static navigation tree provider
src/layouts/hooks/use-filtered-nav-data.ts
Vite Manual Chunking Configuration
10 isolated Rollup vendor chunk groups with boundary matching
vite.config.ts
Isolated Backdrop Theme Component
Lifecycle-bound backdrop instances with zero persistent overlays
src/theme/core/components/backdrop.tsx
Full-Stack & Performance Engineering

Want to scale your web application's speed and SEO?

Let's connect to discuss technical architecture, Core Web Vitals optimization, or full-stack Next.js engineering for your product.