How can I limit N+1 queries on an Absinthe Subscription?

Let’s say I have a subscription:

subscription CommentCreated($postId: String!) {
  commentCreated(postId: $postId) {
    id
    body
    user {
      username
    }
  }
}

When I make N subscriptions via Graphiql and create a new comment, I see N + 1 calls to the DB to fetch the user(1 for the mutation + N for the subscriptions). Is there anyway to prefetch that data so I’m not doing a DB call per subscription connection, but only per mutation?

Can you elaborate on the situation more? Why would you subscribe to a post more than once?

A single user wouldn’t have more than one subscription, but if 100 users are subscribed to a post, then every comment would make 101 db hits to fetch the same user info.

I recommend 2 things.

  1. Use Dataloader https://hexdocs.pm/absinthe/dataloader.html to have data pre-fetched. There is more info here: https://hexdocs.pm/dataloader/Dataloader.html but also search this forum for examples.

  2. use context_id of subscription resolution to use same document for different connections. https://hexdocs.pm/absinthe/subscriptions.html#de-duplicating-updates

3 Likes

I’ve already got dataloader, but that context_id is exactly what I’m looking for! I just read through that article earlier today, not sure how I missed that. Thanks!

2 Likes

I wrote misinformation but cannot edit my previous post. Dataloader does not “pre-fetch”. It actually “batches”.