A Developer’s Dilemma: Selecting the Perfect Protocol - GraphQL, REST, gRPC or WebSockets?
Megha Sahay
Full Stack Development || DevOps || C#/.Net || Java/J2EE || Python || Masters in AI & ML || Ex HSBC || Epiroc Sweden
Selecting the ideal protocol for your unique Project
Introduction
Many software architects face problems to choose between the best suitable technology for their services. A communication technology that is operational, practical and should allow developers to define a set of CRUD (Create, Read, Update and Delete) methods for processing data.
In this article I have tried to compare REST architecture style, gRPC?, GraphQL and WebSockets communication protocols. SOAP is not considered because it is no longer a preferred method of communication in modern web applications. This first section gives introduction to these communication protocols. Then comparing the performance of these protocols. Concluding with some results from research papers.
REST
It stands for Representational State Transfer which is an architecture style. This was introduced and defined by Roy T. Fielding in 2000. When we think of REST which is a concept of resources. A resource can be thought as a thing that service is aware of like an Employee for example. The server will create different representation of this Employee on request. Once the client has a representation of Employee then it can make request to change it, if the operation is successful then a HTTP success code is retuned otherwise an HTTP error code is returned. REST is commonly used over HTTP.
How does HTTP request work?
When we open a web browser of any website. The browser acts as a client that makes a request to remote server. A request can be considered as a text document which contains mainly these information?:
2. header?—?Information and meta data about the request. It can be content type, content length, authorization (who is making a call), Accept (which content type client is able to understand), cookies and much more.
This can be considered as header example.
Cache-control: no-cache
3. content/body?—?It is the information that can optionally asked for to fulfill a request. it can be HTML/CSS/JavaScript/Json or any other format.
Below shows a typical HTTP request with verb, header and content.
POST /api/employee HTTP/1.1
Host: myWebApi.com
Content-Type: application/json
Cache-Control: no-cache
{
"Name": "Megha Sahay",
"Age": 25
}
Response
Response is a textual document containing status code that says success or failure?, headers (content type) and content that server sends in response.
100–199?: informational
200–299: success
300–399: Redirection information
400–499: client error
500–599: server errors
2. Header - It is set of headers just like request header.
3. Content - Very much like request content that contains the response information.
An example of HTTP response. The status code of 200 (ok) is returned. The header information consists of the date server, accept-ranges, content-length, content-type. The content or the body of response is an HTML document as shown below.
HTTP/1.1 200 OK
Date: Thu, 03 Jan 2022 23:30:00 GMT
Server: gws
Accept-Ranges: bytes
Content-Length: 68894
Content-Type: text/html; charset=UTF-8
<!doctype html><html …
Benefits of REST with HTTP
Summary
To sum up REST architecture style can result in better performance and scalability in simple, lightweight applications.
WebSocket Protocol
It is a communication protocol that enables two-way communication. Which would mean that the server is independent of the client and doesn't have to wait for client for request. The server can send data independently. This can be possible by establishing a single TCP connection between client and server.
The websocket protocol consists of two phases?:
领英推荐
GET /chat HTTP/1.1 Host: server.mywebsite.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: gdhsddfdtwDkjskiqw1==
Origin: https://mywebsite.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version:14
The server then replies with its own handshake response which has HTTP code set to 101. Example response is below:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: hdgsahdywqySDASDDA+xOo=
Sec-WebSocket-Protocol: chat
2. TCP connection?—?When the handshake is completed successfully the communication is done via a single TCP connection using The Websocket Protocol. The client server send data independently in chunks called messages. Message consists of frames which are transferred across sides.
The connection to be closed, a unique frame is sent by one of the peers. The frame has the contact of closure. When some other peer receives it, responds with close frame. So that the connection is safely closed.
Summary
To summarize web sockets are Real-time, bidirectional, persistent connections. Suitable for low-latency data exchange. A low latency is a computer network that is optimized to process high volume of data with minimal delay.
gRPC (Google remote procedure call)
gRPC is an open source system that implements remote procedure call concept. It was developed by Google in 2015 as a successor of RPC system called Stubby. Stubby, an RPC framework that consists of core RPC layer that can handle internet-scale of tens of billions of requests per seconds. Stubby was made as open-source called gRPC.
RPC is a Remote Procedure Call, at the Client Code, it just looks like you’re calling a local function from the server. It supports streaming, language independent, low latency.
What makes gRPC so fast?
Summary
gRPC is based on RPC framework uses HTTP/2 and protobuf an binary format, making it very fast. It can be used when you need faster communication. Therefore it should be used in scenario that needs real time data streaming and large data loads.
GraphQL
It is an open source solution for querying and mutating(changing) data via remote API. It was first developed by Facebook but was publicly available in 2015. Now it is developed by Linux Foundation. It is not tied to any specific database or storage engine. It is backed by existing code and data.
Summary
GraphQL is database neutral technology that provides flexibility to the client to get data from multiple servers in a single response. GraphQL was developed to solve a mobile problem. However, those benefits may not be relevant to your project. There are some drawbacks to it for an application like Lack of proper pagination, caching, and MIME types are real issues. As resolvers are harder to maintain managing GraphQL is complex. So, graphQL is suitable for mobile apps or when you have complex schema or you receive data from multiple sources are to name a few.
REST vs GraphQL architecture
This section illustrates the major differences between gRPC, REST and GraphQL.
The main difference between REST and GraphQL APIs technology is the availability of the number of endpoints when they are handling requests
Figure below illustrates the difference between REST and GraphQL architecture.
gRPC vs REST vs?GraphQL
The parameters chosen for comparison between gRPC, REST and GraphQL is the architecture, data organization, the supported operations, data fetching, community support, Performance, Development speed, learning curve for developers, self documentation, file uploading capabilities, in build caching, stability and real world use case. It can be seen from the below summary table that no one technology is winner. There are some tradeoffs if you have a simple application REST can be sufficient as gRPC and GraphQL adds unnecessary complexity.
gRPC vs REST vs GraphQL vs Websocket a performance comparison a closer?look
In this section we will take a closer look at performance comparison. The results are based on the experiments conducted in this research paper.
The parameters chosen are time and memory consumed for inserting/fetching elements to/from database.
gRPC protocol is the fastest in transferring data between client and server. The WebSockets protocol achieved similar results to REST when transferred data was small. When data was larger it turned out to be the slowest. REST style was moderately fast. It turned to be slower than gRPC, but was never the worst in any category. GraphQL had some troubles with small data. It was the worst in inserting and fetching one element from database. It was slightly faster than the WebSockets in fetching a larger data.
Summary
If a programmer is looking for the fastest way to transfer data and does not care about message size the relevant option will be gRPC. On the other hand, if delivery time is not crucial and there is need of low memory usage the right option will be WebSocket. REST protocol is also an interesting way to communicate. It provides decent memory usage, time performance and what is the most important it is easily accessible, which means that every new client can easily connect to server. There is also GraphQL which provides the worst memory usage to time performance ratio especially in single element operations. This means that this protocol should be used in other way, e.g., nested data structures where data is fetched with queries.
References