REST vs GraphQL vs gRPC
Choosing APIs for a food-delivery app
- Imagine designing a food-delivery app in a system design interview.
- REST, GraphQL, and gRPC suit different communication needs and can work together in the same system.
REST: simple resource operations
- Start with REST for the Orders screen:
- Use GET to fetch order details.
- Use POST to create a new order.
- Different screens may need different related data:
- Orders List: restaurant details, order status, and billing information.
- Order Details: order items, delivery address, and rider details.
GraphQL: flexible frontend data fetching
- GraphQL can be a good fit when different screens need different data from related database tables.
- Each screen selects only the fields it needs from the schema in a single query.
- The server collects the related data and sends it back to the frontend.
- Benefits:
- The frontend only needs to send a single request.
- The response does not contain unnecessary fields.
- Tradeoff: you need to maintain the GraphQL schema and server-side data-fetching logic.
gRPC: communication between backend services
- The backend has multiple services:
- Order Service.
- Payment Service.
- Delivery Service, which assigns riders to orders.
- Consider gRPC for communication between these services:
- Calling code can be automatically generated from the request-response contract, reducing manual integration work.
- Protocol Buffers serialize messages into a compact binary format, reducing data size and potentially lowering latency.
Takeaway
- REST: simple resource operations.
- GraphQL: flexible data fetching on the frontend.
- gRPC: strongly typed communication between backend services.
- All three can work together in the same system.