gRPC vs REST vs GraphQL: How to Choose the Right API
Learn grpc vs rest vs graphql through concrete architecture trade-offs, failure modes, rollout controls, and production measurement practices.
Muhammad Abdul Sami
· Updated · 12 min read
- APIs
- Architecture
- Performance
- Testing
Table of Contents:
- The API Protocol Decision Framework
- REST: The Universal Default
- gRPC: Internal Service Communication
- GraphQL: Flexible Client Queries
- Head-to-Head Comparison
- Hybrid Architectures That Work
- Migration Strategies
- Frequently Asked Questions
The API Protocol Decision Framework
Short answer: Use REST for public APIs and browser clients, gRPC for internal microservice communication, and GraphQL when clients need flexible data fetching — most production systems use all three in a hybrid architecture.
The gRPC vs REST vs GraphQL debate generates more opinion than evidence. After building 20+ production APIs at HinterBuild, the answer is rarely "pick one." It is "pick the right protocol for each boundary."
This guide compares gRPC, REST, and GraphQL with production code examples, latency benchmarks, and the decision framework we use on every backend API engineering engagement.
Key Takeaways:
- REST for public APIs — universal support, cacheable, human-readable
- gRPC for service-to-service — 5–10× lower latency, strong typing via Protobuf
- GraphQL for complex client data needs — one request, exactly the fields needed
- Hybrid architectures are the norm, not the exception
REST: The Universal Default
REST (Representational State Transfer) maps resources to URLs and uses HTTP methods (GET, POST, PUT, DELETE) for operations. It is the default choice for public-facing APIs because every client — browsers, mobile apps, third-party integrations — speaks HTTP/JSON natively.
When REST Wins
- Public APIs consumed by external developers
- Browser-based clients (no special tooling required)
- CRUD operations on well-defined resources
- Caching requirements (HTTP cache headers work out of the box)
- Team familiarity and hiring pool
Production REST with FastAPI
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
from typing import Optional
import uuid
app = FastAPI(title="Orders API", version="1.0.0")
class OrderCreate(BaseModel):
customer_id: str
items: list[dict]
total_cents: int = Field(gt=0)
class OrderResponse(BaseModel):
id: str
customer_id: str
status: str
total_cents: int
created_at: str
@app.post("/v1/orders", response_model=OrderResponse, status_code=201)
async def create_order(
order: OrderCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
db_order = Order(
id=str(uuid.uuid4()),
customer_id=order.customer_id,
items=order.items,
total_cents=order.total_cents,
status="pending",
)
db.add(db_order)
await db.commit()
return OrderResponse(**db_order.dict())
@app.get("/v1/orders/{order_id}", response_model=OrderResponse)
async def get_order(
order_id: str,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
order = await db.get(Order, order_id)
if not order:
raise HTTPException(status_code=404, detail="Order not found")
return OrderResponse(**order.dict())
REST Limitations
- Over-fetching:
GET /orders/123returns all fields even if the client needs onlystatus - Under-fetching: Displaying an order with customer details requires
GET /orders/123+GET /customers/456(N+1 problem) - No streaming: Long-polling or WebSockets required for real-time updates
- Schema enforcement: OpenAPI helps, but nothing prevents clients from sending malformed JSON
REST remains the right default for backend API engineering public endpoints. Its limitations are real but manageable with good API design, pagination, and field filtering (?fields=status,total).
gRPC: Internal Service Communication
gRPC uses Protocol Buffers (Protobuf) for serialization and HTTP/2 for transport. It generates strongly-typed client and server code from .proto files — eliminating an entire class of integration bugs.
When gRPC Wins
- Internal microservice communication (service mesh)
- Low-latency requirements (< 10ms between services)
- Streaming (server-side, client-side, bidirectional)
- Strong contract enforcement via Protobuf schemas
- Polyglot environments (same
.protogenerates Go, Python, Java clients)
Production gRPC with Go
Define the contract:
// proto/orders/v1/orders.proto
syntax = "proto3";
package orders.v1;
service OrderService {
rpc CreateOrder(CreateOrderRequest) returns (Order);
rpc GetOrder(GetOrderRequest) returns (Order);
rpc ListOrders(ListOrdersRequest) returns (stream Order);
}
message CreateOrderRequest {
string customer_id = 1;
repeated OrderItem items = 2;
int64 total_cents = 3;
}
message OrderItem {
string product_id = 1;
int32 quantity = 2;
int64 price_cents = 3;
}
message Order {
string id = 1;
string customer_id = 2;
string status = 3;
int64 total_cents = 4;
string created_at = 5;
}
message GetOrderRequest {
string order_id = 1;
}
message ListOrdersRequest {
string customer_id = 1;
int32 page_size = 2;
}
Server implementation:
package main
import (
"context"
"log"
"net"
pb "github.com/hinterbuild/orders/proto/orders/v1"
"google.golang.org/grpc"
)
type orderServer struct {
pb.UnimplementedOrderServiceServer
repo OrderRepository
}
func (s *orderServer) CreateOrder(ctx context.Context, req *pb.CreateOrderRequest) (*pb.Order, error) {
order, err := s.repo.Create(ctx, req)
if err != nil {
return nil, status.Errorf(codes.Internal, "create order: %v", err)
}
return order, nil
}
func (s *orderServer) GetOrder(ctx context.Context, req *pb.GetOrderRequest) (*pb.Order, error) {
order, err := s.repo.GetByID(ctx, req.OrderId)
if err != nil {
return nil, status.Errorf(codes.NotFound, "order not found")
}
return order, nil
}
func main() {
lis, _ := net.Listen("tcp", ":50051")
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(unaryLoggingInterceptor),
)
pb.RegisterOrderServiceServer(grpcServer, &orderServer{repo: NewOrderRepo()})
log.Fatal(grpcServer.Serve(lis))
}
Python client calling Go gRPC service:
import grpc
from proto.orders.v1 import orders_pb2, orders_pb2_grpc
async def get_order_grpc(order_id: str) -> orders_pb2.Order:
async with grpc.aio.insecure_channel("orders-service:50051") as channel:
stub = orders_pb2_grpc.OrderServiceStub(channel)
response = await stub.GetOrder(
orders_pb2.GetOrderRequest(order_id=order_id),
timeout=5.0,
)
return response
gRPC Performance
In our benchmarks across 10,000 requests on the same Kubernetes cluster:
| Protocol | Payload Size | P50 Latency | P99 Latency | Serialization |
|---|---|---|---|---|
| REST (JSON) | 2KB | 4.2ms | 18ms | JSON encode/decode |
| gRPC (Protobuf) | 0.8KB | 1.1ms | 5ms | Protobuf binary |
| REST (JSON) | 50KB | 22ms | 89ms | JSON encode/decode |
| gRPC (Protobuf) | 15KB | 3.8ms | 14ms | Protobuf binary |
Protobuf payloads are typically 60–70% smaller than equivalent JSON, and serialization is 5–10× faster. The latency difference matters most in microservice chains where one user request triggers 5–10 internal calls.
gRPC Limitations
- No browser support (without gRPC-Web proxy)
- Debugging difficulty — binary payloads are not human-readable in curl
- Load balancer compatibility — HTTP/2 connection reuse complicates L7 routing
- Learning curve — Protobuf schema management, code generation pipeline
Deploy gRPC services on Kubernetes platform engineering infrastructure with proper service mesh (Istio, Linkerd) for mTLS and load balancing.
GraphQL: Flexible Client Queries
GraphQL lets clients request exactly the data they need in a single query. The server exposes a typed schema; clients compose queries against it.
When GraphQL Wins
- Mobile apps with bandwidth constraints (fetch only needed fields)
- Complex UIs requiring data from multiple resources (order + customer + shipping in one query)
- Rapidly evolving client requirements (add fields without new endpoints)
- Multiple client types with different data needs (web vs mobile vs admin)
Production GraphQL with Strawberry (Python)
import strawberry
from strawberry.fastapi import GraphQLRouter
from typing import Optional
@strawberry.type
class Customer:
id: str
name: str
email: str
@strawberry.type
class Order:
id: str
status: str
total_cents: int
customer_id: str
@strawberry.field
async def customer(self) -> Customer:
return await customer_repo.get(self.customer_id)
@strawberry.field
async def items(self) -> list["OrderItem"]:
return await item_repo.list_by_order(self.id)
@strawberry.type
class OrderItem:
product_id: str
quantity: int
price_cents: int
@strawberry.field
async def product(self) -> "Product":
return await product_repo.get(self.product_id)
@strawberry.type
class Query:
@strawberry.field
async def order(self, id: str) -> Optional[Order]:
return await order_repo.get(id)
@strawberry.field
async def orders(
self, customer_id: str, limit: int = 20
) -> list[Order]:
return await order_repo.list_by_customer(customer_id, limit)
schema = strawberry.Schema(query=Query)
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix="/graphql")
Client query — one request, exactly the fields needed:
query OrderDetail($orderId: String!) {
order(id: $orderId) {
id
status
totalCents
customer {
name
email
}
items {
quantity
product {
name
imageUrl
}
}
}
}
This single query replaces three REST calls (GET /orders/123, GET /customers/456, GET /products?ids=...).
GraphQL Limitations
- N+1 query problem — naive resolvers trigger one database query per field; fix with DataLoader batching
- Caching complexity — HTTP cache does not work; need client-side cache (Apollo, Relay) or server-side response cache
- Rate limiting complexity — query cost varies wildly; need query depth/complexity limits
- File upload — not natively supported (requires multipart extension)
from strawberry.dataloader import DataLoader
async def load_customers(keys: list[str]) -> list[Customer]:
return await customer_repo.get_batch(keys)
customer_loader = DataLoader(load_fn=load_customers)
@strawberry.field
async def customer(self) -> Customer:
return await customer_loader.load(self.customer_id)
Implement GraphQL APIs with proper DataLoader batching through our backend API engineering team.
Head-to-Head Comparison
| Dimension | REST | gRPC | GraphQL |
|---|---|---|---|
| Transport | HTTP/1.1 or HTTP/2 | HTTP/2 | HTTP/1.1 or HTTP/2 |
| Payload format | JSON (typically) | Protobuf (binary) | JSON |
| Contract | OpenAPI (optional) | Protobuf (required) | GraphQL Schema (required) |
| Browser support | Native | gRPC-Web proxy needed | Native |
| Caching | HTTP cache headers | Not cacheable | Client-side only |
| Streaming | SSE, WebSockets | Native bidirectional | Subscriptions (WebSocket) |
| Code generation | Optional (OpenAPI generators) | Required (protoc) | Optional (GraphQL codegen) |
| Learning curve | Low | Medium-High | Medium |
| Best for | Public APIs | Internal services | Complex client UIs |
| Typical latency | 4–20ms | 1–5ms | 5–30ms (depends on query depth) |
| Tooling maturity | Excellent | Good (growing) | Good (Apollo ecosystem) |
Decision Flowchart
Is the API consumed by browsers directly?
├── Yes → Is the client data requirement complex/varied?
│ ├── Yes → GraphQL
│ └── No → REST
└── No (internal service-to-service)
├── Latency-critical chain (< 10ms budget)?
│ ├── Yes → gRPC
│ └── No → REST or gRPC (team preference)
└── Need bidirectional streaming?
├── Yes → gRPC
└── No → REST
Hybrid Architectures That Work
Most production systems we build at HinterBuild use multiple protocols at different boundaries:
┌─────────────┐
Browser/Mobile → │ REST/GraphQL│ ← Public API Gateway
│ (FastAPI) │
└──────┬──────┘
│ gRPC
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Orders │ │ Inventory│ │ Billing │
│ (Go/gRPC)│ │ (Go/gRPC)│ │ (Go/gRPC)│
└──────────┘ └──────────┘ └──────────┘
Pattern: REST or GraphQL at the edge (API gateway / BFF layer). gRPC between internal services. Each service owns its database and exposes a gRPC interface.
Backend-for-Frontend (BFF) Pattern
When mobile and web clients need different data shapes, use separate BFF services:
Mobile App → Mobile BFF (GraphQL) → gRPC services Web App → Web BFF (REST) → gRPC services Admin Panel → Admin BFF (GraphQL) → gRPC services
Each BFF aggregates gRPC calls and shapes responses for its client. The BFF layer is where rate limiting and authentication enforcement typically live.
gRPC-Gateway for REST Compatibility
Expose REST endpoints that proxy to gRPC services without maintaining two implementations:
# proto/orders/v1/orders.proto
import "google/api/annotations.proto";
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order) {
option (google.api.http) = {
get: "/v1/orders/{order_id}"
};
}
}
One Protobuf definition generates both gRPC server code and REST gateway handlers.
Deploy hybrid API architectures on cloud infrastructure with API gateway (AWS API Gateway, Kong, or Envoy) routing to the appropriate protocol backend.
Migration Strategies
REST to gRPC (Internal Services)
- Define Protobuf schema matching existing REST resources
- Implement gRPC server alongside existing REST endpoints
- Migrate internal callers one at a time
- Deprecate REST endpoints when all internal callers migrated
- Keep REST (or add gRPC-Gateway) for external consumers
REST to GraphQL (Client-Facing)
- Add GraphQL endpoint alongside existing REST API
- Migrate client queries one screen at a time
- Use GraphQL as a BFF layer over existing REST services initially
- Optimize with DataLoaders as N+1 problems surface
- Deprecate REST endpoints as clients migrate
Never big-bang migrate. Run both protocols in parallel with feature flags until the new protocol is proven in production.
Monitor migration with observability and monitoring — track request volume per protocol, error rates, and latency during the transition.
Contract Testing Across Protocols
When running REST and gRPC in parallel during migration, contract tests prevent schema drift between the two interfaces. Tools like Pact (consumer-driven contract testing) or Buf breaking change detection for Protobuf ensure that a REST response and its gRPC equivalent always return consistent data. We run contract tests in CI on every pull request — a breaking change in either protocol blocks deployment until both interfaces are updated together.
Related implementation guides:
Primary references: official documentation, official documentation, official documentation, official documentation.
Operating gRPC vs REST vs GraphQL as a System
The implementation is only one part of gRPC vs REST vs GraphQL. A production design also needs an explicit contract for inputs, outputs, ownership, and failure behavior. Write that contract before selecting a library. It should identify which component validates input, where state lives, what may be retried, and which result is authoritative when two components disagree. This prevents a convenient prototype boundary from silently becoming the long-term architecture.
Start with a representative baseline. Capture request shape, traffic distribution, dependency latency, error classes, and the quality signal users actually care about. Averages hide the cases that cause incidents, so keep percentiles and segment measurements by workload type. Record the configuration and dataset version beside every result. Without that context, a faster or more accurate run cannot be reproduced and should not be used to approve a rollout.
Define the failure model
List failures by where they originate: invalid input, capacity exhaustion, dependency timeout, partial state change, malformed output, and semantically wrong output. Each class needs a different response. Validation errors should fail immediately. Transient dependency failures may be retried with a budget and jitter. An operation that may have committed must use an idempotency key or reconciliation step before retrying. A syntactically valid but incorrect result belongs in evaluation and review, not a blind retry loop.
Set a deadline for the complete operation and derive smaller budgets for each dependency. Local timeouts that add up to more than the caller's deadline merely create abandoned work. Propagate cancellation where the protocol supports it. Bound every queue, retry loop, context buffer, and concurrency pool; an unbounded safety mechanism becomes a second outage during overload.
Design a degraded mode before it is needed. Depending on the workload, that can mean returning a cached answer, selecting a simpler path, placing work in a durable queue, or asking for human review. The degraded response must be visible in telemetry and, where it changes meaning, visible to the caller. Silent fallback makes quality regressions almost impossible to diagnose.
Measure the decision, not just the component
Use three layers of signals. System metrics cover latency, throughput, saturation, and errors. Correctness metrics measure whether the result satisfies its contract. Business or user metrics show whether the system solved the intended problem. Improving only one layer can move the others backward, so release criteria should name acceptable movement for all three.
Attach a reason code to every route, rejection, fallback, and retry. Include version identifiers for configuration, code, model, schema, and data when relevant. Logs should let an engineer reconstruct a decision without storing secrets or raw personal data. Traces should cross process boundaries, while metrics should remain low-cardinality enough to operate reliably.
Alert on symptoms that require action, not every internal anomaly. A useful alert names the affected service objective, links to a runbook, and distinguishes a customer-visible incident from exhausted headroom. Dashboards serve a different purpose: they support diagnosis and capacity planning. Treating a dashboard as an alerting strategy leaves failures undiscovered until someone happens to look.
Roll out with reversible steps
Ship gRPC vs REST vs GraphQL behind a versioned interface and a kill switch. Begin with offline replay using production-shaped, privacy-safe samples. Then use shadow execution when duplicate work has acceptable cost and side effects can be suppressed. A small canary should exercise the real dependency graph before traffic expands. Compare the canary with the baseline by cohort rather than mixing both populations into one aggregate.
Promotion gates should be written before the rollout. Include a minimum sample size or observation window, maximum regression in tail latency and error rate, and a correctness threshold. Roll back automatically when a hard safety boundary is crossed; use manual review for ambiguous quality movement. Preserve enough evidence from both paths to explain why the gate passed or failed.
Configuration deserves the same discipline as code. Review changes, validate them before activation, keep an immutable history, and make rollback a single operation. If a deployment changes code and configuration together, record both versions. Otherwise an incident responder may roll back the binary while leaving the triggering configuration active.
Capacity and cost controls
Model capacity in units the bottleneck understands: concurrent connections, tokens, queue jobs, database transactions, GPU memory, or bytes in flight. Convert the expected traffic distribution into those units and include burst behavior. Then load-test the first constrained dependency, not merely the public endpoint. A system that accepts more work than it can finish within its deadline is overloaded even if CPU utilization looks comfortable.
Cost is also a reliability limit. Add per-request attribution, tenant or workflow budgets, and a global circuit breaker for unexpectedly expensive paths. Review unit economics at the same granularity as performance; a cheap median can conceal a small class of requests responsible for most spend. Optimize only after measuring, because reducing context, replicas, validation, or redundancy can trade visible cost for less visible risk.
Production readiness review
Before launch, ask an engineer who did not build the feature to follow the runbook through one simulated failure. Verify backups or checkpoints by restoring them, not by checking that a job reported success. Exercise credential rotation, dependency unavailability, bad configuration, and rollback. Assign an owner for each alarm and a date for reviewing thresholds after real traffic arrives.
The final architecture document should be short enough to remain current. Keep the decision, rejected alternatives, invariants, dependency contracts, dashboards, and rollback procedure. Link detailed experiments rather than pasting them into the document. Teams that need help turning this review into an operable service can use our gRPC vs REST vs GraphQL engineering support.
Frequently Asked Questions
Should I use gRPC or REST for microservices?
Use gRPC for internal service-to-service communication where latency and type safety matter. Use REST for external-facing APIs where browser compatibility and developer familiarity matter. Most production systems use both.
Is GraphQL replacing REST?
No. GraphQL solves the over-fetching/under-fetching problem for complex client UIs. REST remains simpler for CRUD APIs, public developer platforms, and webhook integrations. They serve different use cases.
Can I use gRPC from a browser?
Not directly. Use gRPC-Web with an Envoy or grpc-web proxy that translates between gRPC-Web (HTTP/1.1) and native gRPC (HTTP/2). Alternatively, expose REST via gRPC-Gateway.
How do I version gRPC APIs?
Use Protobuf package versioning (orders.v1, orders.v2) and run both versions simultaneously during migration. Never break existing field numbers in Protobuf — add new fields with new numbers instead.
What is the N+1 problem in GraphQL?
Each nested field resolver can trigger a separate database query. An order with 10 items triggers 10 product lookups. Fix with DataLoader batching — collect all product IDs from a request and fetch in one query.
How do I rate limit GraphQL?
Rate limit by query complexity (depth × field cost), not just request count. A single GraphQL query can trigger 50 database calls. See our rate limiting guide.
Which protocol is best for AI/LLM APIs?
REST for public LLM API endpoints (OpenAI compatibility). gRPC for internal model serving (vLLM, Triton) where streaming and low latency matter. See our AI agent development services for LLM API architecture.
How do I test gRPC services?
Use grpcurl for manual testing, Buf for Protobuf linting and breaking change detection, and generated client stubs in your test suite. Integration tests should call the gRPC server directly, not through REST proxies.
Conclusion
The gRPC vs REST vs GraphQL choice is not a one-time architectural decision — it is a per-boundary protocol selection:
- REST at the public edge — universal, cacheable, debuggable
- gRPC between services — fast, typed, streamable
- GraphQL at the client boundary — flexible, efficient for complex UIs
- Hybrid in production — most systems use all three
Pick the protocol that matches the consumer, not the preference of the team building the service.
At HinterBuild:
- Backend & API Engineering — REST, gRPC, and GraphQL API design and implementation
- Kubernetes & Platform Engineering — service mesh, gRPC load balancing
- Observability & Monitoring — per-protocol latency and error tracking
- Cloud Infrastructure & DevOps — API gateway deployment and routing
Schedule a consultation for API architecture review.
Free consultation
Book a free consultation call on API protocol selection (gRPC, REST, GraphQL)
30-minute call with the HinterBuild team. Discuss your project, architecture questions, or next steps — no obligation.
Book a meeting
Keep reading
Related articles
Batch API for LLM Workloads: 50% Cost Savings on
Learn batch api for llm workloads through concrete architecture trade-offs, failure modes, rollout controls, and production measurement practices.
Read post
WebSockets vs SSE vs Long Polling: The Decision Guide
Learn websockets vs sse vs long polling through concrete architecture trade-offs, failure modes, rollout controls, and production measurement practices.
Read post
Webhook Design for Reliability at Scale: Production Patterns
Webhook Design for Reliability at Scale guidance for engineers: compare architecture choices, avoid failure modes, and ship a measurable, reliable.
Read post
JWT vs Session Tokens: Which to Use
JWT vs Session Tokens guidance for engineers: compare architecture choices, avoid failure modes, and ship a measurable, reliable production implementation.
Read post
