diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..47cb3b1 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2026-05-03 - Parallelizing Query and Count in Pagination +**Learning:** In Drizzle ORM applications like this codebase, executing the paginated data fetch and total count queries sequentially creates an unnecessary N+1 pattern that increases request latency. +**Action:** When implementing paginated endpoints or queries, always batch independent sequential database operations (like data fetch and count) using `Promise.all()` to parallelize execution and minimize round trips. diff --git a/app/api/products/route.ts b/app/api/products/route.ts index 953d709..730c920 100644 --- a/app/api/products/route.ts +++ b/app/api/products/route.ts @@ -58,19 +58,21 @@ export async function GET(req: NextRequest) { conditions.push(eq(products.isFeatured, true)); } - const result = await db - .select() - .from(products) - .where(and(...conditions)) - .orderBy(desc(products.displayOrder), desc(products.createdAt)) - .limit(limit) - .offset(offset); + // Parallelize data fetch and total count queries to reduce latency + const [result, [{ count }]] = await Promise.all([ + db + .select() + .from(products) + .where(and(...conditions)) + .orderBy(desc(products.displayOrder), desc(products.createdAt)) + .limit(limit) + .offset(offset), - // Get total count for pagination - const [{ count }] = await db - .select({ count: sql`count(*)` }) - .from(products) - .where(and(...conditions)); + db + .select({ count: sql`count(*)` }) + .from(products) + .where(and(...conditions)) + ]); return NextResponse.json({ products: result,