SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

REST, GraphQL, gRPC

Three popular API styles, and how to choose between them.

⏱ 16 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

REST, GraphQL and gRPC are three popular ways to build an API. Each one is best at something different.

  • REST: many URLs, one per β€œthing”. Simple, cacheable, works everywhere. The default for public APIs.
  • GraphQL: one URL. The client asks for exactly the fields it needs. Great for varied screens.
  • gRPC: call a named function on another service, with small binary messages. Great between services.

02Concept: What is it?

🌐REST
Resources with URLs, and HTTP methods (GET, POST, PUT, DELETE).
🧬GraphQL
A query language. You describe the shape of the answer you want.
⚑gRPC
Remote procedure calls (RPC) with Protobuf over HTTP/2.

REST in one minute

REST (Representational State Transfer) treats everything as a resource with a URL. You use the standard HTTP method to say what to do, and the status code tells you how it went. The server keeps no memory of you between calls (stateless).

GraphQL in one minute

There is one endpoint. The client sends a query that lists the exact fields it wants, even across related things. The server returns exactly that shape. A schema defines what can be asked.

gRPC in one minute

You write a .proto file that lists services and methods. Tools make client and server code in many languages. Messages are Protobuf (binary) and travel over HTTP/2, which also allows streaming.

🧠No single winner
These are tools. Many companies use all three: REST or GraphQL for the outside world, and gRPC between inside services.

03Real-Life Example

🍡Three ways to order food
  • REST = a fixed-menu canteen. Each counter has one thing: β€œbiryani”, β€œraita”, β€œdessert”. You visit three counters and each gives you a full plate.
  • GraphQL = a build-your-own bowl. You say exactly what goes in: β€œrice, two kebabs, no onions”. One counter, one bowl, nothing wasted.
  • gRPC = a kitchen walkie-talkie. Staff use short, agreed codes to talk to each other. Very fast. Customers do not use it.
One screen: user profile + 3 posts
REST
πŸ“±App
↓GET /users/7
↓GET /users/7/posts
πŸ–₯️2 requests
GraphQL
πŸ“±App
↓one query
πŸ–₯️1 request
gRPC
πŸ“±App
↓GetProfile()
πŸ–₯️1 binary call
Food
API
Counter per dish
One URL per resource (REST)
A full plate even if you want one item
Over-fetching
Visiting many counters
Under-fetching: many requests
Build-your-own bowl
GraphQL query
Kitchen walkie-talkie
gRPC between services

04Why Do We Need It?

Different clients and different jobs need different things. There are three big problems that these styles try to solve:

πŸ“¦Over-fetching
The API sends 40 fields when the screen needs 3.
πŸ”Under-fetching
One call is not enough, so the app makes many calls.
🐒Slow internal calls
Thousands of service-to-service calls need small, fast messages.
πŸ“±Many clients
Web, mobile and watch each need different data.
πŸ§ͺTyped contracts
Teams want errors found when building, not in production.
🌍Easy for everyone
Public APIs must be easy for any developer to try.
REST is simple and universal. GraphQL gives clients control. gRPC gives speed and strong contracts.

05Where Do We Use It?

StyleUsed a lot forExamples (general idea)
RESTPublic APIs, CRUD apps, simple back-endsPayment, maps and cloud provider APIs
GraphQLApps with many screens and mobile clients, aggregating many back-endsSocial and e-commerce front-ends; GitHub offers a GraphQL API
gRPCService-to-service calls, streaming, low latencyMicroservices inside a company; Kubernetes and etcd use it
A common setup
πŸ“±Web / mobile
→↓REST or GraphQL
πŸšͺAPI gateway
→↓gRPC
πŸ‘€User service
πŸ“Post service
πŸ’³Payment service
Outside world uses REST or GraphQL. Inside, services use gRPC.

06Types / Parts / How It Works

REST

Resources + methods
GET    /users/7              β†’ read user 7                200 OK
GET    /users/7/posts?limit=3 β†’ read his latest 3 posts   200 OK
POST   /users                β†’ create a user              201 Created
PUT    /users/7              β†’ replace user 7             200 OK
PATCH  /users/7              β†’ change part of user 7      200 OK
DELETE /users/7              β†’ remove user 7              204 No Content
  • Nouns in URLs (/orders), verbs in HTTP methods.
  • Stateless: each request has all it needs (like a token). That makes it easy to scale.
  • Caching: GET responses can use normal HTTP caches and CDNs.
  • Pagination: ?limit=20&cursor=abc (cursor-based scales better than page numbers on big data).
  • Versioning: /v1/… or a header, so you can change without breaking clients.
  • OpenAPI: a file that describes your REST API, used to make docs, mocks and client code.

GraphQL

One request, exact fields
POST /graphql
{
  user(id: 7) {
    name
    avatar
    posts(first: 3) { title }
  }
}

β†’ { "data": { "user": { "name": "Asha", "avatar": "…", "posts": [ {"title":"Hi"}, … ] } } }
  • Query reads data. Mutation changes data. Subscription streams updates.
  • Almost always answers 200 OK, with an errors list inside the body when something fails.
  • The N+1 problem: a naive server runs one database query for the list, then one more per item. Fix it by batching (for example a DataLoader).
  • Caching is harder because it is all POST to one URL. Tools cache by query or by object id.
  • Protect against very deep or costly queries with depth and cost limits.

gRPC

Contract first (.proto)
service ProfileService {
  rpc GetProfile (ProfileRequest) returns (ProfileReply);          // unary
  rpc WatchPosts (ProfileRequest) returns (stream Post);           // server stream
  rpc UploadPhotos (stream Photo) returns (UploadSummary);         // client stream
  rpc Chat (stream Msg) returns (stream Msg);                      // two-way
}
  • Uses HTTP/2: many calls share one connection, with streaming built in.
  • Messages are Protobuf: small and fast, with strong types.
  • Code for client and server is generated from the .proto file in many languages.
  • Browsers cannot call gRPC directly. Use gRPC-Web or a gateway that turns it into REST.
  • Supports deadlines, cancelling, and four call shapes (unary, server stream, client stream, two-way).

Side by side

RESTGraphQLgRPC
ShapeResources + HTTP methodsOne endpoint + a queryMethods (RPC)
Data formatJSON (mostly)JSONProtobuf (binary)
TransportHTTP/1.1 or 2HTTP (usually POST)HTTP/2
ContractOpenAPI (optional)Schema (required).proto (required)
Over/under-fetchingCommonSolved by the client queryYou design each method
CachingEasy (HTTP, CDN)HarderCustom
StreamingNo (use SSE / WebSockets)SubscriptionsYes, built in
Browser supportPerfectPerfectNeeds gRPC-Web
Learning curveLowMediumMedium
Best forPublic APIs, simple CRUDVaried clients and screensInternal, fast, typed calls
VisualizerHow many calls does a screen need?Pick a screen, then flip between REST, GraphQL and gRPC to compare requests and wasted data.
The screen we need to draw

The screen needs: name, avatar, and for each of 3 posts: title

How does the app fetch it?
πŸ“±App
→↓#1
→↓#2
πŸ–₯️Servermany URLs, one per resource
GET /users/7
returns ALL user fields (email, address, settings...)
β‰ˆ 900 bytes back
GET /users/7/posts?limit=3
returns full posts with body text
β‰ˆ 2400 bytes back
Requests
2
Data sent back
β‰ˆ 3300 B
Data actually used
β‰ˆ 270 B
Wasted
92%
Data sent for this screen (smaller is better)
RESTβ‰ˆ 3300 B
GraphQLβ‰ˆ 290 B
gRPCβ‰ˆ 330 B

Numbers are rounded examples to show the idea. Real sizes depend on your data and on compression.

REST. The two calls do not depend on each other, so the app can send them together (1 round trip of waiting), but it is still 2 requests and extra data. Simple, cacheable with normal HTTP caching, works everywhere.

07How to Use It / Steps / Implementation

How to choose

  1. 1
    Who is the caller?
    Unknown outside developers β†’ REST (easiest to try and cache). Your own mobile and web apps β†’ REST or GraphQL. Your own services β†’ gRPC.
  2. 2
    Do screens need very different data?
    Yes, and you have many clients β†’ GraphQL helps. A few fixed screens β†’ REST is fine.
  3. 3
    Is speed and size critical?
    Many calls per second, low latency, or streaming β†’ gRPC.
  4. 4
    Do you need HTTP caching or a CDN?
    Yes β†’ REST is the best fit.
  5. 5
    Does a browser call it directly?
    REST or GraphQL. gRPC needs gRPC-Web or a gateway.
  6. 6
    Can you mix?
    Yes. Common pattern: gateway speaks REST or GraphQL outside and gRPC inside.

Good REST design checklist

  1. Plural nouns: /users, /users/7/orders.
  2. Use methods and status codes properly (201 for created, 404 for not found, 429 for too many requests).
  3. Paginate lists. Allow filtering and sorting with query parameters.
  4. Make PUT and DELETE idempotent, and accept an idempotency key on POST.
  5. Version the API. Return clear error bodies.
  6. Secure with HTTPS and authentication. Add rate limits.

08Key Terms to Know

TermMeaning in easy words
ResourceA β€œthing” in REST with its own URL, like a user or an order
CRUDCreate, Read, Update, Delete: the four basic actions on data
StatelessThe server keeps no memory of the client between requests
Over-fetchingGetting more data than the screen needs
Under-fetchingNeeding more than one call to get what the screen needs
Query / MutationGraphQL ways to read / change data
SchemaThe list of types and fields an API supports
ResolverThe GraphQL function that fetches the data for one field
N+1 problemOne query for a list plus one extra query per item: too many database calls
RPCRemote Procedure Call: calling a function on another machine as if it were local
ProtobufA compact binary format used by gRPC, defined in .proto files
HTTP/2A newer HTTP version that sends many requests on one connection and supports streams
OpenAPIA standard way to describe REST APIs in a file

09Pros, Cons and Trade-offs

StyleProsCons
RESTSimple, universal, easy to cache, easy to debug, huge toolingOver/under-fetching, many round trips, no built-in streaming
GraphQLOne request, exact data, strong schema, fast front-end work, good for aggregating many back-endsHarder caching, N+1 risk, costly queries need limits, more server work
gRPCFast, small, typed, streaming, code generation, deadlinesNot human readable, browsers need a gateway, harder to debug by hand, less suited to public APIs
When REST wins
  • Public API for anyone
  • CDN and HTTP caching matter
  • Simple CRUD, small team
  • Easy debugging with curl
When it loses
  • Many different screens need different data
  • Chatty mobile apps on slow networks
  • Heavy streaming or tiny latency needs
⚠️GraphQL is not β€œfaster” by default
It reduces round trips and wasted data for the client. But the server can do more work, and a bad query can be very costly. Add limits and batching.

10Common Problems and Mistakes

Common mistakes

  1. REST with verbs in URLs (/getUser, /deleteOrder) instead of nouns and methods.
  2. Returning 200 for errors in REST. Use real status codes.
  3. No pagination, so one call can return a million rows.
  4. GraphQL without limits. A deeply nested query can take the server down.
  5. GraphQL N+1. One query per item turns a fast query into hundreds of slow ones.
  6. Changing .proto field numbers. This breaks old clients.
  7. Choosing by trend. Pick for your callers and your team’s skills.
πŸ“‰Chatty clients
REST screens that need 8 calls feel slow on mobile.
πŸ’£Expensive queries
One GraphQL query can touch every table.
πŸ•΅οΈHard to debug
Binary gRPC messages need tools to inspect.
🧱Caching gaps
GraphQL over POST skips normal HTTP caches.

11Real-World Examples

🌍Most public APIs
Payment, maps, messaging and cloud providers expose REST APIs.
πŸ™GitHub
Offers both a REST API and a GraphQL API.
πŸ“˜Facebook / Meta
Created GraphQL to serve its mobile apps (open-sourced in 2015).
πŸ”Google
Created Protobuf and gRPC; used widely for internal services (general idea).
☸️Kubernetes ecosystem
Components such as etcd use gRPC.
🏒Large companies
Often mix: REST or GraphQL at the edge, gRPC inside.
Mini case: a shopping app
πŸ“±Mobile app
→↓GraphQL (one query per screen)
πŸšͺGateway
→↓gRPC
πŸ›οΈCatalog
πŸ›’Cart
πŸ’³Payments
Client-facing Service-to-service
Each link uses the style that fits it best.

12Related Topics to Read Next

What is an API?β†’

The basics behind all three styles.

API Styles→

The conversation patterns these tools can carry.

Data Formats→

JSON and Protobuf, the formats used here.

Idempotency→

Safe retries for REST and gRPC calls.

HTTP / HTTPS→

The base of REST and GraphQL, and HTTP/2 for gRPC.

Rate Limiting→

Protect any style of API from overload.

Authentication vs Authorization→

How to secure each style.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”REST: resources + HTTP methods + status codes. Stateless, cacheable, universal.
  • βœ”GraphQL: one endpoint, client picks fields. Fixes over/under-fetching. Watch N+1 and query cost.
  • βœ”gRPC: RPC + Protobuf + HTTP/2. Fast, typed, streaming. Best inside a company.
  • βœ”Public API? REST. Many client screens? GraphQL. Service to service? gRPC.
  • βœ”REST checklist: nouns, right methods and codes, pagination, versioning, idempotency, HTTPS and limits.
  • βœ”Mixing is normal: REST/GraphQL at the edge, gRPC inside.
  • βœ”One line: β€œREST for reach, GraphQL for flexibility, gRPC for speed.”
← Previous
Data Formats
Next β†’
Pagination, Filtering and Sorting