API design: REST vs GraphQL vs gRPC

An API is the contract between a client and a service. In an interview you pick a style, define the operations and say what happens when something goes wrong. The three styles you need to know are REST, GraphQL and gRPC. This lesson explains how each one works, the design rules that matter most (methods, status codes, retries, paging, versioning), and how to choose. Examples use an online shop with orders.

1. The Three Styles in One View

  • REST models the system as resources (orders, users) with URLs. Clients use standard HTTP methods on them. It is simple, cacheable and works everywhere. Most public APIs are REST.
  • GraphQL has one endpoint and a typed schema. The client sends a query that lists exactly the fields it wants, and gets exactly those. It suits clients with many different screens.
  • gRPC is contract-first. You describe services and messages in a .proto file, generate client and server code, and call remote functions over HTTP/2 with compact binary messages. It suits fast calls between internal services.
flowchart LR
  W["Web and mobile apps"] --> G["GraphQL gateway or backend-for-frontend"]
  P["Partners and public clients"] --> R["REST API gateway"]
  G --> S1["Order service"]
  G --> S2["User service"]
  R --> S1
  S1 -- "gRPC" --> S3["Payment service"]
  S1 -- "gRPC" --> S4["Inventory service"]

This picture is a common answer: REST at the public edge, GraphQL for your own apps, and gRPC between internal services. Section 6 explains the reasoning. Login and permissions (API keys, OAuth, tokens) are in the authentication lesson, rate limits are in the rate limiter lesson, and the gateways in the diagram are in the load balancers, proxies and API gateways lesson.

2. REST

2.1 Resource URLs

  • Use nouns, not verbs, and plural names: GET /orders/456, not /getOrder?id=456.
  • Show ownership with nesting, but keep it shallow: GET /orders/456/items. Avoid going deeper than two levels.
  • For actions that do not fit create, read, update or delete, either model the action as a resource or use a sub-path: POST /orders/456/cancel.
  • Filter, sort and page with query parameters: GET /orders?status=PAID&limit=20.

2.2 HTTP Methods

Two properties decide how a method is used. A method is safe if it does not change anything on the server. A method is idempotent if doing it twice has the same effect as doing it once. Idempotency decides whether a failed request can be retried without harm.

Method Purpose Safe Idempotent Cacheable Retry guidance
GET Read a resource Yes Yes Yes Safe to retry
HEAD Same as GET, headers only Yes Yes Yes Safe to retry
OPTIONS Ask which methods are allowed (used for CORS preflight) Yes Yes No Safe to retry
TRACE Echo the request back, for diagnostics Yes Yes No Safe to retry. Usually disabled for security
PUT Replace a resource completely No Yes No Safe to retry: the same body gives the same result
DELETE Remove a resource No Yes No Safe to retry: a repeat may return 404, but the end state is the same
POST Create a resource or run an action No No Only with explicit freshness headers (rare) Not safe to retry without an idempotency key
PATCH Change part of a resource No Depends on the change No "Set status to PAID" is safe to retry. "Add 10 to the balance" is not
CONNECT Open a tunnel through a proxy (how HTTPS passes through proxies) No No No Handled by clients and proxies. Not used in API design

The most useful rows for interviews are PUT versus POST (PUT can be retried, POST cannot) and PUT versus PATCH (replace everything, or change one field).

2.3 Status Codes

  • 2xx, success: 200 OK, 201 Created (return the new resource's URL), 202 Accepted (work will finish later), 204 No Content.
  • 3xx, go elsewhere: 301 moved permanently, 304 not modified (the cached copy is still good).
  • 4xx, the client made a mistake: 400 bad request, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict (for example a duplicate or a version clash), 422 valid format but invalid content, 429 too many requests.
  • 5xx, the server failed: 500 internal error, 502 and 504 bad or slow upstream, 503 unavailable.

Retry guidance follows from the code. Do not retry 4xx errors, because the same request fails again (except 429, which means "slow down", and 409 in some cases). Retry 5xx errors and timeouts with exponential backoff and jitter, and respect the Retry-After header. Retry only requests that are idempotent, or that carry an idempotency key (see 2.4).

2.4 Idempotency Keys

Networks fail. A client that sends POST /payments and gets a timeout does not know if the payment happened. If it retries, it may charge the customer twice. The fix is an idempotency key:

  • The client sends a unique key in a header: Idempotency-Key: 7c9e....
  • The server stores the key with a hash of the request and the response it gave.
  • If the same key arrives again, the server returns the stored response and does not repeat the work.
  • If the same key arrives with a different body, the server rejects it (409 or 422).
  • Keys are kept for a limited time, for example 24 hours.

2.5 Pagination

Never return an unbounded list. There are two methods:

  • Offset: ?offset=1000000&limit=20. Simple, and lets users jump to a page. But the database must scan and skip a million rows, so deep pages are slow. If rows are added or removed while the user pages, items are skipped or shown twice.
  • Cursor (keyset): ?limit=20&cursor=abc. The cursor encodes the last item seen, for example its creation time and id, and the query is WHERE (created_at, id) < (:t, :id) ORDER BY created_at DESC, id DESC LIMIT 20. It is fast at any depth and stable while data changes. You cannot jump to page 500. Use cursors for feeds and large collections.

2.6 Versioning, Errors and Caching

  • Versioning: adding a field or an endpoint does not break clients, so it needs no new version. Removing a field, renaming it or changing its type does. Put a version in the URL (/v2/orders) or a header, keep the old one running for a stated period, and tell clients early.
  • Errors: return one consistent shape with a machine-readable code, a human message, details and a request id: {"error": {"code": "ORDER_NOT_FOUND", "message": "...", "request_id": "..."}}.
  • Caching: GET responses can be cached by browsers, CDNs and proxies. Use Cache-Control to set the lifetime. Use ETag and If-None-Match so a client can ask "has this changed?" and get a tiny 304 response if not. This free caching is a main strength of REST.
  • Over-fetching and under-fetching: a fixed REST response may carry fields the client does not need, or force several calls to build one screen. GraphQL addresses this.

2.7 Example in Spring Boot

Creating an order and reading it back. The create call returns 201 with the new URL in the Location header, and takes the idempotency key from section 2.4:

@RestController
@RequestMapping("/orders")
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest request,
                                                @RequestHeader("Idempotency-Key") String key) {
        OrderResponse order = service.create(request, key);       // same key returns the stored result
        return ResponseEntity.created(URI.create("/orders/" + order.id())).body(order);   // 201
    }

    @GetMapping("/{id}")
    public OrderResponse get(@PathVariable long id) {
        return service.get(id);       // OrderNotFoundException is annotated @ResponseStatus(NOT_FOUND) for a 404
    }
}

3. GraphQL

A GraphQL service has one endpoint, usually POST /graphql, and a typed schema. The client asks for exactly the fields it needs, even across related objects, in one request:

query {
  order(id: "456") {
    status
    total
    items { name price }
    customer { name }
  }
}

The response has the same shape as the query. Three operation types exist: query (read), mutation (write) and subscription (a stream of updates, usually over WebSockets).

Strengths: one round trip builds a whole screen, no over-fetching, a self-documenting typed schema, and frontend teams can add fields to their queries without asking for a new endpoint. It is a good fit for mobile apps, where requests are costly.

Problems you must be ready to discuss:

  • The N+1 problem: a query for 20 orders with their customers can run 1 query for the orders and then 20 separate queries for customers. Fix it by batching lookups within one request, with a tool such as DataLoader.
  • Expensive queries: a client can ask for deeply nested data and overload the backend. Limit query depth and cost, set timeouts, and use persisted queries (only pre-approved queries are allowed).
  • Caching is harder: one URL and POST requests do not suit HTTP caches. Cache by object id inside the client, use persisted queries over GET so a CDN can cache them, and cache in the resolvers.
  • Errors: a response can be HTTP 200 with an errors list next to partial data. Monitoring must look inside the body.
  • Authorization: it must be enforced per field and per object, not only per endpoint.
  • Rate limiting: counting requests is not enough. Limit by query cost.

3.1 Example in Spring Boot

With spring-boot-starter-graphql, you write the schema in a .graphqls file, and controller methods are mapped to its fields:

type Query {
  order(id: ID!): Order
}
type Order {
  id: ID!
  status: String!
  total: Int!
  items: [Item!]!
  customer: Customer!
}
type Item { name: String! price: Int! }
type Customer { name: String! }
@Controller
public class OrderGraphqlController {

    private final OrderService orders;
    private final CustomerService customers;

    public OrderGraphqlController(OrderService orders, CustomerService customers) {
        this.orders = orders;
        this.customers = customers;
    }

    @QueryMapping                                   // the "order" field of Query
    public Order order(@Argument String id) {
        return orders.get(id);
    }

    @BatchMapping                                   // the "customer" field of Order
    public Map<Order, Customer> customer(List<Order> orders) {
        return customers.findFor(orders);           // one lookup for all orders, so no N+1
    }
}

Without @BatchMapping, a query for 20 orders would call the customer lookup 20 times. With it, Spring collects all the orders in the response and calls the method once.

4. gRPC

With gRPC you write the contract first, in a .proto file:

service OrderService {
  rpc GetOrder (GetOrderRequest) returns (Order);
  rpc WatchOrders (WatchRequest) returns (stream Order);
}
message Order {
  string id = 1;
  Status status = 2;
  int64 total = 3;
  string currency = 4;
}

Tools generate typed client and server code in many languages. Messages use Protocol Buffers, a compact binary format, and travel over HTTP/2 (see the HTTP versions lesson).

  • Small and fast. The order {"id":"456","status":"PAID","total":85000,"currency":"INR"} is 59 bytes as compact JSON. In Protobuf it is 16 bytes: the id is 5 bytes (tag, length, three characters), the status enum is 2, the total is 4 and the currency is 5. That is 73% smaller, and binary parsing is also faster.
  • Four call types: unary (one request, one response), server streaming, client streaming and bidirectional streaming.
  • Deadlines: a client sets a time limit on a call, and the limit passes down to every service the call touches. Work stops when the deadline passes. This prevents slow chains from piling up.
  • Own status codes: gRPC has its own codes (for example NOT_FOUND, DEADLINE_EXCEEDED, UNAVAILABLE), not HTTP codes.

Evolving the contract: a field's number identifies it on the wire. You can add new fields with new numbers and old clients still work. Never reuse or renumber a field, and never change its type. When you remove a field, mark its number as reserved so nobody reuses it later.

Limits:

  • Browsers cannot call gRPC directly. Use gRPC-Web or a gateway that translates between REST and gRPC.
  • Binary is harder to debug. You need tools such as grpcurl.
  • Load balancing needs care. gRPC keeps long-lived HTTP/2 connections, so a basic connection-level load balancer sends all of one client's calls to one backend. Use a load balancer that understands HTTP/2 and balances each call, or balance on the client side.

4.1 Example in Spring Boot

Spring Boot has no built-in gRPC server, so a common choice is the community starter grpc-spring-boot-starter (the net.devh project). The protobuf plugin of your build tool generates OrderServiceGrpc and the message classes from the .proto file. The server implements the generated base class:

@GrpcService
public class OrderGrpcService extends OrderServiceGrpc.OrderServiceImplBase {

    private final OrderRepository repo;

    public OrderGrpcService(OrderRepository repo) {
        this.repo = repo;
    }

    @Override
    public void getOrder(GetOrderRequest request, StreamObserver<Order> responseObserver) {
        Optional<Order> order = repo.find(request.getId());
        if (order.isEmpty()) {
            responseObserver.onError(Status.NOT_FOUND.withDescription("order not found").asRuntimeException());
            return;
        }
        responseObserver.onNext(order.get());       // send the response
        responseObserver.onCompleted();             // end the call
    }
}

A calling service injects a generated stub and sets a deadline, as described above:

@GrpcClient("orders")
private OrderServiceGrpc.OrderServiceBlockingStub orders;

Order order = orders.withDeadlineAfter(500, TimeUnit.MILLISECONDS)
        .getOrder(GetOrderRequest.newBuilder().setId("456").build());

5. Comparison

Aspect REST GraphQL gRPC
Format JSON over HTTP JSON over HTTP, one endpoint Protobuf over HTTP/2
Contract Optional (OpenAPI) Required typed schema Required .proto file
Who decides the response shape The server The client The server (fixed messages)
Streaming Not built in (use SSE or WebSockets) Subscriptions Built in, all four types
HTTP caching Excellent Hard Not applicable
Browser support Native Native Needs gRPC-Web or a gateway
Debugging Easy (curl, browser) Good (playground tools) Needs special tools
Best fit Public and partner APIs Apps with many views and data sources Internal service-to-service calls

6. How to Choose

  • Public or partner API: REST. It is easy to learn, easy to debug and cacheable, and every language has a client.
  • Your own web and mobile apps with many screens and many backend services: GraphQL, often as a backend-for-frontend (BFF), a gateway that collects data from many services for one client type.
  • Internal service-to-service calls with high volume, low latency needs or streaming: gRPC.
  • Real-time updates to the client: neither REST nor gRPC fits well for browsers. Use WebSockets or server-sent events (see the real-time lesson).

Say the reason, not just the choice: "REST at the edge because partners need simplicity and caching. gRPC inside because call volume is high and I want typed contracts and deadlines." Many real systems use all three. Do not pick GraphQL or gRPC because they are fashionable. Pick based on who calls the API and what they need.

7. Common Pitfalls

  • Verbs in REST URLs (/createOrder), and returning 200 for errors.
  • No idempotency on payments and other creates, so retries cause duplicates.
  • Offset pagination on large or fast-changing data. Use cursors.
  • Unbounded lists with no limit or maximum page size.
  • Breaking changes without a version, such as renaming a field or changing a type.
  • GraphQL without limits: no depth or cost limit, no batching, and per-endpoint authorization only.
  • Reusing a Protobuf field number, which silently corrupts old clients.
  • gRPC behind a connection-level load balancer, so one backend takes all the load.
  • No timeouts or deadlines, so one slow service blocks the whole chain.

8. Interview Questions This Lesson Prepares You For

  • When would you use GraphQL instead of REST? When clients such as mobile apps need different shapes of data from many services, and you want to avoid several round trips and over-fetching. Cost: harder caching, N+1 problems and a need for query limits.
  • When is gRPC the better choice? For internal service-to-service calls with high volume, tight latency, typed contracts, deadlines or streaming. It is a poor fit for public browser clients.
  • How do you make POST safe to retry? Use an idempotency key. The server stores the key and response, and returns the saved response on a repeat. Reject the same key with a different body.
  • PUT or PATCH? PUT replaces the whole resource and is idempotent. PATCH changes some fields, and is idempotent only if the change is (set a value, not add to a value).
  • Offset or cursor pagination? Cursor for large or changing data, because it stays fast and stable at any depth. Offset only for small, stable lists that need page jumping.
  • How do you change an API without breaking clients? Make only additive changes in place. For breaking changes, add a new version, keep the old one for an announced period, and in Protobuf never reuse or renumber fields.
  • What is the N+1 problem and how do you fix it? One query loads a list, then one more query runs for each item, so 20 orders cause 21 queries. Fix it by batching the lookups into one query, for example with DataLoader or Spring's @BatchMapping.