Mars
Mars

Reputation: 936

how to optimize Graphql with Redis

currently I have graphql with mongodb, and now I want add redis layer to optimize server response time.

assume I have schema like this:

type Query{
  book(id: ID):Book
}
type Book{
  # simple fields direct come from mongodb collection Book
  A
  B
  C

  # fields with values generated from simple fields
  X
  Y
  Z

  # fields with aggregated data from other db collections e.g avg/min/max
  L
  M
  N

}

Here is the question: what kind of data should I store in Redis?

1) stringified raw doc from db, keyed by ID

2) put each calculated field into a hash value for redis, each field use HGET from redis

here are my concerns about above options:

1) fields ABC/XYZ should be fine but LMN will result in extra db accesses

2) when query all fields for Book, there will one HGET for each field and most of them are just simple values, maybe wasting time on initiation too many requests?

Upvotes: 2

Views: 2661

Answers (1)

stockholmux
stockholmux

Reputation: 1215

Generally, the idea with caching is to put your data in the way you would want to get it out. However, Redis is in-memory and memory is not cheap - so I wouldn't waste memory on serialization overhead. That being said, just throw the values into a Redis hash (one value per field).

With regards to wasting times on requests (which I assume you mean to Redis), this is not a huge concern. The underlying protocol of Redis is very efficient and you can either do (given a book ID of 'book1234'):

  • HGETALL book1234 to get everything
  • HGET book1234 A B C X Y Z L M N (or your selected fields). HGET is variadic (since Redis 4), so you can just supply the fields you want.

Finally, if you have the ability to install Redis modules, you might want to look at ReJSON, which allows for native handling of JSON data - allowing you to cherry pick the data from the structure. This maybe the best of both worlds.

Upvotes: 3

Related Questions