Menu

Your DataLoader fixed the N+1. It may also be giving posts the wrong author.
📰

Your DataLoader fixed the N+1. It may also be giving posts the wrong author.

DEV Community: postgres·Muhammad Adnan·13 days ago
#tZtdqqWh
#devtopostgresql#devto#dev#rows#order
Reading 0:00
15s threshold

You found an N+1 in your GraphQL API: a list of 25 posts, each Post.author resolver running its own SELECT . You added a DataLoader, the query count dropped from 26 to 2, and you moved on.

Here is the batch function most people write first:

const userById = new DataLoader < string , User > ( async ( ids ) => { const { rows } = await db . query < User > ( ' SELECT * FROM users WHERE id = ANY($1::uuid[]) ' , [ ids ], ); return rows ; });

Enter fullscreen mode

Exit fullscreen mode

It passes every test you throw at it. It is also wrong in two ways, and one of them is silent.

Bug 1: Postgres doesn't return rows in the order you asked

DataLoader has one contract: the batch function returns an array in the same order and of the same length as ids . Result 0 goes to whoever asked for ids[0] , result 1 to ids[1] , and so on. DataLoader never looks inside the objects to check.

WHERE id = ANY($1) makes no promise about order.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.