REST, GraphQL and gRPC
medium 26 minThree ways to offer an API.
See it run
One profile screen, served three ways: count the waves, the queries and the bytes.
Operations
REST: four requests
The profile screen needs the user, three orders and their product names.
Step 1 of 5
Wave 1: two requests
- Time so far
- 0 ms
The user and the orders do not depend on each other, so the app asks for both.
Step 1: Wave 1: two requests
user, orders = parallel( get("/users/123"), get("/users/123/orders?limit=3")) # wave 1a, b = parallel( get(f"/products/{orders[0].product}"), get(f"/products/{orders[1].product}")) # wave 2render(user, orders, a, b)- Waves
- 2
- Model time
- 240 ms
- One after another
- 4 waves, 480 ms
Assumptions: 100 ms round trip, 20 ms server work, connection open. Count waves, not requests.
In the real world
The same rest, graphql and grpc doing real jobs. Pick one and step through it.
Each boundary gets the style its callers need.
Step 1 of 2
Partners
Partners call the REST API with JSON. Reads can be cached.
Step 1: Partners
Common mistakes
The bugs interviewers watch for, with the fix beside each.
GraphQL without limits
criticalOne query can ask for friends of friends of friends and stop the database.
Wrongserver = GraphQL(schema)Rightserver = GraphQL(schema, max_depth=8, max_cost=1000, timeout_seconds=5)A resolver that queries per item
majorA list of 100 items becomes 101 queries.
Wrongdef product(item): return db.one(item.product_id)Rightdef product(item): return product_loader.load(item.product_id)Reusing a Protobuf field number
criticalOld programs read the new field as the old one.
Wrongstring phone = 4; // 4 was the emailRightreserved 4;string phone = 5;A remote call that looks local
majorNetworks are slow and fail. Without a deadline, callers wait and pile up.
Wronguser = stub.GetUser(request)Rightuser = stub.GetUser(request, timeout=0.5)
Interview tips
How to explain it
- REST: addresses and methods.
- GraphQL: exactly these fields.
- gRPC: typed calls in binary.
Memory trick: REG
- R readable and reliable: public.
- E exactly what you need: screens.
- G greased lightning: services.
Count
- Waves on mobile.
- Queries per request.
- Who can debug it at night.
Avoid saying
- gRPC is ten times faster.
- GraphQL replaces REST.
- REST cannot return several things at once.