REST vs gRPC vs GraphQL vs WebSockets: how to choose an API protocol

Four popular ways for software to talk, each built for a different job. Learn how REST, gRPC, GraphQL and WebSockets work, where each one shines, where each one breaks, and how real systems use all four together.

Four plug sockets on a wall, each a different shape, labelled REST, gRPC, GraphQL and WebSockets. Under each, a small picture of what it is good at - an open book for REST (readable by anyone), a lightning bolt for gRPC (fast between services), a shopping list for GraphQL (ask for exactly what you need) and two arrows going both ways for WebSockets (live, two-way).
Fig. 1 — Like plug sockets, API protocols are standards. The trick is knowing which socket fits which device.

Imagine you’re building a social media app. Very quickly, you need four different kinds of conversation:

  • Outside developers want to build tools on top of your app. They need an API that’s easy to read and test.
  • Inside your system, the feed service asks the user service for profiles thousands of times a second. Every millisecond and every byte counts.
  • The mobile app’s profile screen needs a user, their posts, comments and like counts, ideally in one trip over a slow phone network.
  • Chat must deliver a message the instant it’s sent, without the phone asking “anything new?” every second.

No single protocol is good at all four. That’s why REST, gRPC, GraphQL and WebSockets all exist, and why big systems use all of them at once.

In the last article we looked at how services wait for each other. This one is about the language they speak: the API protocols that carry the messages.

What an API protocol really is

An API (application programming interface) is a contract between two pieces of software. It answers four questions:

  1. What data do I send?
  2. How is it formatted?
  3. Where do I send it?
  4. What do I get back, and what happens if something goes wrong?

A protocol is a shared set of rules for that contract, so every team doesn’t invent its own.

Think of plug sockets. Countries use different designs, but inside one country every device follows the same standard, so any lamp works in any socket. API protocols do the same for software: a Java service and a Python service can talk because they both follow the same rules.

The four protocols at a glance

Four panels showing the shape of each conversation. REST: a client asks for a resource by URL, GET /users/123, and gets back readable JSON. gRPC: two services share a .proto contract and call each other's functions directly, sending small binary messages over HTTP/2, with streaming. GraphQL: a client sends one query to a single /graphql endpoint listing exactly the fields it wants, and gets back exactly that shape. WebSockets: a client and server open one connection that stays open, and messages flow both ways at any time.
Same goal, four very different shapes of conversation.
REST gRPC GraphQL WebSockets
Main idea Resources at URLs Call a function on another service Ask for exactly the fields you want A connection that stays open
Data format JSON (text) Protocol Buffers (binary) JSON (text) Anything, often JSON
Direction Client asks, server answers Both, including streams Client asks, server answers Both ways, any time
Readable by humans? Yes No Yes Depends
Works in browsers? Yes Only through a proxy Yes Yes
Best at Public APIs, simple CRUD Fast service-to-service calls Flexible screens, many clients Live, real-time updates

Let’s look at each one properly.

REST: the web’s default

REST (Representational State Transfer) treats everything as a resource with its own URL, and uses the standard HTTP methods to act on it:

GET    /api/v1/users/123     → read user 123
POST   /api/v1/users         → create a new user
PUT    /api/v1/users/123     → replace user 123
PATCH  /api/v1/users/123     → change part of user 123
DELETE /api/v1/users/123     → delete user 123

The server answers with JSON and a status code that tells you what happened: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error.

REST is stateless: every request carries everything the server needs, so any server can handle it. That makes it easy to scale behind a load balancer. In Spring Boot, a REST endpoint is just a few lines:

// Java · UserController.java
@RestController
@RequestMapping("/api/v1/users")
class UserController {
    @GetMapping("/{id}")
    UserResponse get(@PathVariable String id) {
        return users.findById(id)
                .map(UserResponse::from)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
    }
}

Why people love REST:

  • Everyone knows it. Any language, any tool, even curl in a terminal, can call it.
  • JSON is easy to read and debug.
  • HTTP caching works for free. A GET response can be cached by browsers and CDNs.

Where REST struggles:

  • Over-fetching: you ask for a user and get 40 fields when the screen needs 3.
  • Under-fetching: the screen needs the user and their posts and comments, so the app makes many calls, one after another.
  • Text is bigger and slower to parse than binary, which matters at very high volume.

Use REST for: public APIs, web apps, simple create-read-update-delete services, and anything where being easy to understand matters most. When in doubt, start with REST.

gRPC: fast calls between services

gRPC (an open-source framework first built at Google) lets one service call a function on another service as if it were a local method. You define the contract once, in a .proto file:

// user.proto
service UserService {
  rpc GetUser (GetUserRequest) returns (User);                 // one request, one reply
  rpc WatchUsers (WatchRequest) returns (stream User);         // one request, a stream of replies
}

message GetUserRequest { string user_id = 1; }

message User {
  string id = 1;
  string name = 2;
  string email = 3;
}

A tool then generates client and server code from that file, in Java, Go, Python and many other languages. Calling another service feels like calling a method:

// Java · generated client stub
User user = userStub.getUser(GetUserRequest.newBuilder().setUserId("123").build());
A .proto contract file in the middle. Arrows go out to generated code in Java for the feed service and generated code in Go for the user service. Between them, a fast lane labelled HTTP/2 carries small binary messages. Underneath, the same user record is shown twice: as JSON text with field names repeated in every message, and as a much shorter row of binary bytes, labelled Protocol Buffers: field numbers instead of names.
One contract, code generated for every language, and small binary messages on the wire.

Why gRPC is fast and safe:

  • Protocol Buffers are binary. Messages send field numbers instead of field names, so they’re much smaller than JSON and quicker to read.
  • It runs on HTTP/2, which sends many calls over one connection at the same time.
  • Strong types. If you send the wrong type, your code won’t compile. Mistakes show up before production, not in it.
  • Streaming is built in. A server can stream results back, a client can stream data up, or both at once.

Where gRPC struggles:

  • Browsers can’t call it directly. You need a proxy (gRPC-Web) or a REST gateway in front.
  • You can’t just read it. Binary messages need special tools to inspect and debug.
  • More setup: .proto files, code generation, and a learning curve for the team.

Use gRPC for: internal calls between your own microservices, especially busy ones, and anywhere you want streaming or strict contracts across languages.

GraphQL: ask for exactly what you need

GraphQL (first built at Facebook for its mobile apps) turns the usual REST model around. Instead of the server deciding what each URL returns, the client writes a query listing exactly the fields it wants, and sends it to one endpoint:

query {
  user(id: "123") {
    name
    posts(last: 10) {
      text
      likeCount
      comments { text author { name } }
    }
  }
}

The answer comes back in exactly that shape: no extra fields, no missing pieces, one round trip.

Left, REST: a phone makes many separate calls in a row: GET /users/123, GET /users/123/posts, then ten calls to GET /posts/id/comments, 12 round trips in total. Each reply also carries fields the screen doesn't use, shown greyed out. Right, GraphQL: the phone sends one query to /graphql and gets back one reply with exactly the name, posts, likes and comments the screen needs.
REST can need many trips and send extra data. GraphQL gets one screen's data in one trip.

Behind the scenes, the server has a schema (the list of types and fields) and small functions that fetch each field. With Spring for GraphQL:

// Java · UserGraphqlController.java
@Controller
class UserGraphqlController {
    @QueryMapping
    User user(@Argument String id) { return users.findById(id); }

    @BatchMapping   // loads posts for ALL users in the reply with one query, not one per user
    Map<User, List<Post>> posts(List<User> users) { return posts.findByAuthors(users); }
}

That @BatchMapping matters. Without batching, a list of 100 users can trigger 1 query for the users and 100 more for their posts: the N+1 problem. Batching (often called a DataLoader) turns that into 2 queries.

Why teams pick GraphQL:

  • No over-fetching or under-fetching. Great on slow mobile networks.
  • One API serves many clients. Web, iOS and Android each ask for what their screen needs, with no new endpoint per screen.
  • Self-documenting. Tools can read the schema and show every type and field.

Where GraphQL struggles:

  • Caching is harder. Everything is a POST to one URL, so ordinary HTTP caching doesn’t help much.
  • Clients can write very expensive queries, by accident or on purpose (more on this below).
  • More work on the server: resolvers, batching, and checking permissions on every field.

Use GraphQL for: apps with many different screens or many client types, especially mobile, and when front-end teams need to move without waiting for new endpoints.

WebSockets: a line that stays open

REST, gRPC calls and GraphQL queries mostly follow the same pattern: the client asks, the server answers. But what if the server has news? With a normal API, the client has to keep asking: “Anything new? Anything new?” That’s called polling.

A WebSocket opens one connection that stays open. After that, either side can send a message at any time. The server can push a chat message, a price change or a “your rider is 2 minutes away” update the moment it happens.

Two timelines over the same 10 seconds. Polling: the client asks the server 'anything new?' every second, ten requests, and nine of the answers are 'no'; the one real update arrives up to a second late. WebSocket: one connection opens at the start and stays open, and the server pushes the update the instant it happens. A third, smaller row shows Server-Sent Events: one open connection where only the server sends.
Polling asks again and again. A WebSocket waits on an open line and hears news straight away.

Why WebSockets are great for live features:

  • Instant updates, both ways.
  • Very little overhead per message, because the connection is already open.

Where they struggle:

  • Connections are long-lived and stateful. A server holding 100,000 open connections can’t be swapped out casually, and load balancers must keep each client on the same server.
  • Messages must reach users on other servers. If Alice is connected to server 1 and Bob to server 7, server 1 needs a way to pass Alice’s message along, usually a pub/sub system like Redis or Kafka between the servers.
  • Connections drop on every tunnel and lift. Clients need to reconnect with backoff (wait 1 s, 2 s, 4 s…) and ask “what did I miss since message 5,281?”

Use WebSockets for: chat, multiplayer games, collaborative editing, live dashboards and trading screens, anything where waiting even a second feels broken.

How real systems use all four

Back to the social media app. You don’t pick one protocol. You pick one per kind of conversation, often behind an API gateway that is the single front door:

An architecture diagram. On the left, three kinds of clients: partner developers using REST, a mobile app using GraphQL, and a web browser that also opens a WebSocket for chat. They all go through an API gateway. Behind the gateway, a chat service keeps the WebSocket connections. The GraphQL layer and the gateway call internal services, Feed, User and Post, using gRPC, shown as fast lanes. A Redis pub/sub box connects the chat servers.
Each protocol where it fits: REST outside, GraphQL for apps, gRPC inside, WebSockets for live features.
  • REST for the public API: partners can read the docs and test with curl.
  • GraphQL for the mobile and web apps: each screen gets its data in one trip.
  • gRPC between internal services: the feed service calls the user service thousands of times a second, cheaply.
  • WebSockets for chat, notifications and “online” dots.

Changing an API without breaking everyone

Once other people depend on your API, every change is risky. Rename one field from userName to name, and every app still reading userName breaks the moment you deploy.

The golden rule: add, don’t change or remove.

  • Adding a new optional field is safe. Old clients ignore it.
  • Renaming, removing or changing the type of a field is a breaking change.

When you truly must break something:

Protocol How to evolve safely
REST Keep the old field next to the new one for a while. For big changes, publish a new version (/api/v2/users) and keep /v1 running until clients move.
gRPC Add new fields with new numbers. Never reuse or change a field number; mark removed ones as reserved.
GraphQL Add new fields, and mark old ones @deprecated(reason: "Use name"). Watch usage, and remove them only when no one asks for them.
WebSockets Put a type and version in every message, so clients can ignore messages they don’t understand.

What breaks, and how to fix it

What breaks Example The fix
A breaking REST change A renamed field crashes old app versions still on users’ phones Add, don’t rename. Version big changes.
gRPC service down Calls fail at once with UNAVAILABLE Deadlines on every call, a few retries with backoff, and a circuit breaker
An expensive GraphQL query A deeply nested query makes the server run millions of database queries Depth and complexity limits, timeouts, batching, and only allowing approved queries in production
A dropped WebSocket The phone enters a tunnel and misses messages Reconnect with backoff, then resume from the last message ID

The GraphQL one surprises people. With Spring for GraphQL, adding limits takes a couple of beans:

// Java · GraphqlLimits.java (graphql-java instrumentations, picked up by Spring Boot)
@Configuration
class GraphqlLimits {
    @Bean Instrumentation maxDepth()      { return new MaxQueryDepthInstrumentation(10); }
    @Bean Instrumentation maxComplexity() { return new MaxQueryComplexityInstrumentation(1000); }
}

Puzzle 1: the deep query

Every level multiplies the work. 100 users, each with 100 posts, each with an author who has 100 posts… after a few levels you’re asking the database for millions of rows. One query can take your server down. It’s a cheap attack, and an easy accident.

Fixes, from simplest: limit the depth (say, 10 levels), limit the complexity (give each field a cost and reject queries over a budget), add a timeout, batch database calls, and for your own apps, use persisted queries: only queries you’ve approved in advance can run. GraphQL’s flexibility needs limits.

Puzzle 2: is faster always better?

It depends on who’s calling. If it’s a busy internal service making thousands of calls a second, 10% faster and smaller messages can save real money: keep gRPC. If it’s a public API, or browsers call it, 5 ms isn’t worth losing readable JSON, easy testing and browser support: go back to REST.

Often the best answer is both: gRPC inside, REST at the edge, and a gateway that translates. Speed is one trade-off, not the only one.

Puzzle 3: live prices for a million users

Polling means a million requests every second, and most of them get back “no change”. Prices also arrive up to a second late. The upside: each request is simple and easy to cache and load-balance.

A WebSocket means a million open connections, but data only flows when the price actually changes, and it arrives instantly. Since prices change often and users are watching closely, WebSockets (or SSE) win here. If users only glance at the price now and then, plain polling with a CDN cache is cheaper and simpler.

A quick way to choose

  1. Is it a public API, or are you not sure? → REST.
  2. Is it busy service-to-service traffic inside your system? → gRPC.
  3. Do many screens or clients need different shapes of the same data? → GraphQL.
  4. Must the server push updates instantly? → WebSockets, or SSE if only the server sends.

Key takeaways

  1. An API is a contract, and a protocol is the shared set of rules for it.
  2. REST is simple, readable and cacheable. It’s the right default, and the best choice for public APIs.
  3. gRPC is fast, typed and great for streaming, best for internal service-to-service calls.
  4. GraphQL lets clients ask for exactly what they need, but needs batching and query limits.
  5. WebSockets keep a two-way line open for live features, but connections are harder to scale. Consider SSE for one-way pushes.
  6. Real systems mix them. Pick per conversation, and add instead of change so you never break your clients.

Next in this thread: when you send a message, will it arrive at most once, at least once, or exactly once? That’s message delivery semantics.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.