AlgoViz

REST, GraphQL and gRPC

medium 26 min

Three 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

Our system100 msMobile appREST APIUsers serviceOrders serviceProducts service
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

Our systemJSONquerygRPCgRPCPartnersOur appREST APIGraphQL serverOrders serviceProducts service

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

    critical

    One query can ask for friends of friends of friends and stop the database.

    Wrong
    server = GraphQL(schema)
    Right
    server = GraphQL(schema, max_depth=8, max_cost=1000,                 timeout_seconds=5)
  • A resolver that queries per item

    major

    A list of 100 items becomes 101 queries.

    Wrong
    def product(item):    return db.one(item.product_id)
    Right
    def product(item):    return product_loader.load(item.product_id)
  • Reusing a Protobuf field number

    critical

    Old programs read the new field as the old one.

    Wrong
    string phone = 4;   // 4 was the email
    Right
    reserved 4;string phone = 5;
  • A remote call that looks local

    major

    Networks are slow and fail. Without a deadline, callers wait and pile up.

    Wrong
    user = stub.GetUser(request)
    Right
    user = 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.