This article covers our experience in PayPal Expand GraphQL All the knowledge I learned when I was in school , And will be deployed in your company as GraphQL Guide to .
A year ago. , We wrote “ GraphQL：PayPal Checkout Success stories of ”, It covers what we learned from REST To batch REST To GraphQL History . A lot of things have changed since then ！ This article is about PayPal structure GraphQL API When you get A series of Part of best practices and observations .
A year ago. , Use GraphQL Very few of our products . Although we are PayPal Checkout It's a success on , But no infrastructure , Tools , Training or support . Despite these gaps , but GraphQL Still taking off like a rocket . At the time of writing , We have 50 One use GraphQL Different products ！
It's very fast , Like other technological changes , Enterprise expansion has nothing to do with horizontal expansion or paying a lot of money for servers or cloud computing . Extension staff , Tools and processes are the most challenging .
In the deployment GraphQL Before , It's important to have a deep understanding of your company , And reflect on who you are , What to do and what are the advantages and disadvantages .
PayPal stay 2013–2015 Moved to Node. It changed the whole company , And improved the way we make and transport our products . One C ++ Simple content changes to a single application will take weeks to deploy . Now? , Developers can experiment in a few minutes , Iterate and launch new product features .
It didn't happen overnight , It's not by chance . stay Node Join in PayPal Before ,Bill Scott Put forward The use of LeanUX Building the product vision , Iteration and learning are the key . stay LeanUX in ,UI Bits are experimental and disposable . If the experiment doesn't work well , Please keep iterating ！Node.js Is the key to success .
2014 year , We launched Kraken, This is a Express One on top Group Library , Designed through configurable middleware , Security default settings ,dust.js Renderers and content localization for your application “ Offer some help ”. Now? , The team is building the client React Applications , And the application is deployed to CDN Static packages for , Instead of code running in the server cluster .
about API, We use BFF（backend-for-frontend） Pattern . Even though they are very professional , And allow developers to iterate , But they are tightly coupled and can't be reused well . As a result, we have a lot of teams that iterate and build the same things over and over again ！ structure BFF API It's not an easy thing . Usually , They contain a lot of choreography logic , In these logics , You need to go from 5、10、15 Getting data from different services , Normalize these responses , discarded 95％ Response , And then map the data , Filter and categorize as needed data . Writing this code doesn't make good use of our developers' time . This tight coupling and lack of reuse is a problem for us .
GraphQL Can you help ？ yes !
Developer experience > performance
Before jumping into the production ready items list , We should reset our expectations . When you first contact GraphQL when , The main benefit is that less data is transmitted over the network , So it's faster , Higher performance applications .
Large companies will GraphQL Place on existing REST Above services . The result is yours GraphQL The query will only match the slowest REST As fast as the service .GraphQL Allows you to get everything you need in a round trip . If there is idle between the client and the server , Can reduce round trip and delay . however , It's not a commitment you can make for everyone .
After a while , You'll realize that developers The benefits of experience and flexibility are far more compelling than performance .
GraphQL Friendly to human beings . Use GraphQL, Developers can base on fields instead of endpoints , Domain or complex join . Developers can traverse the graph to choose the user's name ,60x60 My profile photos , Main shipping address and credit card , Instead of calling 6-10 Different services . New employees love it . If you know JSON What does it look like , Please remove double quotes and commas , Then you can query GraphQL API. Your UI Developers love it , Because it's product centric , It's declarative , And has a rich tool set , Reduces integration friction and improves confidence .
When you will GraphQL When recommending to company leaders and teams , Pay attention to the experience of developers , Productivity and flexibility . otherwise , You may disappoint them .
GraphQL At the edge of the stack
stay PayPal, Our core services are developed by an independent back-end team , Our product team builds BFF API, To organize data from these basic core services . first , We think “ GraphQL It should be everywhere ”！
After a lot of experiments and reflections , We found that GraphQL The edge of the stack glows the most .
GraphQL Product centered , Should be influenced by your product team （ Or development ）.GraphQL The mode should be in When designing, first Advice from the product team . Back end developers should not design them in isolation .GraphQL Be good at it . therefore ,GraphQL The edge of the stack that best suits you , And can be compared with REST Working together .
Open in the company GraphQL
well , It's time to do this ！ This section is used in your company GraphQL List of .
First , You need to lay the foundation for the product team .GraphQL New and exciting , There are many open-ended questions and insights . Almost nothing is static . You have many choices ！
Building the foundation
stay PayPal,GraphQL Already with for BFF API and UI The product team that has made a contribution stands out . We are GraphQL API Use Node.js. Like many other companies , We use Apollo Of Open source libraries and tools .Apollo Have a dedicated team to build and maintain these tools , So they're first-class in terms of first-class documentation . We use apollo The server , And in specific PayPal Put into use when the production is ready , For example, logging and detection , Authentication , Error handling and rate limiting .
If you have any unique requirements , Please create open source libraries that are compatible with （ for example Apollo） Modules and plug-ins used together . Don't create deep abstractions or hide complexity from developers . Keep it available for Google！
Make sure that the architect and API Designer support GraphQL, To help you extend design reviews and enforce standards . They probably have designed REST API many years .GraphQL Is different . At first , You may encounter resistance . Push it . You need to spend time with them outlining the differences , And challenge them to do it differently API Design ： No version control , Embrace charts instead of using ID Create relationships , No, HATEOAS link . By inviting architects , You will not be the only subject matter expert , It will be GraphQL Bring legitimacy .
You need to set some design criteria . Create a document and reference it anywhere . Use things like graphql-schema-linter And so on. Tools to enforce naming conventions .
Some examples include ：
then , You will need to choose around pagination . What is the preferred way to display the list in the schema ？ Cursor based paging ？
How will you find errors ？ At the time of writing , We haven't figured out the error handling yet , There are many options to choose from ：
stay PayPal, We chose to use custom attributes to extend the error . We like that it's still up to standard , And allows us to add error classifications and other metadata to errors when needed . We don't think the other options are possible , And allow errors to go unnoticed . We'll provide more details in future medium-sized posts .
authentication / to grant authorization
First , We protected the whole architecture , And then realize that we have many different types of users with different privileges . then , We created a higher order auth function , You can use it to wrap the parser . Last , We realized that creating custom auth Instructions are the best way to protect the architecture .
Get superpowers with great tools
Before , We wrote 《GraphQL： Test your API And release the superpowers 》, It explains GraphQL And REST What are the unique advantages compared with , You can better understand API How to use , And with API The process of integrating and protecting clients provides customers with additional confidence to cope with major changes .
For starters , You can delay , Error and usage data are piped to the company's instrumentation tools .
Other tools we recommend include ：graphql-playground For testing queries in development mode ,graphql-schema-linter Used to enforce the schema naming convention ,eslint-plugin-graphql It is used to query the mode and the client ,graphql-doctor be used for PR Status check .
Apollo Graph Manager The instruments and tools provided can show insight at the field level , Confidence in radical change , White list queries , And by providing interlining and online for each field SLA Time to simplify customer integration .
Apollo Graph Manager It's not free . Can we build our own ？ Maybe , But not so perfect . We don't have it GraphQL Infrastructure team . If we do that , We don't want to wait 12-18 Months to build something comparable and have to maintain it . We want to cash it now GraphQL Commitment ！ In terms of buying and building decisions ,Apollo Platform It's a clear purchase . We suggest that you also consider .
Expand in the enterprise GraphQL challenges
up to now ,GraphQL great , But until we solve some problems about the way it's assembled and how successful it is , It's great .
stay 2012 Years ago ,PayPal yes C ++ monorepo. From then on , We have produced thousands of... In many areas and product teams GitHub The repository , It forms the service and application layers . For possession monorepos Of Facebook and GitHub For a company like this , Sharing is not a big problem .
GraphQL It's tricky in many repositories . If you don't have custom tricks like custom remote types , You can't reference or link remote types that don't exist in the local file system . It's not easy for developers to discover or reuse types defined in other services .
Users want to see a single cohesive graph that can be browsed , Without thinking about many services , You have to use many services to get the data you need . actually , It's difficult to assemble single graphics .
One solution is Pattern splicing , The gateway uses the bottom layer GraphQL API And show the developer a single pattern , And delegate the incoming query to the underlying API.Marc-Andre Giroux Wrote an excellent article , The challenge of pattern stitching is introduced . Stitching through patterns , The gateway has glue code , Responsible for maintaining relationships between types and ensuring proper execution of subqueries . The glue code is problematic , When the gateway owner doesn't know these types of , When it's unrealistic that the product team has the relationship between these infrastructures .
Apollo Platform Our solution is a Joint development Example , This example uses custom directives to declaratively link types together . It eliminates the need for glue code in gateways , Set up Appropriate separation of concerns , And allows you to extend types that you don't own in local development . See if companies will adopt it and how alliances will affect GraphQL Norms will be interesting .
What if it's impractical to build a map ？ At PayPal , We optimized for fast iteration and continuous learning . Many developers have no incentive to slow down , Reach a consensus and become part of a larger whole . This is the double-edged sword of our culture . If you can't draw a picture , We can also reuse work ？ Another option is to have GraphQL Modules and graphql-component And Class Local modules . Use local modules , You can choose the type and field you want , And all the code runs in the same process . Many of the problems of pattern stitching and union have disappeared . however , We have a lot of similar endpoints , And the server space is not reduced . Is this all right? ？
This is what we use GraphQL The most difficult problem we have .
（banq notes ： The problem of business aggregation can be solved by GraphQL Do you want to solve it by repeated combination ？）