Cursor rule
.cursor/rules/performance-optimization-patterns.mdcPerformance optimization patterns for database queries, React components, and API efficiency in POS System
Cursor rules
Quality
66/100
Scores the file, not the repository.Length
3,766 words
35 headings · 17 code blocksRepository
118
— · pushed 339 days agoLast changed
3 days ago
First indexed 3 days ago.12345# ⚡ Performance Optimization Patterns67## 🎯 Performance Philosophy for POS Systems89### Critical Performance Metrics10- **Order Creation:** < 500ms from click to confirmation11- **Payment Processing:** < 2s for complete transaction12- **Kitchen Updates:** Real-time (< 100ms propagation)13- **Product Search:** < 200ms for instant results14- **Database Queries:** < 100ms for typical CRUD operations1516### Performance Monitoring Strategy17```typescript18// Performance monitoring utilities19class PerformanceMonitor {20 static timeOperation<T>(name: string, operation: () => Promise<T>): Promise<T> {21 console.time(name);22 return operation().finally(() => console.timeEnd(name));23 }2425 static measureRender(componentName: string) {26 return (Component: React.ComponentType<any>) => {27 return React.memo(Component, (prevProps, nextProps) => {28 const start = performance.now();29 const shouldUpdate = !Object.is(prevProps, nextProps);30 const end = performance.now();3132 if (end - start > 1) {33 console.warn(`${componentName} render check took ${end - start}ms`);34 }3536 return !shouldUpdate;37 });38 };39 }40}41```4243## 🗄️ Database Performance Patterns4445### Optimized Query Patterns46```go47// ✅ CORRECT: Efficient query with proper indexing48func (h *OrderHandler) GetOrdersWithPagination(c *gin.Context) {49 page := getIntParam(c, "page", 1)50 perPage := getIntParam(c, "per_page", 20)51 status := c.Query("status")5253 // Use indexed columns in WHERE clause54 query := `55 SELECT56 o.id, o.order_number, o.status, o.total_amount, o.created_at,57 u.username, t.table_number,58 COUNT(*) OVER() as total_count59 FROM orders o60 LEFT JOIN users u ON o.user_id = u.id61 LEFT JOIN dining_tables t ON o.table_id = t.id62 WHERE ($1 = '' OR o.status = $1)63 AND o.created_at >= CURRENT_DATE - INTERVAL '7 days'64 ORDER BY o.created_at DESC65 LIMIT $2 OFFSET $366 `6768 offset := (page - 1) * perPage69 rows, err := h.db.Query(query, status, perPage, offset)70 // ... handle results71}7273// ✅ CORRECT: Batch insert for order items74func (h *OrderHandler) CreateOrderWithItems(c *gin.Context) {75 tx, err := h.db.Begin()76 if err != nil {77 // handle error78 return79 }80 defer tx.Rollback()8182 // Create order83 var orderID string84 err = tx.QueryRow(`85 INSERT INTO orders (customer_name, order_type, status, total_amount)86 VALUES ($1, $2, $3, $4)87 RETURNING id88 `, req.CustomerName, req.OrderType, "pending", req.TotalAmount).Scan(&orderID)8990 // Batch insert order items (much faster than individual inserts)91 if len(req.Items) > 0 {92 valueStrings := make([]string, 0, len(req.Items))93 valueArgs := make([]interface{}, 0, len(req.Items)*4)9495 for i, item := range req.Items {96 valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d, $%d)",97 i*4+1, i*4+2, i*4+3, i*4+4))98 valueArgs = append(valueArgs, orderID, item.ProductID, item.Quantity, item.Price)99 }100101 stmt := fmt.Sprintf(`102 INSERT INTO order_items (order_id, product_id, quantity, price)103 VALUES %s104 `, strings.Join(valueStrings, ","))105106 _, err = tx.Exec(stmt, valueArgs...)107 if err != nil {108 return // Rollback automatically called109 }110 }111112 err = tx.Commit()113 // ... handle success114}115```116117### Database Connection Optimization118```go119// ✅ CORRECT: Optimized connection pool120func SetupDatabase() *sql.DB {121 db, err := sql.Open("postgres", dsn)122 if err != nil {123 log.Fatal("Failed to connect to database:", err)124 }125126 // Performance tuning for POS workload127 db.SetMaxOpenConns(25) // Limit concurrent connections128 db.SetMaxIdleConns(10) // Keep connections alive129 db.SetConnMaxLifetime(5 * time.Minute) // Rotate connections130 db.SetConnMaxIdleTime(2 * time.Minute) // Close idle connections131132 return db133}134135// ✅ CORRECT: Connection health monitoring136func (h *Handler) healthCheck(c *gin.Context) {137 ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)138 defer cancel()139140 if err := h.db.PingContext(ctx); err != nil {141 c.JSON(http.StatusServiceUnavailable, gin.H{142 "status": "unhealthy",143 "database": "disconnected",144 })145 return146 }147148 c.JSON(http.StatusOK, gin.H{149 "status": "healthy",150 "database": "connected",151 })152}153```154155### Query Optimization Patterns156```sql157-- ✅ CORRECT: Strategic indexes for POS workload158-- Covering index for order listing (includes all needed columns)159CREATE INDEX CONCURRENTLY idx_orders_status_created_covering160ON orders (status, created_at DESC)161INCLUDE (id, order_number, total_amount, customer_name);162163-- Partial index for active orders only164CREATE INDEX CONCURRENTLY idx_orders_active165ON orders (created_at DESC)166WHERE status IN ('pending', 'confirmed', 'preparing', 'ready');167168-- Composite index for order items lookup169CREATE INDEX CONCURRENTLY idx_order_items_order_product170ON order_items (order_id, product_id);171172-- ✅ CORRECT: Efficient aggregation queries173-- Get daily sales summary with single query174SELECT175 DATE(created_at) as sales_date,176 COUNT(*) as order_count,177 SUM(total_amount) as total_sales,178 AVG(total_amount) as avg_order_value,179 COUNT(DISTINCT table_id) as tables_served180FROM orders181WHERE status = 'completed'182 AND created_at >= CURRENT_DATE - INTERVAL '30 days'183GROUP BY DATE(created_at)184ORDER BY sales_date DESC;185```186187## ⚛️ React Performance Optimization188189### Component Optimization Patterns190```typescript191// ✅ CORRECT: Optimized product grid with memoization192import React, { memo, useMemo, useCallback } from 'react'193import { FixedSizeGrid } from 'react-window'194195interface ProductGridProps {196 products: Product[]197 onProductSelect: (product: Product) => void198 selectedProducts: string[]199 searchTerm: string200}201202export const ProductGrid = memo<ProductGridProps>(({203 products,204 onProductSelect,205 selectedProducts,206 searchTerm207}) => {208 // ✅ CORRECT: Memoize filtered products209 const filteredProducts = useMemo(() => {210 if (!searchTerm) return products211212 return products.filter(product =>213 product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||214 product.description?.toLowerCase().includes(searchTerm.toLowerCase())215 )216 }, [products, searchTerm])217218 // ✅ CORRECT: Memoize selected set for O(1) lookup219 const selectedSet = useMemo(() =>220 new Set(selectedProducts), [selectedProducts]221 )222223 // ✅ CORRECT: Stable callback reference224 const handleProductSelect = useCallback((product: Product) => {225 onProductSelect(product)226 }, [onProductSelect])227228 // ✅ CORRECT: Virtual scrolling for large product catalogs229 const Cell = useCallback(({ columnIndex, rowIndex, style }) => {230 const index = rowIndex * 3 + columnIndex231 const product = filteredProducts[index]232233 if (!product) return <div style={style} />234235 return (236 <div style={style}>237 <ProductCard238 product={product}239 isSelected={selectedSet.has(product.id)}240 onSelect={handleProductSelect}241 />242 </div>243 )244 }, [filteredProducts, selectedSet, handleProductSelect])245246 return (247 <FixedSizeGrid248 columnCount={3}249 rowCount={Math.ceil(filteredProducts.length / 3)}250 columnWidth={300}251 rowHeight={200}252 height={600}253 width={920}254 >255 {Cell}256 </FixedSizeGrid>257 )258}, (prevProps, nextProps) => {259 // ✅ CORRECT: Custom comparison for performance260 return (261 prevProps.products === nextProps.products &&262 prevProps.selectedProducts.length === nextProps.selectedProducts.length &&263 prevProps.searchTerm === nextProps.searchTerm264 )265})266```267268### State Management Optimization269```typescript270// ✅ CORRECT: Optimized cart state with reducer271import { useReducer, useCallback, useMemo } from 'react'272273interface CartState {274 items: Map<string, CartItem>275 lastUpdated: number276}277278type CartAction =279 | { type: 'ADD_ITEM'; product: Product; quantity: number }280 | { type: 'UPDATE_QUANTITY'; productId: string; quantity: number }281 | { type: 'REMOVE_ITEM'; productId: string }282 | { type: 'CLEAR' }283284// ✅ CORRECT: Reducer for predictable state updates285const cartReducer = (state: CartState, action: CartAction): CartState => {286 const newItems = new Map(state.items)287288 switch (action.type) {289 case 'ADD_ITEM':290 const existingItem = newItems.get(action.product.id)291 newItems.set(action.product.id, {292 product: action.product,293 quantity: existingItem ? existingItem.quantity + action.quantity : action.quantity,294 subtotal: action.product.price * (existingItem ? existingItem.quantity + action.quantity : action.quantity)295 })296 break297298 case 'UPDATE_QUANTITY':299 if (action.quantity <= 0) {300 newItems.delete(action.productId)301 } else {302 const item = newItems.get(action.productId)303 if (item) {304 newItems.set(action.productId, {305 ...item,306 quantity: action.quantity,307 subtotal: item.product.price * action.quantity308 })309 }310 }311 break312313 case 'REMOVE_ITEM':314 newItems.delete(action.productId)315 break316317 case 'CLEAR':318 newItems.clear()319 break320321 default:322 return state323 }324325 return {326 items: newItems,327 lastUpdated: Date.now()328 }329}330331export const useOptimizedCart = () => {332 const [state, dispatch] = useReducer(cartReducer, {333 items: new Map(),334 lastUpdated: 0335 })336337 // ✅ CORRECT: Memoized calculations only when items change338 const calculations = useMemo(() => {339 const itemsArray = Array.from(state.items.values())340 return {341 total: itemsArray.reduce((sum, item) => sum + item.subtotal, 0),342 itemCount: itemsArray.reduce((count, item) => count + item.quantity, 0),343 isEmpty: state.items.size === 0,344 items: itemsArray345 }346 }, [state.lastUpdated]) // Only recalculate when cart actually changes347348 // ✅ CORRECT: Stable action creators349 const actions = useMemo(() => ({350 addItem: (product: Product, quantity = 1) =>351 dispatch({ type: 'ADD_ITEM', product, quantity }),352 updateQuantity: (productId: string, quantity: number) =>353 dispatch({ type: 'UPDATE_QUANTITY', productId, quantity }),354 removeItem: (productId: string) =>355 dispatch({ type: 'REMOVE_ITEM', productId }),356 clear: () => dispatch({ type: 'CLEAR' })357 }), [])358359 return { ...calculations, ...actions }360}361```362363### Query Optimization with TanStack Query364```typescript365// ✅ CORRECT: Optimized API queries with caching strategy366import { useQuery, useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'367368// Smart caching for products (rarely change)369export const useProducts = (categoryId?: string) => {370 return useQuery({371 queryKey: ['products', categoryId],372 queryFn: () => apiClient.getProducts({ category_id: categoryId }),373 staleTime: 10 * 60 * 1000, // 10 minutes374 gcTime: 30 * 60 * 1000, // 30 minutes375 select: (data) => data.data || [],376 placeholderData: (previousData) => previousData, // Keep UI stable377 })378}379380// Aggressive caching for categories (change infrequently)381export const useCategories = () => {382 return useQuery({383 queryKey: ['categories'],384 queryFn: () => apiClient.getCategories(),385 staleTime: 60 * 60 * 1000, // 1 hour386 gcTime: 24 * 60 * 60 * 1000, // 24 hours387 })388}389390// Real-time polling for kitchen orders391export const useKitchenOrders = () => {392 return useQuery({393 queryKey: ['kitchen-orders'],394 queryFn: () => apiClient.getKitchenOrders(),395 refetchInterval: 5000, // 5 seconds396 staleTime: 0, // Always consider stale for real-time updates397 })398}399400// ✅ CORRECT: Infinite scrolling for order history401export const useOrderHistory = () => {402 return useInfiniteQuery({403 queryKey: ['order-history'],404 queryFn: ({ pageParam = 1 }) =>405 apiClient.getOrders({ page: pageParam, per_page: 50 }),406 getNextPageParam: (lastPage, allPages) => {407 const hasMore = lastPage.data.length === 50408 return hasMore ? allPages.length + 1 : undefined409 },410 staleTime: 2 * 60 * 1000, // 2 minutes411 })412}413414// ✅ CORRECT: Optimistic mutations with rollback415export const useUpdateOrderStatus = () => {416 const queryClient = useQueryClient()417418 return useMutation({419 mutationFn: ({ orderId, status }: { orderId: string; status: string }) =>420 apiClient.updateOrderStatus(orderId, status),421422 onMutate: async ({ orderId, status }) => {423 // Cancel outgoing refetches424 await queryClient.cancelQueries({ queryKey: ['kitchen-orders'] })425426 // Snapshot previous value427 const previousOrders = queryClient.getQueryData(['kitchen-orders'])428429 // Optimistically update430 queryClient.setQueryData(['kitchen-orders'], (old: any) => ({431 ...old,432 data: old?.data?.map((order: any) =>433 order.id === orderId ? { ...order, status } : order434 )435 }))436437 return { previousOrders, orderId, status }438 },439440 onError: (err, variables, context) => {441 // Rollback on error442 if (context?.previousOrders) {443 queryClient.setQueryData(['kitchen-orders'], context.previousOrders)444 }445 },446447 onSettled: () => {448 // Ensure consistency449 queryClient.invalidateQueries({ queryKey: ['kitchen-orders'] })450 },451 })452}453```454455## 🌐 API Performance Patterns456457### Response Optimization458```go459// ✅ CORRECT: Efficient response handling460type APIResponse struct {461 Success bool `json:"success"`462 Message string `json:"message"`463 Data interface{} `json:"data,omitempty"`464 Meta *MetaInfo `json:"meta,omitempty"`465 Error *string `json:"error,omitempty"`466}467468type MetaInfo struct {469 CurrentPage int `json:"current_page,omitempty"`470 PerPage int `json:"per_page,omitempty"`471 Total int `json:"total,omitempty"`472 TotalPages int `json:"total_pages,omitempty"`473}474475// Compressed response middleware476func CompressionMiddleware() gin.HandlerFunc {477 return gin.HandlerFunc(func(c *gin.Context) {478 // Enable gzip compression for responses > 1KB479 c.Header("Content-Encoding", "gzip")480 c.Next()481 })482}483484// ✅ CORRECT: Response caching for static data485func CacheMiddleware(duration time.Duration) gin.HandlerFunc {486 return gin.HandlerFunc(func(c *gin.Context) {487 // Cache headers for categories, products488 if c.Request.Method == "GET" {489 c.Header("Cache-Control", fmt.Sprintf("max-age=%d", int(duration.Seconds())))490 }491 c.Next()492 })493}494```495496### Concurrent Request Handling497```go498// ✅ CORRECT: Concurrent data fetching499func (h *OrderHandler) GetOrderWithDetails(c *gin.Context) {500 orderID := c.Param("id")501502 // Use goroutines for parallel data fetching503 var (504 order *models.Order505 items []models.OrderItem506 payments []models.Payment507 orderErr error508 itemsErr error509 payErr error510 wg sync.WaitGroup511 )512513 // Fetch order details concurrently514 wg.Add(3)515516 go func() {517 defer wg.Done()518 order, orderErr = h.getOrderByID(orderID)519 }()520521 go func() {522 defer wg.Done()523 items, itemsErr = h.getOrderItems(orderID)524 }()525526 go func() {527 defer wg.Done()528 payments, payErr = h.getOrderPayments(orderID)529 }()530531 wg.Wait()532533 // Check for errors534 if orderErr != nil || itemsErr != nil || payErr != nil {535 c.JSON(http.StatusInternalServerError, models.APIResponse{536 Success: false,537 Message: "Failed to fetch order details",538 })539 return540 }541542 // Combine results543 orderWithDetails := models.OrderWithDetails{544 Order: order,545 Items: items,546 Payments: payments,547 }548549 c.JSON(http.StatusOK, models.APIResponse{550 Success: true,551 Data: orderWithDetails,552 })553}554```555556### Request Rate Limiting557```go558// ✅ CORRECT: Rate limiting to prevent abuse559import "golang.org/x/time/rate"560561type RateLimiter struct {562 visitors map[string]*rate.Limiter563 mu sync.RWMutex564 rate rate.Limit565 burst int566}567568func NewRateLimiter(r rate.Limit, b int) *RateLimiter {569 return &RateLimiter{570 visitors: make(map[string]*rate.Limiter),571 rate: r,572 burst: b,573 }574}575576func (rl *RateLimiter) getLimiter(ip string) *rate.Limiter {577 rl.mu.Lock()578 defer rl.mu.Unlock()579580 limiter, exists := rl.visitors[ip]581 if !exists {582 limiter = rate.NewLimiter(rl.rate, rl.burst)583 rl.visitors[ip] = limiter584 }585586 return limiter587}588589func (rl *RateLimiter) RateLimitMiddleware() gin.HandlerFunc {590 return func(c *gin.Context) {591 limiter := rl.getLimiter(c.ClientIP())592593 if !limiter.Allow() {594 c.JSON(http.StatusTooManyRequests, models.APIResponse{595 Success: false,596 Message: "Rate limit exceeded",597 Error: stringPtr("rate_limit_exceeded"),598 })599 c.Abort()600 return601 }602603 c.Next()604 }605}606```607608## 📊 Performance Monitoring & Profiling609610### Frontend Performance Monitoring611```typescript612// ✅ CORRECT: Performance monitoring utilities613class POSPerformanceMonitor {614 private static metrics: Map<string, number[]> = new Map()615616 // Measure API response times617 static async measureAPI<T>(618 operation: string,619 apiCall: () => Promise<T>620 ): Promise<T> {621 const start = performance.now()622623 try {624 const result = await apiCall()625 const duration = performance.now() - start626627 this.recordMetric(operation, duration)628629 if (duration > 1000) {630 console.warn(`Slow API call: ${operation} took ${duration.toFixed(2)}ms`)631 }632633 return result634 } catch (error) {635 const duration = performance.now() - start636 console.error(`Failed API call: ${operation} failed after ${duration.toFixed(2)}ms`)637 throw error638 }639 }640641 // Monitor component render times642 static measureRender(componentName: string) {643 return function<T extends Record<string, any>>(644 Component: React.ComponentType<T>645 ): React.ComponentType<T> {646 return React.memo(Component, (prevProps, nextProps) => {647 const start = performance.now()648 const shouldUpdate = !shallowEqual(prevProps, nextProps)649 const end = performance.now()650651 POSPerformanceMonitor.recordMetric(`${componentName}_render_check`, end - start)652653 return !shouldUpdate654 })655 }656 }657658 private static recordMetric(name: string, value: number) {659 const existing = this.metrics.get(name) || []660 existing.push(value)661662 // Keep only last 100 measurements663 if (existing.length > 100) {664 existing.shift()665 }666667 this.metrics.set(name, existing)668 }669670 // Get performance summary671 static getPerformanceSummary() {672 const summary: Record<string, any> = {}673674 this.metrics.forEach((values, name) => {675 const avg = values.reduce((sum, val) => sum + val, 0) / values.length676 const max = Math.max(...values)677 const min = Math.min(...values)678679 summary[name] = { avg, max, min, count: values.length }680 })681682 return summary683 }684}685686// Usage in components687export const ProductCard = POSPerformanceMonitor.measureRender('ProductCard')(688 ({ product, onSelect }) => {689 // Component implementation690 }691)692```693694### Backend Performance Profiling695```go696// ✅ CORRECT: Request timing middleware697func TimingMiddleware() gin.HandlerFunc {698 return gin.HandlerFunc(func(c *gin.Context) {699 start := time.Now()700701 // Process request702 c.Next()703704 // Calculate duration705 duration := time.Since(start)706707 // Log slow requests708 if duration > 500*time.Millisecond {709 log.Printf("SLOW REQUEST: %s %s took %v",710 c.Request.Method, c.Request.URL.Path, duration)711 }712713 // Add timing header714 c.Header("X-Response-Time", duration.String())715716 // Metrics collection (integrate with your monitoring system)717 collectMetric(fmt.Sprintf("request_duration_%s", c.Request.URL.Path), duration)718 })719}720721// Database query profiling722func (h *Handler) profileQuery(query string, args ...interface{}) (*sql.Rows, error) {723 start := time.Now()724 rows, err := h.db.Query(query, args...)725 duration := time.Since(start)726727 if duration > 100*time.Millisecond {728 log.Printf("SLOW QUERY: %s took %v", query, duration)729 }730731 return rows, err732}733```734735## 🎯 Performance Optimization Checklist736737### Database Optimization738- [ ] **Indexes Created:** All frequently queried columns have appropriate indexes739- [ ] **Query Analysis:** EXPLAIN ANALYZE used to verify query performance740- [ ] **Connection Pooling:** Properly configured pool sizes and timeouts741- [ ] **Batch Operations:** Multiple inserts/updates use batch processing742- [ ] **Pagination:** Large result sets use LIMIT/OFFSET or cursor pagination743744### React Optimization745- [ ] **Component Memoization:** Heavy components use React.memo with custom comparison746- [ ] **State Structure:** State is normalized and minimizes re-renders747- [ ] **List Rendering:** Large lists use virtualization or pagination748- [ ] **Bundle Size:** Code splitting implemented for large components749- [ ] **Image Optimization:** Images are properly sized and compressed750751### API Optimization752- [ ] **Response Caching:** Static data has appropriate cache headers753- [ ] **Compression:** Responses are gzipped for large payloads754- [ ] **Rate Limiting:** API endpoints protected from abuse755- [ ] **Concurrent Processing:** I/O operations are handled concurrently756- [ ] **Error Handling:** Timeouts and circuit breakers implemented757758### Development Tools759```bash760# Performance testing commands761npm run build:analyze # Bundle size analysis762npm run lighthouse # Web performance audit763go tool pprof # Go profiling764```765766### Production Monitoring767- **APM Integration:** Use tools like New Relic, DataDog, or Sentry768- **Database Monitoring:** Track slow queries and connection pool usage769- **Real User Monitoring:** Track actual user experience metrics770- **Alert Thresholds:** Set up alerts for performance degradation771772## 🚀 Performance-First Development Mindset773774### 1. Performance-Driven Architecture Decisions775```typescript776// ✅ PERFORMANCE-FIRST: Architecture decisions with performance implications777class PerformanceFirstArchitecture {778 // Performance-aware component design779 static createPerformantComponent<TProps>(780 config: PerformanceComponentConfig<TProps>781 ): React.FC<TProps> {782 // Intelligent memoization based on performance profile783 const memoStrategy = config.performance_profile === 'high_frequency'784 ? 'shallow_comparison' // Fast for frequent updates785 : config.performance_profile === 'complex_data'786 ? 'deep_comparison' // Thorough for complex objects787 : 'custom_comparison' // Custom logic for specific needs788789 return React.memo((props: TProps) => {790 // Performance monitoring built-in791 const renderStart = performance.now()792793 // Lazy load heavy dependencies794 const HeavyComponent = useMemo(() => {795 if (config.requires_heavy_component) {796 return React.lazy(() => import(config.heavy_component_path))797 }798 return null799 }, [])800801 // Efficient state management802 const optimizedState = usePerformantState(config.state_config)803804 // Performance budgets enforcement805 const result = config.render(props, optimizedState)806807 const renderTime = performance.now() - renderStart808 if (renderTime > config.performance_budget) {809 console.warn(`Component ${config.name} exceeded performance budget: ${renderTime}ms > ${config.performance_budget}ms`)810 PerformanceMonitor.recordSlowRender(config.name, renderTime, props)811 }812813 return result814 }, this.createMemoComparison(memoStrategy))815 }816817 // Performance-aware API design818 static createPerformantAPI<TRequest, TResponse>(819 config: PerformanceAPIConfig<TRequest, TResponse>820 ): PerformantAPI<TRequest, TResponse> {821 return {822 execute: async (request: TRequest): Promise<TResponse> => {823 const executionStart = performance.now()824825 // Request optimization826 const optimizedRequest = await this.optimizeRequest(request, config)827828 // Concurrent execution for independent operations829 const [830 validationResult,831 cacheResult,832 authResult833 ] = await Promise.all([834 config.validate ? this.validateRequest(optimizedRequest) : Promise.resolve(true),835 config.cacheable ? this.checkCache(optimizedRequest) : Promise.resolve(null),836 config.requires_auth ? this.validateAuth(optimizedRequest) : Promise.resolve(true)837 ])838839 if (cacheResult) {840 return cacheResult // Early return from cache841 }842843 // Execute business logic with timeout844 const result = await Promise.race([845 config.execute(optimizedRequest),846 this.createTimeout(config.timeout || 5000)847 ])848849 const executionTime = performance.now() - executionStart850851 // Performance analysis and alerting852 if (executionTime > config.performance_threshold) {853 PerformanceMonitor.recordSlowAPI(config.endpoint, executionTime, {854 request_size: JSON.stringify(request).length,855 response_size: JSON.stringify(result).length,856 cache_hit: false857 })858 }859860 return result861 }862 }863 }864}865```866867### 2. Real-Time Performance Monitoring868```typescript869// ✅ REAL-TIME: Advanced performance monitoring with business intelligence870class BusinessPerformanceMonitor {871 // Real-time performance dashboard872 static createRealtimeMonitor(): RealtimePerformanceMonitor {873 return {874 // Business-critical performance metrics875 trackBusinessMetrics: () => {876 return {877 order_creation_speed: this.measureOrderCreationSpeed(),878 payment_processing_speed: this.measurePaymentSpeed(),879 kitchen_efficiency: this.measureKitchenThroughput(),880 customer_wait_times: this.measureCustomerExperience(),881882 // Advanced metrics883 revenue_per_second: this.calculateRevenueVelocity(),884 table_turnover_rate: this.calculateTableEfficiency(),885 staff_productivity: this.calculateStaffEfficiency(),886 system_reliability: this.calculateUptimeScore()887 }888 },889890 // Predictive performance analysis891 predictPerformanceIssues: async (): Promise<PredictiveAlert[]> => {892 const currentMetrics = await this.gatherCurrentMetrics()893 const historicalPatterns = await this.getHistoricalPatterns()894895 const predictions: PredictiveAlert[] = []896897 // Database performance prediction898 if (currentMetrics.database.connection_count > historicalPatterns.database.avg_connections * 0.8) {899 predictions.push({900 type: 'database_capacity',901 severity: 'warning',902 predicted_impact: 'Order processing may slow down in 15-30 minutes',903 recommendation: 'Scale database connections or implement connection pooling',904 confidence: this.calculatePredictionConfidence(currentMetrics.database),905 business_impact: await this.calculateBusinessImpact('database_slowdown')906 })907 }908909 // Kitchen bottleneck prediction910 const kitchenLoad = await this.calculateKitchenLoad()911 if (kitchenLoad.projected_queue_time > 20) { // minutes912 predictions.push({913 type: 'kitchen_bottleneck',914 severity: 'high',915 predicted_impact: 'Customer complaints likely in next 30 minutes',916 recommendation: 'Alert kitchen manager to optimize workflow or add staff',917 confidence: this.calculateKitchenLoadPrediction(kitchenLoad),918 business_impact: await this.calculateBusinessImpact('customer_satisfaction_drop')919 })920 }921922 return predictions923 },924925 // Performance optimization recommendations926 generateOptimizationRecommendations: async (): Promise<OptimizationRecommendation[]> => {927 const performanceAnalysis = await this.analyzeSystemPerformance()928 const recommendations: OptimizationRecommendation[] = []929930 // Database optimization opportunities931 if (performanceAnalysis.database.slow_queries.length > 0) {932 recommendations.push({933 category: 'database',934 priority: 'high',935 title: 'Optimize Slow Database Queries',936 description: `${performanceAnalysis.database.slow_queries.length} queries taking > 100ms`,937 implementation: {938 effort: 'medium',939 estimated_time: '2-4 hours',940 expected_improvement: '20-40% faster order processing',941 breaking_changes: false942 },943 specific_actions: [944 'Add index on orders(created_at, status)',945 'Optimize JOIN query in getOrdersWithItems',946 'Implement query result caching for product catalog'947 ]948 })949 }950951 // Frontend performance opportunities952 if (performanceAnalysis.frontend.bundle_size > 2048) { // KB953 recommendations.push({954 category: 'frontend',955 priority: 'medium',956 title: 'Reduce Bundle Size',957 description: `Bundle size is ${performanceAnalysis.frontend.bundle_size}KB, affecting load times`,958 implementation: {959 effort: 'medium',960 estimated_time: '4-6 hours',961 expected_improvement: '30% faster initial page load',962 breaking_changes: false963 },964 specific_actions: [965 'Implement code splitting for role-specific interfaces',966 'Lazy load non-critical components',967 'Tree shake unused dependencies',968 'Optimize images and assets'969 ]970 })971 }972973 return recommendations974 }975 }976 }977978 // Performance regression detection979 static createRegressionDetector(): PerformanceRegressionDetector {980 return {981 detectRegressions: async (deployment: DeploymentMetrics): Promise<RegressionAnalysis> => {982 const baselineMetrics = await this.getBaselineMetrics()983 const regressions: PerformanceRegression[] = []984985 // Response time regression986 const responseTimeIncrease = (deployment.avg_response_time - baselineMetrics.avg_response_time) / baselineMetrics.avg_response_time987 if (responseTimeIncrease > 0.1) { // 10% increase988 regressions.push({989 metric: 'response_time',990 current_value: deployment.avg_response_time,991 baseline_value: baselineMetrics.avg_response_time,992 regression_percentage: responseTimeIncrease * 100,993 business_impact: await this.calculateResponseTimeImpact(responseTimeIncrease),994 severity: responseTimeIncrease > 0.25 ? 'critical' : 'warning'995 })996 }997998 // Database query performance regression999 const queryPerformanceRegression = this.analyzeQueryRegression(deployment.database_metrics, baselineMetrics.database_metrics)1000 if (queryPerformanceRegression.has_regression) {1001 regressions.push({1002 metric: 'database_performance',1003 current_value: queryPerformanceRegression.current_avg_time,1004 baseline_value: queryPerformanceRegression.baseline_avg_time,1005 regression_percentage: queryPerformanceRegression.percentage_increase,1006 affected_queries: queryPerformanceRegression.affected_queries,1007 business_impact: await this.calculateDatabaseImpact(queryPerformanceRegression),1008 severity: queryPerformanceRegression.percentage_increase > 50 ? 'critical' : 'warning'1009 })1010 }10111012 return {1013 has_regressions: regressions.length > 0,1014 regressions,1015 overall_performance_score: this.calculatePerformanceScore(deployment),1016 recommendation: this.generateRegressionRecommendation(regressions)1017 }1018 },10191020 // Automatic rollback triggers1021 shouldTriggerRollback: (regressions: PerformanceRegression[]): RollbackDecision => {1022 const criticalRegressions = regressions.filter(r => r.severity === 'critical')1023 const highBusinessImpact = regressions.some(r => r.business_impact.revenue_impact > 1000) // $1000+ impact10241025 return {1026 should_rollback: criticalRegressions.length > 0 || highBusinessImpact,1027 reason: criticalRegressions.length > 01028 ? 'Critical performance regression detected'1029 : highBusinessImpact1030 ? 'High business impact performance regression'1031 : 'Performance within acceptable bounds',1032 confidence: this.calculateRollbackConfidence(regressions),1033 estimated_impact_if_not_rolled_back: this.estimateOngoingImpact(regressions)1034 }1035 }1036 }1037 }1038}1039```10401041### 3. Automated Performance Optimization1042```typescript1043// ✅ AUTOMATION: Self-optimizing system with ML-powered insights1044class AutomatedPerformanceOptimizer {1045 // Machine learning performance optimizer1046 static createMLOptimizer(): MLPerformanceOptimizer {1047 return {1048 // Intelligent caching decisions1049 optimizeCachingStrategy: async (): Promise<CacheOptimization> => {1050 const accessPatterns = await this.analyzeAccessPatterns()1051 const cachePerformance = await this.analyzeCacheHitRates()10521053 return {1054 recommended_cache_sizes: {1055 products: this.calculateOptimalCacheSize(accessPatterns.products),1056 orders: this.calculateOptimalCacheSize(accessPatterns.orders),1057 users: this.calculateOptimalCacheSize(accessPatterns.users)1058 },10591060 cache_eviction_policies: {1061 products: 'LRU', // Least recently used for menu items1062 orders: 'TTL', // Time-based for order data1063 users: 'LFU' // Least frequently used for user profiles1064 },10651066 dynamic_ttl_recommendations: {1067 products: this.calculateDynamicTTL(accessPatterns.products),1068 categories: this.calculateDynamicTTL(accessPatterns.categories),1069 settings: this.calculateDynamicTTL(accessPatterns.settings)1070 }1071 }1072 },10731074 // Database query optimization1075 optimizeDatabaseQueries: async (): Promise<QueryOptimization> => {1076 const queryPatterns = await this.analyzeQueryPatterns()1077 const indexUsage = await this.analyzeIndexUsage()10781079 return {1080 recommended_indexes: [1081 ...this.findMissingIndexes(queryPatterns),1082 ...this.optimizeExistingIndexes(indexUsage)1083 ],10841085 query_rewrites: [1086 ...this.identifySuboptimalQueries(queryPatterns),1087 ...this.suggestJoinOptimizations(queryPatterns)1088 ],10891090 partitioning_recommendations: this.analyzePartitioningOpportunities(queryPatterns),10911092 connection_pool_optimization: {1093 optimal_pool_size: this.calculateOptimalPoolSize(queryPatterns),1094 connection_timeout: this.calculateOptimalTimeout(queryPatterns),1095 idle_timeout: this.calculateOptimalIdleTimeout(queryPatterns)1096 }1097 }1098 },10991100 // Frontend performance optimization1101 optimizeFrontendPerformance: async (): Promise<FrontendOptimization> => {1102 const userInteractions = await this.analyzeUserInteractions()1103 const componentUsage = await this.analyzeComponentUsage()11041105 return {1106 code_splitting_recommendations: {1107 route_based: this.recommendRouteSplitting(userInteractions),1108 component_based: this.recommendComponentSplitting(componentUsage),1109 vendor_splitting: this.recommendVendorSplitting()1110 },11111112 lazy_loading_opportunities: [1113 ...this.identifyLazyLoadComponents(componentUsage),1114 ...this.identifyLazyLoadImages(userInteractions),1115 ...this.identifyLazyLoadData(userInteractions)1116 ],11171118 preloading_strategy: {1119 critical_resources: this.identifyCriticalResources(userInteractions),1120 prefetch_candidates: this.identifyPrefetchCandidates(userInteractions),1121 preconnect_domains: this.identifyPreconnectDomains()1122 }1123 }1124 }1125 }1126 }11271128 // Continuous performance improvement1129 static createContinuousImprovement(): ContinuousPerformanceImprovement {1130 return {1131 // Weekly performance reviews1132 weeklyPerformanceReview: async (): Promise<WeeklyPerformanceReport> => {1133 const weeklyMetrics = await this.gatherWeeklyMetrics()1134 const improvements = await this.identifyImprovements()1135 const regressions = await this.identifyRegressions()11361137 return {1138 overall_trend: this.calculatePerformanceTrend(weeklyMetrics),1139 key_improvements: improvements,1140 performance_regressions: regressions,1141 business_impact: {1142 revenue_impact: this.calculateRevenueImpact(weeklyMetrics),1143 customer_satisfaction: this.calculateSatisfactionImpact(weeklyMetrics),1144 operational_efficiency: this.calculateEfficiencyImpact(weeklyMetrics)1145 },1146 recommended_actions: this.generateWeeklyRecommendations(weeklyMetrics)1147 }1148 },11491150 // Performance goal setting and tracking1151 setPerformanceGoals: (goals: PerformanceGoals): PerformanceTracker => {1152 return {1153 trackProgress: async (): Promise<GoalProgress> => {1154 const currentMetrics = await this.getCurrentMetrics()11551156 return {1157 response_time: {1158 goal: goals.response_time,1159 current: currentMetrics.avg_response_time,1160 progress: this.calculateProgress(goals.response_time, currentMetrics.avg_response_time),1161 trend: this.calculateTrend(currentMetrics.response_time_history)1162 },11631164 throughput: {1165 goal: goals.throughput,1166 current: currentMetrics.requests_per_second,1167 progress: this.calculateProgress(goals.throughput, currentMetrics.requests_per_second),1168 trend: this.calculateTrend(currentMetrics.throughput_history)1169 },11701171 error_rate: {1172 goal: goals.error_rate,1173 current: currentMetrics.error_rate,1174 progress: this.calculateProgress(goals.error_rate, currentMetrics.error_rate),1175 trend: this.calculateTrend(currentMetrics.error_rate_history)1176 }1177 }1178 },11791180 generateImprovementPlan: async (): Promise<ImprovementPlan> => {1181 const progress = await this.trackProgress()1182 const gaps = this.identifyPerformanceGaps(progress)11831184 return {1185 priority_actions: this.prioritizeImprovements(gaps),1186 timeline: this.createImprovementTimeline(gaps),1187 resource_requirements: this.calculateResourceNeeds(gaps),1188 expected_outcomes: this.predictImprovementOutcomes(gaps)1189 }1190 }1191 }1192 }1193 }1194 }1195}1196```11971198### Advanced Performance Development Commands1199```bash1200# Performance monitoring1201npm run perf:monitor # Real-time performance monitoring1202npm run perf:analyze # Comprehensive performance analysis1203npm run perf:regression # Check for performance regressions1204npm run perf:optimize # Run automated optimizations12051206# Performance testing1207npm run perf:load-test # Load testing with realistic scenarios1208npm run perf:stress-test # Stress testing to find breaking points1209npm run perf:benchmark # Benchmark critical operations1210npm run perf:profile # Profile CPU and memory usage12111212# Performance budgets1213npm run perf:budget-check # Validate performance budgets1214npm run perf:bundle-analyze # Analyze bundle size and composition1215npm run perf:lighthouse # Run Lighthouse performance audit1216npm run perf:vitals # Check Core Web Vitals12171218# Backend performance1219go run perf:database # Database performance analysis1220go run perf:api # API endpoint performance testing1221go run perf:memory # Memory usage profiling1222go run perf:cpu # CPU usage profiling1223```
Also in madebyaris/poinf-of-sales
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| madebyaris/poinf-of-sales.cursor/rules/admin-interface-patterns.mdc · 118 | Cursor rules | stylearchsecurityapi+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/api-patterns.mdc · 118 | Cursor rules | lint-formatstylesecuritydatabase+3 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/authentication-and-security-patterns.mdc · 118 | Cursor rules | setupteststylesecurity+4 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/backend-golang.mdc · 118 | Cursor rules | testlint-formatstylearch+5 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/business-logic-patterns.mdc · 118 | Cursor rules | teststyledatabaseperformance+1 | 50/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/database-patterns.mdc · 118 | Cursor rules | stylearchtypessecurity+2 | 62/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/development-workflow.mdc · 118 | Cursor rules | setupbuildteststyle+3 | 86/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/docker-deployment.mdc · 118 | Cursor rules | setupbuildteststyle+8 | 77/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/frontend-react.mdc · 118 | Cursor rules | buildtestlint-formatstyle+4 | 69/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/makefile-scripting.mdc · 118 | Cursor rules | setuplint-formatstylearch+2 | 81/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/project-architecture.mdc · 118 | Cursor rules | setupteststylearch+6 | 78/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/react-native-mobile-patterns.mdc · 118 | Cursor rules | buildstylearchui+2 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/role-based-access-patterns.mdc · 118 | Cursor rules | styletypessecuritydatabase+2 | 58/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/tech-debt-prevention.mdc · 118 | Cursor rules | styletesting-strategyui | 50/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/testing-patterns.mdc · 118 | Cursor rules | setupteststylearch+4 | 74/100 | 3 days ago | |
| madebyaris/poinf-of-sales.cursor/rules/user-journey-optimization.mdc · 118 | Cursor rules | styleperformanceagent-behaviour | 50/100 | 3 days ago |
Diff against .cursor/rules/admin-interface-patterns.mdc Diff against .cursor/rules/api-patterns.mdc Diff against .cursor/rules/authentication-and-security-patterns.mdc Diff against .cursor/rules/backend-golang.mdc Diff against .cursor/rules/business-logic-patterns.mdc Diff against .cursor/rules/database-patterns.mdc Diff against .cursor/rules/development-workflow.mdc Diff against .cursor/rules/docker-deployment.mdc Diff against .cursor/rules/frontend-react.mdc Diff against .cursor/rules/makefile-scripting.mdc Diff against .cursor/rules/project-architecture.mdc Diff against .cursor/rules/react-native-mobile-patterns.mdc Diff against .cursor/rules/role-based-access-patterns.mdc Diff against .cursor/rules/tech-debt-prevention.mdc Diff against .cursor/rules/testing-patterns.mdc Diff against .cursor/rules/user-journey-optimization.mdc
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 3 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 3 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 3 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 3 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 3 days ago |
