Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -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.
26 changes: 14 additions & 12 deletions app/api/products/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>`count(*)` })
.from(products)
.where(and(...conditions));
db
.select({ count: sql<number>`count(*)` })
.from(products)
.where(and(...conditions))
]);

return NextResponse.json({
products: result,
Expand Down