diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..9ab54bd --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-05-18 - Fix N+1 Query in getUserOrders +**Learning:** Found an N+1 query vulnerability when iterating over fetched entities and dispatching separate requests to fetch child entities (fetching orderItems for each order). In serverless setups using Drizzle ORM this causes a database request amplification that degrades performance severely at scale. +**Action:** Replace `Promise.all` loops running queries with single batch requests utilizing Drizzle's `inArray` operator, then map the data back using reduce maps grouping by foreign key. diff --git a/lib/actions/orders.ts b/lib/actions/orders.ts index 3d367bb..223b4ad 100644 --- a/lib/actions/orders.ts +++ b/lib/actions/orders.ts @@ -3,7 +3,7 @@ import { db } from "@/lib/db"; import { orders, orderItems, products, productVariants, user, bargainSessions } from "@/lib/db/schema"; import { getServerSession } from "@/lib/auth-server"; -import { eq, desc, sql, and, isNull } from "drizzle-orm"; +import { eq, desc, sql, and, isNull, inArray } from "drizzle-orm"; import { revalidatePath } from "next/cache"; import { markCouponUsed } from "./admin"; @@ -297,20 +297,31 @@ export async function getUserOrders() { .where(eq(orders.userId, session.user.id)) .orderBy(desc(orders.createdAt)); - // Fetch items for each order - const ordersWithItems = await Promise.all( - userOrders.map(async (order) => { - const items = await db - .select() - .from(orderItems) - .where(eq(orderItems.orderId, order.id)); + if (userOrders.length === 0) { + return []; + } - return { - ...order, - items, - }; - }) - ); + // ⚡ Bolt Optimization: Fix N+1 query problem by batch fetching all related order items + // Reduces DB queries from O(N) to O(1) where N is number of orders + const orderIds = userOrders.map((order) => order.id); + const allItems = await db + .select() + .from(orderItems) + .where(inArray(orderItems.orderId, orderIds)); + + // Group items by orderId to avoid nested loops mapping them + const itemsByOrderId = allItems.reduce((acc, item) => { + if (!acc[item.orderId]) { + acc[item.orderId] = []; + } + acc[item.orderId].push(item); + return acc; + }, {} as Record); + + const ordersWithItems = userOrders.map((order) => ({ + ...order, + items: itemsByOrderId[order.id] || [], + })); return ordersWithItems; } diff --git a/lib/bargain-discount.ts b/lib/bargain-discount.ts index c8c0862..f6a6df6 100644 --- a/lib/bargain-discount.ts +++ b/lib/bargain-discount.ts @@ -9,5 +9,5 @@ export function formatBargainDiscountLabel(maxBargainDiscount: string | number | ? value.toLocaleString("en-IN") : value.toLocaleString("en-IN", { maximumFractionDigits: 2 }); - return `Bargain upto ₹${formatted}`; + return `Bargain up to ₹${formatted}`; }