Architecture for avoiding repeated data in GraphQL

Viewed 215

I have a application where the same data is present in many places in the graph and need to optimize the data queries to avoid processing and sending the same data too often.

As an example consider the following pseudo schema:

type Group {
  name: String
  members: [Person]
}
type Person {
  name: String
  email: String
  avatar: Avatar
  follows: [Person]
  followedBy: [Person]
  contacts: [Person]
  groups: [Group]
  bookmarks: [Bookmark]
  sentMessages: [Message]
  receivedMessages: [Message]
}
type Message {
  text: String
  author: Person
  recipients: [Person]
}
type Bookmark {
  message: Message
}

Querying a users data can easily contain hundreds, if not thousands, of Person-objects even though it the small circle of friends/contacts/follows only contains tens of distict users.

In my real implementation about 80% of each GraphQL query (in bytes) is redundant and considering that the client does many different queries in the same space above 90% of all data transferred and processed is redundant.

How could I improve the model so that I don't have to load the same data again and again without complicating the client too much?

I'm using Apollo for both GraphQL client and server.

1 Answers

Use/implement pagination (instead of just arrays) for relations - this way you can query for count/total (render it without array processing) and array of ids only - usually there is no need to query/join person table (DB) at all.

Render list of Person components (react?) using passed id prop only ... only rendered Person fetches for more details (if not cached, use batching to merge requests) consumed/rendered inside.

Related