Skip to content

API Styles: REST, gRPC, GraphQL and More

Intermediate 41 min read Part 4 of 18

REST, RPC and gRPC, GraphQL and SOAP compared: how each works, where each shines, and how to choose for public, internal and mobile clients.

Summary#

REST models the system as resources (URLs) manipulated with standard HTTP methods; it is simple, cacheable and universal, which makes it the default for public APIs. gRPC calls remote functions with compact Protocol Buffers over HTTP/2, with streaming and generated clients; it is the common choice between internal services. GraphQL exposes one endpoint and a typed schema, letting clients ask for exactly the fields they need; it suits many different front ends over complex data. SOAP is an older XML-based style still found in enterprise and finance. Choose by client type, performance needs and how much flexibility clients need.

Why It Exists#

Every system with more than one component needs a contract for how components talk. The style of that contract affects performance, how easily clients evolve, how well it caches, and how much tooling you get. A public API used by thousands of developers needs different properties from a chatty call between two internal services, and both differ from a mobile app that must load a screen in one round trip.

This page compares the main styles. How to design a good API within a style is covered in API Design. It builds on HTTP and HTTPS.

How It Works#

Three questions every API style answers#

All API styles answer the same three questions in different ways, and comparing them along these lines makes the choice much clearer:

  1. What is the API organised around? REST is organised around data: things (resources) that exist in the system, such as users, orders and tickets. RPC is organised around behaviour: operations the server can perform, such as checkPermission or chargeCard. GraphQL is organised around a graph of types that clients walk through, picking the fields they want.
  2. How is the data encoded? As text (JSON for REST and GraphQL, XML for SOAP), which is human-readable and universal, or as binary (Protocol Buffers for gRPC, Thrift, Avro), which is smaller and faster to parse but needs the schema to decode.
  3. How strict is the contract? REST contracts are optional (an OpenAPI document is common but not required). gRPC, GraphQL and SOAP require a schema, which enables code generation and compile-time checks, and also forces every change through the schema.

The flowchart reflects a practical rule: default to REST unless you have a specific reason not to. It is understood by every developer and tool, it works for the large majority of use cases, and in an interview "I will use REST for the public API" is a complete answer that lets you move on to the harder parts of the design. Real-time features (chat, notifications, live prices) are a different category: they need persistent connections rather than an API style, and are covered in Real-time Communication.

REST principles and resources#

REST (Representational State Transfer) is an architectural style built on HTTP:

  • Resources are nouns with URLs: /users/42, /users/42/orders.
  • Standard methods express actions: GET reads, POST creates, PUT replaces, PATCH updates, DELETE removes.
  • Representations: the server returns a representation of the resource, usually JSON.
  • Stateless: every request carries everything needed (auth token, parameters).
  • Cacheable: responses declare cacheability with HTTP headers, so browsers and CDNs can cache GETs.
  • Uniform interface: the same patterns everywhere make APIs predictable. Strict REST also includes HATEOAS (responses link to related actions), which few APIs fully follow.
GET    /v1/orders?status=open&limit=20    -> 200 list of orders
POST   /v1/orders                         -> 201 Created, Location: /v1/orders/981
GET    /v1/orders/981                     -> 200 order
PATCH  /v1/orders/981  {"note": "gift"}   -> 200 updated order
DELETE /v1/orders/981                     -> 204 No Content

Strengths: universally understood, easy to debug with curl, works with HTTP caches and every language. Weaknesses: clients may need several calls for one screen (under-fetching) or receive fields they do not need (over-fetching); text JSON is relatively verbose.

REST in depth#

Where REST comes from. Roy Fielding defined REST in his 2000 doctoral dissertation at UC Irvine, as a description of the architectural constraints that made the web scale. The constraints are: client-server separation; statelessness (each request carries everything the server needs, so any server can handle any request); cacheability (responses say whether and how long they may be reused); a uniform interface; a layered system (clients cannot tell whether they talk to the origin or to a proxy, CDN or gateway); and optional code on demand (the server can send scripts). Most "REST APIs" in practice follow some of these, especially statelessness and the uniform interface, and loosely follow the rest.

The four qualities of a RESTful interface:

  • Resources are identified by URLs. A resource keeps the same URL whatever you do with it. /orders/981 is the order whether you read, change or delete it.
  • Actions are expressed with methods and representations. The HTTP method says what to do, headers describe the representation (Content-Type: application/json), and the body carries the data.
  • Errors are self-describing through status codes. Use the standard HTTP codes instead of always returning 200 with an error message inside.
  • Hypermedia drives navigation (HATEOAS). Responses include links to related resources and allowed next steps, so a client can explore the API the way a person explores a website by following links.
{
  "id": 981,
  "status": "open",
  "total_cents": 4599,
  "_links": {
    "self":   { "href": "/orders/981" },
    "items":  { "href": "/orders/981/items" },
    "cancel": { "href": "/orders/981/cancellation", "method": "POST" }
  }
}

Few public APIs follow HATEOAS fully, because most clients are written against documentation rather than discovering links at run time. Leonard Richardson's maturity model, popularised by Martin Fowler, describes the levels: level 0 sends everything to one URL (plain RPC over HTTP), level 1 introduces resources, level 2 uses HTTP methods and status codes properly, and level 3 adds hypermedia. Most good APIs sit at level 2.

Representations and content negotiation. A resource is not the same thing as its JSON. The same order could be represented as JSON for an app, as CSV for an export or as a PDF for an invoice. Clients say what they can accept with the Accept header, the server picks a format and declares it in Content-Type, and it returns 406 Not Acceptable if it cannot serve any of them. In practice most APIs serve JSON only, but the idea explains why REST URLs name things and never formats or actions. It also explains why the same URL can return a smaller representation to a client that asks for one, for example through a fields query parameter that selects only some fields, which is a lightweight answer to over-fetching within REST.

Modelling resources from core entities. In an interview, the resources are usually the core entities you already listed. For a ticketing system with events, venues, tickets and bookings:

GET  /events                     list events (filters in the query string)
GET  /events/123                 one event
GET  /venues/7                   one venue
GET  /events/123/tickets         available tickets for event 123
POST /events/123/bookings        create a booking for event 123
GET  /bookings/555               one booking

Resources are nouns, usually plural, describing things that exist, not actions. "Book" and "purchase" become a booking resource that you create.

Nested or flat? Nest when the parent is required for the request to make sense: /events/123/tickets always needs an event. Use query parameters for optional filters: /tickets?event_id=123&section=VIP might be called with any combination of filters, or none. Avoid nesting deeper than two levels (/events/123/sections/4/rows/9/seats), which makes URLs fragile; give deep objects their own top-level URLs.

Where input goes:

LocationRoleExample
PathIdentifies which resource; required/events/123
Query stringOptional filters, sorting, pagination, behaviour switches?city=NYC&date=2026-01-01&limit=20
BodyThe data being created or changed; large or sensitive valuesBooking details, payment method
HeadersMetadata: auth, content type, idempotency key, cachingAuthorization, Idempotency-Key

For example, booking two VIP seats for event 123 with an email confirmation: the event ID goes in the path because it identifies the parent, "notify by email" goes in the query string because it is an optional switch, and the seats and payment go in the body because they are the data being created. Secrets never go in URLs, because URLs end up in logs, browser history and analytics.

POST /events/123/bookings?notify=true
Idempotency-Key: 4f1c-9a27
 
{ "seats": [ { "section": "VIP", "quantity": 2 } ], "payment_method_id": "pm_77" }

Methods and their guarantees. A method is safe if it does not change server state, and idempotent if sending it several times has the same effect on server state as sending it once:

MethodUseSafeIdempotent
GETReadYesYes
POSTCreate, or trigger a processNoNo
PUTReplace a whole resource, or create it at a known URLNoYes
PATCHChange part of a resourceNoNot guaranteed
DELETERemoveNoYes

PATCH depends on its content: "set email to X" is idempotent, "append item to list" is not. DELETE is idempotent in effect even though the first call may return 204 and later calls 404. These guarantees matter because networks fail and clients retry: retrying a GET, PUT or DELETE is safe, while retrying a POST can create a duplicate booking unless the API supports idempotency keys. See Idempotency.

Returning data. A response is a status code plus a body. The codes that matter most are 200 OK, 201 Created (with a Location header pointing at the new resource), 204 No Content, 400 Bad Request, 401 Unauthorized (not authenticated), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict, 429 Too Many Requests, 500 Internal Server Error and 503 Service Unavailable. The essential distinction is between 4xx (the client must change something before retrying) and 5xx (the server failed, and a retry may succeed). In an interview, nobody expects every code; showing that you know this difference is what counts.

Operations that do not fit the verbs. Some actions are not naturally create, read, update or delete: "archive all expired documents", "start a game", "resend a verification email". Three common approaches:

  • Model the state change as an update: PATCH /games/42 with a body setting status to started.
  • Model the action as a resource you create: POST /archive-jobs creates an archive job you can then poll with GET /archive-jobs/17. This works well for long-running work.
  • Use a clearly named action sub-resource: POST /documents/9/archive. Not purist REST, but widely used (Google's API design guide calls these custom methods) and clear.

Where REST is weaker. REST works best when data sits in a natural hierarchy. Several situations strain it:

  • Queries that are not a path. "All records updated in the last hour that match these event types" ends up as a mix of path, query parameters and sometimes a body on a POST search endpoint.
  • Verbs that do not fit, as above.
  • Several round trips per screen. Rendering a blog post with its author and comments might need three requests. On a mobile network with 100-300 ms round trips, that is slow.
  • Payload growth. As fields are added over the years, older clients download data they never use.

These weaknesses are exactly what GraphQL and Backend-for-Frontend layers address.

RPC and gRPC#

RPC (remote procedure call) makes a network call look like a function call: GetUser(id), ChargeCard(order, amount). The API is organised around actions, not resources.

gRPC, open-sourced by Google, is the most common modern RPC framework:

  • Protocol Buffers (protobuf) define messages and services in a .proto file. Messages are encoded in a compact binary format, typically several times smaller and faster to parse than JSON.
  • Code generation produces typed clients and server stubs in many languages from the same file.
  • HTTP/2 transport gives multiplexing over one connection and header compression.
  • Streaming: unary (one request, one response), server streaming, client streaming and bidirectional streaming.
  • Deadlines and cancellation propagate across services.
syntax = "proto3";
service OrderService {
  rpc GetOrder (GetOrderRequest) returns (Order);
  rpc WatchOrders (WatchRequest) returns (stream OrderEvent);   // server streaming
}
message GetOrderRequest { string order_id = 1; }
message Order { string id = 1; string status = 2; int64 total_cents = 3; }

Weaknesses: browsers cannot call gRPC directly without a proxy (gRPC-Web), binary payloads are harder to inspect, and HTTP caching does not apply.

RPC in depth#

The idea. A remote procedure call lets a program run a procedure in another address space, usually on another machine, using code that looks like a local function call. Andrew Birrell and Bruce Nelson's 1984 paper "Implementing Remote Procedure Calls" described the classic design, which almost every RPC framework still follows:

The stubs are generated from an interface definition. The client stub packs (marshals) the procedure identifier and arguments into a message, the operating system sends it, the server stub unpacks (unmarshals) it and calls the matching procedure, and the reply travels back the same way.

A remote call is not a local call. It is thousands of times slower (a function call takes nanoseconds, a network call takes from about half a millisecond in one data center to hundreds of milliseconds across continents), it can fail halfway, and the caller may never learn whether the server ran it. Jim Waldo and colleagues' 1994 paper "A Note on Distributed Computing" argued that hiding these differences behind a local-looking interface is a mistake, because latency, partial failure and concurrency cannot be abstracted away. Modern RPC frameworks therefore make remoteness visible: calls take deadlines, return status codes, and are usually asynchronous.

RPC is about exposing behaviour. Instead of resources, you name operations:

getEvent(eventId: "123")
createBooking(eventId: "123", userId: "456", seats: [...])
getAvailableTickets(eventId: "123", section: "VIP")
checkPermission(userId: "456", resource: "booking:555", action: "cancel")

checkPermission shows where RPC is the more natural fit: it is an action, and modelling it as a REST resource is awkward. Internal service-to-service calls are full of such operations, which is one reason RPC dominates inside companies.

The same operations in both styles. A small library system makes the contrast concrete:

OperationRPC styleREST style
Register a memberPOST /registerMemberPOST /members
Close a membershipPOST /closeMembership with the member ID in the bodyDELETE /members/88
Read a memberGET /getMember?memberId=88GET /members/88
List a member's loansGET /listLoansForMember?memberId=88GET /members/88/loans
Borrow a bookPOST /borrowBook with member and book IDsPOST /members/88/loans with the book ID
Change a loan's due datePOST /updateLoan with loan ID and new datePATCH /loans/301 with the new date
Return a bookPOST /returnBook with the loan IDDELETE /loans/301, or PATCH its status to returned

The REST column reuses a few URLs and the standard methods; the RPC column adds a new endpoint name for each operation.

Trade-offs of RPC:

  • Tight coupling. Clients are bound to specific procedures and their signatures, so the client tends to mirror the server's implementation.
  • A new endpoint per use case. Each new operation is a new procedure to define, document and support.
  • Harder debugging, especially with binary encodings that you cannot read in a log or with curl.
  • Less help from existing infrastructure. HTTP caches and proxies understand GET on a URL; they do not understand that getEvent is a cacheable read sent as a POST.
  • Performance and control. On the plus side, you can shape each call exactly for its use, send compact binary messages and keep connections open, which is why RPC is preferred for high-volume internal traffic.

Frameworks. gRPC (Google, using Protocol Buffers) is the most common today. Apache Thrift, originally developed at Facebook, offers a similar interface language with several encodings and transports. Apache Avro, from the Hadoop ecosystem, stores the writer's schema alongside the data or in a registry, which suits data pipelines and Kafka. JSON-RPC is a minimal text protocol with method names and parameters in JSON. Twirp and Connect provide protobuf-based RPC over plain HTTP that is easier to call from browsers and curl.

gRPC and Protocol Buffers in depth#

How protobuf encodes data. A protobuf message is a sequence of fields, each written as a tag followed by a value. The tag combines the field number and a wire type (field_number × 8 + wire_type), and both the tag and integers use varints, which take one byte for values under 128 and grow by one byte per 7 bits. Strings and nested messages are written as a length followed by the bytes. Field names are never sent; the schema maps numbers to names.

For a message with string id = 1 and string name = 2, the value with ID "42" and name "Ada Lovelace" encodes as:

JSON (minified):  {"id":"42","name":"Ada Lovelace"}       33 bytes
Protobuf:         0A 02 34 32  12 0C 41 64 61 20 4C 6F 76 65 6C 61 63 65    18 bytes
                  tag=field 1, len 2, "42"   tag=field 2, len 12, "Ada Lovelace"

The saving grows for numbers (the integer 300 is 2 bytes as a varint, 3 characters plus quotes and a key name in JSON), for repeated keys in long arrays, and for parsing cost, since there is no text to scan. Field numbers 1-15 have one-byte tags, so put the most frequent fields there.

gRPC on the wire. gRPC runs over HTTP/2. Each call is one HTTP/2 stream: the method is the path (/tickets.TicketService/GetEvent), metadata travels as headers, each message is a protobuf payload with a 5-byte prefix (a compression flag and a 4-byte length), and the final status (grpc-status, grpc-message) is sent in HTTP trailers after the body. Because HTTP/2 multiplexes streams, thousands of concurrent calls share one TCP connection.

Four call types:

TypeShapeExample
UnaryOne request, one responseGetEvent
Server streamingOne request, a stream of responsesWatch order status changes, stream search results
Client streamingA stream of requests, one responseUpload GPS points or metrics in a batch
BidirectionalBoth sides stream independentlyChat between services, live collaboration backends

Features for running services at scale:

  • Deadlines. The caller says "I will wait 200 ms". The deadline is passed along to downstream calls, so work is abandoned everywhere once the original caller has given up.
  • Cancellation propagates the same way.
  • Status codes designed for distributed systems: OK, INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED, UNAUTHENTICATED, RESOURCE_EXHAUSTED, FAILED_PRECONDITION, DEADLINE_EXCEEDED, UNAVAILABLE and others. Clients know that UNAVAILABLE is usually safe to retry and INVALID_ARGUMENT never is.
  • Interceptors (middleware) for authentication, logging, metrics and tracing.
  • Client-side load balancing, health checking and retries, configured through service config.
  • Generated code for many languages, so a Go service and a Java service share one contract with compile-time type checks.

Performance, honestly. Binary encoding, HTTP/2 multiplexing and long-lived connections make gRPC faster than JSON over HTTP/1.1. Published benchmarks vary widely, from modest gains to many times the throughput, depending on payload shape and implementation. The gain matters most when latency is dominated by the network and serialisation rather than by the work the server does. If each call spends 40 ms in a database, saving 0.2 ms of JSON parsing changes nothing. Choose gRPC for its contracts, streaming, deadlines and efficiency at high call volume, and do not optimise the protocol before the real bottlenecks are handled.

Browsers and public clients. Browsers cannot control HTTP/2 framing and trailers directly, so they cannot speak native gRPC. Options: gRPC-Web through a proxy such as Envoy; transcoding, where annotations on the .proto map methods to REST URLs and a gateway (Envoy's JSON transcoder, grpc-gateway) serves JSON to the outside while services speak gRPC inside; or Connect, which supports gRPC, gRPC-Web and a simple JSON-over-HTTP protocol from the same definitions. For clients you do not control, REST with JSON remains the norm.

GraphQL#

GraphQL, open-sourced by Facebook, exposes a single endpoint and a typed schema describing all data and relationships. Clients send queries naming exactly the fields they want; mutations change data; subscriptions stream updates.

query {
  user(id: "42") {
    name
    orders(last: 3) { id total status }
  }
}

On the server, each field is filled by a resolver function. This solves over- and under-fetching: one request returns exactly the shape a screen needs, which matters on slow mobile networks and when many front ends (web, iOS, Android, partners) need different views of the same data.

The classic problem is N+1 queries: resolving orders for 50 users naively runs 1 query for the users plus 50 for their orders. The standard fix is batching with a DataLoader, which collects keys during one request and fetches them in a single query.

Other costs: HTTP caching is harder (usually POST to one URL), expensive queries need limits (depth, complexity, timeouts), and authorisation must be enforced per field.

GraphQL in depth#

The problem it was built for. Facebook began building GraphQL in 2012, when its mobile apps needed different data from the website, and REST endpoints returned fixed shapes. Mobile teams kept asking for new endpoints or changes to existing ones, which slowed both sides down. It was open-sourced in 2015. With fixed endpoints, a front-end team building a new screen has three poor options:

  • Under-fetch and chain calls: fetch a list of 10 users, then make 10 more calls for their details. Each round trip adds latency, which hurts most on mobile networks.
  • Build big aggregation endpoints that return everything any screen might need. These over-fetch, grow slow and become hard to change, because many clients depend on them.
  • Write a new endpoint per screen, which multiplies backend work and couples back-end releases to front-end changes.

GraphQL replaces these with one endpoint and a query language. The client describes the shape it wants and the server returns exactly that shape.

Schema first. The schema defines types, fields and relationships. The ! means a value is never null:

type Course {
  id: ID!
  title: String!
  instructor: Instructor!
  lessons(first: Int, after: String): LessonConnection!
}
type Instructor { id: ID!  name: String!  avatarUrl: String }
type Query {
  course(id: ID!): Course
  courses(topic: String, first: Int, after: String): CourseConnection!
}
type Mutation { enroll(courseId: ID!): Enrollment! }
type Subscription { lessonPublished(courseId: ID!): Lesson! }

Relationships live in the schema, so a client can walk from a course to its instructor and lessons in one query. A mobile list screen might ask only for title and instructor { name }, while the web course page asks for everything, both from the same endpoint and with no backend change. This is GraphQL's main benefit: front-end teams can iterate on screens without waiting for new endpoints, as long as the fields exist in the schema.

How a query executes. The server parses the query, validates it against the schema (unknown fields or wrong argument types fail before any data is fetched), and then executes it by calling a resolver for each field, parent before child. A resolver is a function that returns a field's value, perhaps from a database, a cache or another service.

The N+1 problem, with numbers. A query for 100 courses with their instructors runs one resolver for courses (1 query), then the instructor resolver once per course (100 queries): 101 database round trips instead of 2. At 2 ms each that is about 200 ms instead of 4 ms. The standard fix is DataLoader-style batching: during one tick of execution, instructor resolvers register the IDs they need; the loader then issues one SELECT ... WHERE id IN (...) and hands each resolver its row. It also caches within one request, so the same instructor is loaded once.

Authorisation per field. REST secures endpoints. GraphQL exposes a graph, so a single query can reach data through many paths, such as course to students to emails. Authorisation must be checked in resolvers or the business layer behind them, per type and field, not only at the endpoint. A user may see a course's title but not its revenue.

Protecting the server from expensive queries. Clients can write queries that are deep (friends { friends { friends ... } }) or wide (thousands of items at each level). Defences: maximum depth, a query cost score (each field and list multiplies cost, and queries over a budget are rejected), mandatory page sizes on lists, timeouts, rate limits based on cost rather than request count, and persisted queries, where only pre-registered queries are allowed in production. Many teams also disable schema introspection for public endpoints.

Caching is different. Queries are usually POSTed to one URL, so HTTP and CDN caches cannot key on the URL. Instead, client libraries such as Apollo Client and Relay keep a normalised cache keyed by type and ID, so a course fetched by one query updates every screen that shows it. On the server side, resolvers cache their data sources. Persisted queries sent as GET requests with a hash can be cached at a CDN.

Other details worth knowing:

  • Errors come back in an errors array, usually with HTTP 200. Partial results are possible: some fields resolve and others fail. Monitoring that only watches HTTP status codes misses GraphQL errors.
  • Pagination commonly follows the Relay connection convention: edges, node, cursor and pageInfo with hasNextPage.
  • Mutations are write operations, executed one after another in the order given.
  • Subscriptions push events, usually over WebSockets.
  • Versioning is avoided: add fields freely, mark old ones @deprecated, and remove them once usage, which is measurable per field, drops to zero.

When GraphQL is worth it. Many client types with different data needs, fast-changing front ends, and several teams querying overlapping data. In an interview its benefits are often murky: requirements are fixed, so the flexibility does not show, and interviewers usually want to see how you optimise specific access patterns, where a generic graph layer can get in the way. Bring it up when the interviewer stresses flexible data fetching, many different clients, or deliberately uncertain requirements. Otherwise, mention that you considered it and stay with REST.

SOAP briefly#

SOAP is an older protocol using XML envelopes, with a formal contract in WSDL and standards for security and transactions (WS-*). It is verbose and heavy, but still used in banking, insurance, government and older enterprise integrations. New public APIs rarely choose it.

SOAP in a little more depth#

SOAP (originally "Simple Object Access Protocol") wraps every message in an XML envelope with an optional header (security tokens, transaction context, routing) and a body naming the operation:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
    <wsse:Security><!-- signed token --></wsse:Security>
  </soap:Header>
  <soap:Body>
    <GetAccountBalance xmlns="urn:bank">
      <AccountId>12345678</AccountId>
    </GetAccountBalance>
  </soap:Body>
</soap:Envelope>

A WSDL file describes the operations, message types (in XML Schema) and endpoints, and tools generate client classes from it. On top sits a family of WS-* standards: WS-Security for message-level signing and encryption (which survives passing through intermediaries, unlike TLS, which only protects each hop), WS-ReliableMessaging for guaranteed delivery, and WS-AtomicTransaction for distributed transactions. Errors come back as SOAP faults.

That formality is why SOAP is still found in banking, payments networks, insurance, healthcare, telecoms and government, where contracts are signed between organisations and change slowly. It is also why it lost the public web: XML is verbose and slow to parse, the WS-* stack is complex, almost every call is a POST to one URL (so HTTP caching does not help), and tooling outside Java and .NET is limited. Today you usually meet SOAP when integrating with an existing partner system, often wrapped behind a small adapter service that exposes REST or gRPC to the rest of your platform.

Comparison#

RESTgRPCGraphQLSOAP
ModelResources + HTTP methodsFunctions (services and methods)Typed graph, client-selected fieldsOperations in XML envelopes
FormatUsually JSONProtobuf (binary)JSONXML
TransportHTTP/1.1 or 2HTTP/2HTTP (usually POST)HTTP, others
ContractOpenAPI (optional).proto (required)Schema (required)WSDL (required)
CachingExcellent (HTTP)Application-level onlyHarder; needs persisted queries or client cachesPoor
StreamingVia SSE/WebSocketsBuilt in, bidirectionalSubscriptionsNo
Browser supportNativeNeeds gRPC-Web proxyNativePossible, rare
PerformanceGoodVery good (small payloads, multiplexing)Good; depends on resolversLower
Best fitPublic APIs, CRUD, cacheable readsInternal service-to-service, low latency, streamingMany clients with varied data needsLegacy enterprise integration

Choosing for public vs internal vs mobile clients#

  • Public / third-party APIs: REST with JSON and an OpenAPI spec. Every developer knows it, it works from any language, and it caches well. Some platforms add GraphQL for partners with complex needs.
  • Internal service-to-service: gRPC for low latency, strong typing, streaming and generated clients; REST is fine when simplicity matters more than performance.
  • Mobile and rich web front ends: GraphQL or a Backend-for-Frontend that aggregates calls into screen-shaped responses, to cut round trips on slow networks. See API Gateway.
  • Real-time: gRPC streaming internally; WebSockets or SSE to browsers. See Real-time Communication.

Mixing is normal: REST at the edge, gRPC inside, GraphQL as a gateway for front ends.

Good habits within gRPC and GraphQL#

Choosing a style is half the work; using it well is the other half. A few habits prevent most later pain.

gRPC and protobuf:

  • One request and one response message per method (GetEventRequest, GetEventResponse), even if they hold a single field today. Adding fields later is then always possible without changing the method signature.
  • Resource-oriented names even in RPC. Google's public API guidelines (the AIPs) recommend standard methods named Get, List, Create, Update and Delete on resources, plus a few custom methods. This gives RPC APIs much of REST's predictability.
  • Pagination with page tokens: List requests carry page_size and page_token, and responses return next_page_token. The token is opaque, so the server can change how it pages.
  • Field masks for partial updates: an update_mask lists which fields to change, so "not sent" is never confused with "set to empty".
  • Rich errors: return a proper status code plus structured details (which field was invalid, a retry delay), not a string to parse.
  • Lint and check for breaking changes in CI, with tools such as Buf, so an incompatible .proto change fails the build.
  • Always set deadlines on the client; a call without a deadline can wait forever.

GraphQL:

  • Design the schema around the product, not the database. Types should be what screens talk about (a Course with lessons), not a copy of tables and join keys.
  • Use connections for every list that might grow, with mandatory first arguments and a maximum.
  • Use specific mutations (enrollInCourse, cancelBooking) with input types and payload types, rather than generic "update anything" mutations. They are easier to authorise, audit and evolve.
  • Use nullable fields where failure is possible. If a field comes from a service that may be down, making it nullable lets the rest of the response succeed with a partial result.
  • Measure per-field and per-operation latency. One slow resolver can dominate a query, and per-field tracing (Apollo and others provide it) finds it.
  • Use federation or schema stitching only once several teams need to own parts of one graph. A single schema is simpler until then.

For both: generate documentation from the contract, publish example requests, and keep a changelog. Developers judge an API by how quickly they can make a first successful call.

One feature, three styles#

Take a course page that shows a course's title, its instructor's name and the first five lessons. Here is the same feature in each style.

REST: three resources, so either three requests or one endpoint that embeds related data:

GET /courses/12                      -> course with instructor_id
GET /instructors/7                   -> instructor
GET /courses/12/lessons?limit=5      -> first five lessons
or
GET /courses/12?include=instructor,lessons&lessons_limit=5

The first form makes three round trips (fine on a fast network, slow on mobile); the second form needs the server to support an include convention (JSON:API defines one), and the response is easy to cache at a CDN because it is a GET on a URL.

gRPC: one purpose-built method:

rpc GetCoursePage (GetCoursePageRequest) returns (CoursePage);
message GetCoursePageRequest { string course_id = 1; int32 lesson_limit = 2; }
message CoursePage { Course course = 1; Instructor instructor = 2; repeated Lesson lessons = 3; }

This is fast and typed, and exactly right for the call. But every new screen tends to get a new method, which is the "new API per use case" cost of RPC.

GraphQL: one query in the shape of the screen:

query {
  course(id: "12") {
    title
    instructor { name }
    lessons(first: 5) { edges { node { title durationMinutes } } }
  }
}

No backend change is needed when the screen later adds the instructor's avatar; the client asks for one more field. The server must batch the instructor and lesson lookups, and HTTP caching of the response needs persisted queries.

All three work. The choice depends on who the clients are, how often screens change, how much caching matters and what the team already runs well.

A short history, and why it matters#

Distributed calls are old. Sun RPC (1980s), CORBA (1990s), Microsoft's DCOM and Java RMI all tried to make remote objects look local, and all struggled with tight coupling, complex tooling and firewalls that blocked their custom protocols. SOAP (around 1998-2000) moved RPC onto HTTP and XML, so calls could pass through the web's infrastructure, but brought heavy standards. REST, described by Fielding in 2000, won the public web in the late 2000s together with JSON, because it reused HTTP's own semantics, caching and tooling instead of building on top of them. Inside large companies, binary RPC never went away: Google's internal Stubby system became the basis for gRPC (open-sourced in 2015), and Facebook's Thrift (open-sourced in 2007) played the same role. GraphQL (2015) answered a problem that only appeared once many mobile and web clients shared one backend.

The pattern is useful: styles that fight the web's infrastructure lose on the public internet, and styles that ignore performance lose inside the data center. That is why today's common pattern is REST at the edge and binary RPC inside, with GraphQL or BFF layers where client diversity demands it.

Security differences between styles#

  • REST: authentication with bearer tokens or API keys in headers. Authorisation per endpoint and per resource, which must check ownership: does booking 555 belong to this user? Missing that check (broken object-level authorisation) is the most common serious API vulnerability, and it is first on the OWASP API Security Top 10.
  • gRPC: usually internal, secured with mutual TLS between services (often through a service mesh) and per-method authorisation in interceptors. Do not expose internal methods to the internet just because the gateway can route them.
  • GraphQL: in addition to per-field authorisation, it is exposed to query-cost attacks (deep or wide queries), to batching attacks (many operations in one request, used to bypass per-request rate limits on login attempts) and to schema discovery through introspection. Use cost limits, operation-count limits, persisted queries and rate limits based on cost.
  • SOAP: message-level signing and encryption with WS-Security, and the need to harden XML parsers against XML external entity attacks.

For all styles, validate input against the contract, apply rate limits at the gateway, and never trust identifiers in the request body over the authenticated identity. See Authentication and Authorization.

Other styles you will meet#

  • JSON-RPC: a tiny RPC protocol where each request is a JSON object with a method name, parameters and an ID. Used by Ethereum nodes and by the Language Server Protocol that powers editor features.
  • tRPC: end-to-end typed procedures for TypeScript projects where client and server share one codebase. There is no schema file; types flow from the server code. It suits full-stack TypeScript apps, not public or polyglot APIs.
  • OData: a standard for REST APIs with query options in the URL ($filter, $select, $expand), common in Microsoft and SAP ecosystems. It offers some of GraphQL's flexibility within REST conventions.
  • Event-driven (asynchronous) APIs: instead of request and response, producers publish events to a broker (Kafka, a message queue) or call webhooks, and consumers react. They are described with AsyncAPI documents the way REST is described with OpenAPI. See Event-Driven Architecture.
  • Persistent connections: WebSockets and SSE are not request/response styles at all; they carry messages whose format you define, often JSON. See Real-time Communication.

Choosing in practice: one system, several styles#

Most real systems use more than one style, each at the boundary where it fits best. A ticketing platform might look like this:

How to reason about each boundary:

  • Public and partner APIs: REST with JSON and an OpenAPI document, versioned, with SDKs for the main languages. The audience is unknown and diverse, so universality and stability matter most.
  • Your own web app: REST through the gateway is usually enough. Add GraphQL if many screens and teams need different combinations of the same data.
  • Your own mobile apps: a Backend-for-Frontend (BFF) or GraphQL so that each screen needs one round trip. Mobile clients stay installed for months or years, so the BFF also absorbs changes in the services behind it without breaking old app versions.
  • Internal service to service: gRPC where call volume or latency matters, or where many languages need one typed contract. REST is perfectly acceptable for low-volume internal APIs, and many companies use it throughout.
  • External legacy systems: whatever they require, often SOAP, isolated behind an adapter.
  • Things that just happened: events on a stream or queue, and webhooks to and from outside companies.

In an interview you usually define only the user-facing API during the API step, as REST unless there is a reason not to, and then mention in the high-level design that internal services talk over gRPC or REST. Do not spend interview time designing every internal method.

API vs SDK#

An API is the contract: endpoints, messages, rules. An SDK (software development kit) is a client library in a specific language that wraps the API: it handles authentication, retries, pagination, serialisation and types. Good platforms ship SDKs for popular languages so developers call client.orders.create(...) instead of building HTTP requests. gRPC and GraphQL tooling generate much of an SDK from the contract; REST SDKs are often generated from OpenAPI specs.

API vs SDK in depth#

An API defines what can be done and how messages look. An SDK packages that API as a library in a particular language, so developers call methods instead of building HTTP requests. A good SDK takes care of the parts every client otherwise reimplements, often badly:

  • Authentication: signing requests (as AWS's Signature Version 4 does) or refreshing OAuth tokens.
  • Retries with backoff and jitter on safe errors, with idempotency keys added automatically to retried writes.
  • Pagination as an iterator, so for order in client.orders.list() walks every page.
  • Typed models and typed errors, so mistakes are caught by the compiler or editor.
  • Timeouts and connection pooling with sensible defaults.
  • Telemetry hooks for logging and tracing.

Generated or hand-written? Generating SDKs from the contract (OpenAPI, protobuf, or a modelling language such as AWS's Smithy) keeps many languages in sync with the API automatically. Hand-written layers on top add idiomatic touches that generators miss. Large API providers typically combine both.

When to ship a native library instead of only a raw API. A client library makes sense when you know the target platforms, want to control how your functionality is accessed, want to control how errors and retries are handled on the client, or when performance and the developer experience are the main concern. The costs are maintenance per language, versioning (old SDK versions stay installed for years and keep calling your API) and the risk that a bug in the SDK reaches every customer. Hence the rule: the API is the contract, and the SDK is a convenience on top. Never add behaviour that only the SDK can reach, because some customers will always call the API directly.

Performance and cost, worked through#

Consider a booking flow in which one user request fans out to 5 internal calls, at 20,000 user requests per second: 100,000 internal calls per second.

  • Payload size. If each internal response is 2 KB as JSON and 0.8 KB as protobuf, internal traffic is about 200 MB/s versus 80 MB/s. That is meaningful network and CPU at scale, especially across zones, where cloud providers often charge for data transfer.
  • Serialisation CPU. If encoding plus decoding a 2 KB JSON message costs about 20-50 microseconds and protobuf a fraction of that, 100,000 calls per second spend several CPU cores just on JSON. At this scale that becomes a real cost; at 100 calls per second it is noise.
  • Connections. HTTP/1.1 needs one connection per concurrent request (or queues requests behind each other); HTTP/2, which gRPC requires, multiplexes them on a few connections.
  • Latency budget. If the 5 calls run in sequence and each takes 3 ms of network and serialisation plus 5 ms of work, the user waits 40 ms. Running independent calls in parallel matters more than the choice of encoding.

The lesson: the choice of style changes efficiency by a constant factor, while the shape of the calls (how many, sequential or parallel, how chatty) often changes it by much more. Fix the shape first.

When to Use It#

  • REST: default for public APIs, CRUD-style resources, cacheable reads, and broad client compatibility.
  • gRPC: high call volume between services, strict latency budgets, polyglot microservices, streaming.
  • GraphQL: many client types needing different shapes of related data, fast-moving front ends.
  • SOAP: only when integrating with systems that require it.

When NOT to Use It#

  • Do not use gRPC for public browser APIs unless you are ready to run gRPC-Web proxies.
  • Do not adopt GraphQL for a simple CRUD API with one client; you inherit caching, security and N+1 complexity for little gain.
  • Do not force RPC-style verbs into REST URLs (/getUserOrders); pick one style per API and stay consistent.

How to Implement It#

  1. Identify the clients: public developers, internal services, your own mobile and web apps.
  2. Pick a style per boundary: REST at the public edge, gRPC inside, GraphQL or a BFF for front ends if needed.
  3. Write the contract first (OpenAPI, .proto, GraphQL schema) and generate code and docs from it.
  4. Add cross-cutting rules: auth, rate limits, pagination, errors and versioning. See API Design.
  5. For GraphQL, add DataLoader batching, query depth and complexity limits, and per-field authorisation from day one.
TechnologyFits when
OpenAPI + Swagger toolsDocumenting and generating clients for REST APIs
gRPC + protobuf, BufTyped internal APIs and code generation
Apollo Server/Federation, GraphQL Yoga, HasuraGraphQL servers and federated schemas
gRPC-Web, EnvoyExposing gRPC to browsers
Connect RPC, TwirpSimpler RPC over HTTP with protobuf

Trade-offs#

StyleGainCostPick when
RESTSimple, universal, cacheableOver/under-fetching, verbose JSONPublic APIs, CRUD
gRPCFast, typed, streamingBrowser support, harder debugging, no HTTP cachingInternal, high-volume calls
GraphQLExact data per screen, one round tripN+1 risk, caching and security complexityMany varied clients
SOAPFormal contracts, enterprise standardsHeavy XML, complex toolingLegacy integrations
Backend-for-FrontendScreen-shaped responses, absorbs service changesOne more service per client typeMobile apps, very different front ends
Transcoding gRPC to RESTOne contract, JSON outside, protobuf insideGateway configuration, mapping limitsTeams standardised on protobuf with public clients
JSON-RPC or tRPCVery simple, typed in one codebaseNot suited to public or polyglot APIsInternal tools, full-stack TypeScript

Common Pitfalls#

  • Choosing GraphQL because it is popular, then shipping N+1 queries and unbounded query costs.
  • Making breaking protobuf changes (reusing field numbers) that crash older clients.
  • REST APIs that use POST for everything, losing caching and idempotency semantics.
  • Exposing internal gRPC services directly to the internet without a gateway.
  • Designing REST URLs as verbs (/createBooking), which mixes styles and loses method semantics.
  • Taking the user ID from the request body instead of the authentication token.
  • Balancing gRPC with an L4 load balancer, so new servers receive no traffic from existing clients.
  • Returning GraphQL errors inside HTTP 200 responses and monitoring only HTTP status codes.
  • Sending large files through RPC messages instead of object storage with signed URLs.

Real-World Examples#

Google created gRPC and released it as open source in 2015; it is now a Cloud Native Computing Foundation project used widely for internal service communication.

Facebook developed GraphQL for its mobile apps and released it publicly in 2015; GitHub offers a public GraphQL API alongside its REST API.

GitHub publishes both a REST API and a GraphQL API, which lets integrators choose between simple endpoints and precise queries. Stripe offers a REST API with official SDKs in many languages and dated API versions, so each account stays pinned to the behaviour it integrated against. Google's public cloud APIs are defined in protobuf and served both as gRPC and as REST with JSON from the same definitions.

In the Interview#

The API step in an interview#

In a structured interview, defining the API is a short step, often about five minutes, between listing core entities and drawing the high-level design. Most interviewers do not expect a perfect API. They want a reasonable one quickly, so that the time goes to the hard parts. (Front-end, product and more junior roles may spend longer here.)

A good routine:

  1. State the style in one sentence: "REST with JSON for the client-facing API." Change this only for a reason, such as many clients with varied data needs (GraphQL) or a purely internal, high-throughput API (gRPC).
  2. Derive resources from your core entities, one or two endpoints per functional requirement.
  3. Write each endpoint as method, path, input and output: POST /events/:id/bookings with seats and payment method in, a booking out.
  4. Put authentication in a header and derive the user from the token, never from a userId field in the body that a client could forge.
  5. Mention pagination for lists and idempotency keys for payments and bookings.
  6. Move on. Note that internal calls use gRPC or REST when you draw the services.

Follow-up questions to expect#

  • "Why REST and not gRPC for the mobile app?" Clients I do not control, browser support, easy debugging and HTTP caching. gRPC fits inside, between my own services.
  • "The mobile home screen needs data from five services." Add a BFF or GraphQL layer that fetches in parallel on the server side, close to the services, and returns one screen-shaped response.
  • "How would you stream order updates?" gRPC server streaming between internal services; SSE or WebSockets to clients.
  • "How do you avoid breaking clients?" Additive changes only, protobuf field numbers never reused, GraphQL fields deprecated before removal, REST versions for breaking changes.
  • "GraphQL is slow for this query." Check for N+1 resolvers and add DataLoader batching, add cost limits, and consider a dedicated optimised resolver or REST endpoint for the hot path.
Deep Dive: Schema evolution, federation and performance detailsShow

Schema evolution. Protobuf identifies fields by number, so you can add fields freely; old clients ignore unknown ones. You must never reuse a field number or change its type; mark removed fields reserved. GraphQL evolves by adding fields and deprecating old ones (with the @deprecated directive), avoiding versions entirely. REST typically uses additive changes plus URL or header versions for breaking ones.

GraphQL federation. In large organisations, one GraphQL schema is assembled from many teams' sub-schemas (Apollo Federation and similar). A router plans each query across the owning services. This keeps one API for clients while each team owns its part, but query planning adds latency and a new critical component.

Persisted queries. Clients register allowed GraphQL queries ahead of time and send only a hash. This allows CDN caching via GET, blocks arbitrary expensive queries, and reduces request size.

gRPC load balancing. Because gRPC multiplexes over long-lived HTTP/2 connections, L4 load balancers send all of a client's calls to one server. Use L7 (request-level) balancing, client-side balancing, or limit connection age.

JSON is not always slow. For many APIs the database dominates latency, and JSON overhead is a small fraction. Choose gRPC for its contracts, streaming and efficiency at high volume, not as a fix for a slow query.

Deep Dive: Compatibility rules for each styleShow

Contracts change for as long as an API lives. Knowing exactly what each style allows prevents most outages caused by API changes.

Protobuf (gRPC, and Kafka with protobuf schemas):

  • Safe: add a new field with a new number; old readers skip unknown fields, and new readers see default values (zero, empty) when old writers omit them.
  • Safe: remove a field, if its number and name are marked reserved so they are never reused.
  • Unsafe: reuse a field number for a different meaning, or change a field's type incompatibly. Old data will be decoded as the wrong thing, silently.
  • Subtle: in proto3, a scalar field set to its default value is not sent, so "not set" and "zero" look the same. Use optional or wrapper types when the difference matters, such as a price of 0 versus unknown.
  • Renaming a field is safe on the wire, since names are not sent, but it breaks JSON transcoding and generated code.

GraphQL:

  • Safe: add types, fields and optional arguments.
  • Unsafe: remove or rename fields, make a nullable field non-null in an input, or add a required argument.
  • Practice: mark fields @deprecated(reason: ...), track per-field usage from query logs, and remove a field only when usage is zero. This replaces versioning almost entirely.

REST and JSON:

  • Safe: add optional request fields and new response fields, provided clients ignore unknown fields (the "tolerant reader" rule; document it).
  • Unsafe: remove or rename fields, change types or meanings, make optional input required, or change status codes that clients branch on.
  • Practice: make additive changes within a version, and for breaking changes introduce /v2 (or a dated version header, as Stripe does) and support the old version for a published period.

Avro and schema registries. In data pipelines, readers and writers may use different schema versions. Avro resolves the writer's schema against the reader's schema, and schema registries (such as Confluent Schema Registry) check every new schema version for backward or forward compatibility before producers may use it.

Consumer-driven contract tests (for example Pact) let each client publish the interactions it relies on, and the provider's build fails if a change would break any of them. This turns compatibility from a review checklist into an automated test.

Deep Dive: Streaming, transport and load balancing differencesShow

HTTP/1.1, HTTP/2 and connection behaviour. REST over HTTP/1.1 opens several connections per client and spreads naturally across servers behind any load balancer. gRPC's long-lived HTTP/2 connections carry many calls, so an L4 load balancer that balances connections, not requests, can pin all of one client's traffic to one server even after new servers are added. The fixes are L7 balancing per request (Envoy, Linkerd, cloud L7 load balancers with HTTP/2 support), client-side balancing using a list of endpoints from service discovery, or a maximum connection age so clients reconnect and rebalance periodically.

Flow control. HTTP/2 has per-stream and per-connection flow-control windows, so a slow reader of one gRPC stream does not stall other streams on the same connection. Within one stream, a sender that writes faster than the receiver reads will eventually block, which is natural backpressure for streaming RPCs.

Streaming across styles. gRPC has native streaming in both directions. GraphQL subscriptions usually run over WebSockets (the graphql-ws protocol) or SSE. REST has no streaming of its own and relies on SSE, WebSockets or long polling. For large downloads, REST supports range requests and resumable transfers, which RPC frameworks do not offer out of the box. That is one reason file transfer usually happens over plain HTTP to object storage even in gRPC-heavy systems.

Message size limits. gRPC implementations cap message size by default, commonly at 4 MB for received messages. Large payloads should be streamed in chunks, or uploaded to object storage with only a reference passed through the RPC.

Retries and idempotency across styles. REST signals idempotency through methods, gRPC through method options and service-config retry policies, and GraphQL not at all (mutations are POSTs). Whatever the style, a retried write must carry an idempotency key or be designed to be idempotent. See Idempotency.

Key Takeaways#

  • REST models resources with HTTP methods and is the default for public, cacheable APIs.
  • gRPC uses protobuf over HTTP/2 for fast, typed, streaming calls, mainly between internal services.
  • GraphQL lets clients request exactly the fields they need through one schema, at the cost of N+1 risk and harder caching.
  • SOAP survives in legacy enterprise integrations; rarely choose it for new APIs.
  • Choose per boundary: REST at the edge, gRPC inside, GraphQL or a BFF for varied front ends; ship SDKs for developer convenience.
  • Default to REST for client-facing APIs; switch only for a stated reason.
  • REST exposes data as resources with methods whose safety and idempotency guarantees matter for retries; RPC exposes behaviour as procedures.
  • gRPC brings binary protobuf, HTTP/2, streaming, deadlines and generated clients; use it mainly between your own services.
  • GraphQL fixes over- and under-fetching for varied clients, but needs batching, cost limits, field-level authorisation and different caching.
  • Optimise the shape of calls (count, parallelism) before the encoding, and keep the API, not the SDK, as the real contract.