When and How to use GraphQL with Microservice Architecture

Fabrizio Fenoglio picture Fabrizio Fenoglio · Jun 28, 2016 · Viewed 35.2k times · Source

I'm trying to understand where GraphQL is most suitable to use within a Microservice architecture.

There is some debate about having only 1 GraphQL schema that works as API Gateway proxying the request to the targeted microservices and coercing their response. Microservices still would use REST / Thrift protocol for communication though.

Another approach is instead to have multiple GraphQL schemas one per microservice. Having a smaller API Gateway server that route the request to the targeted microservice with all the information of the request + the GraphQL query.

1st Approach

Having 1 GraphQL Schema as an API Gateway will have a downside where every time you change your microservice contract input/output, we have to change the GraphQL Schema accordingly on the API Gateway Side.

2nd Approach

If using Multiple GraphQL Schema per microservices, make sense in a way because GraphQL enforces a schema definition, and the consumer will need to respect input/output given from the microservice.

Questions

  • Where do you find GraphQL the right fit for designing microservice architecture?

  • How would you design an API Gateway with a possible GraphQL implementation?

Answer

helfer picture helfer · Jun 28, 2016

Definitely approach #1.

Having your clients talk to multiple GraphQL services (as in approach #2) entirely defeats the purpose of using GraphQL in the first place, which is to provide a schema over your entire application data to allow fetching it in a single roundtrip.

Having a shared nothing architecture might seem reasonable from the microservices perspective, but for your client-side code it is an absolute nightmare, because every time you change one of your microservices, you have to update all of your clients. You will definitely regret that.

GraphQL and microservices are a perfect fit, because GraphQL hides the fact that you have a microservice architecture from the clients. From a backend perspective, you want to split everything into microservices, but from a frontend perspective, you would like all your data to come from a single API. Using GraphQL is the best way I know of that lets you do both. It lets you split up your backend into microservices, while still providing a single API to all your application, and allowing joins across data from different services.

If you don't want to use REST for your microservices, you can of course have each of them have its own GraphQL API, but you should still have an API gateway. The reason people use API gateways is to make it more manageable to call microservices from client applications, not because it fits well into the microservices pattern.