API Styles — REST, GraphQL, gRPC & Async APIs
When to choose REST, GraphQL, gRPC, plain RPC, webhooks or event-driven async APIs; GraphQL schemas, resolvers, N+1 and DataLoader, query cost limits and caching; gRPC/protobuf schema evolution; Backend-for-Frontend; and AsyncAPI/event contracts.
The landscape
| Style | Paradigm | Transport / format | Strengths | Weaknesses | Typical use |
|---|---|---|---|---|---|
| REST | resources | HTTP + JSON | simple, cacheable, ubiquitous | over/under-fetching, many round trips | public APIs, CRUD |
| GraphQL | typed graph queries | HTTP POST + JSON | exact data per screen, one round trip, schema | caching, cost control, complexity | multi-client frontends, aggregation |
| gRPC | RPC | HTTP/2 + Protobuf | fast, typed, streaming, codegen | browsers need proxies, less human-readable | internal microservices, mobile |
| JSON-RPC / tRPC | RPC | HTTP + JSON | simple; tRPC gives end-to-end TS types | not resource-oriented, weak caching | internal/full-stack TS apps |
| Webhooks | callbacks | HTTP POST | push to third parties | delivery reliability, security | integrations (payments, Git) |
| Event streams | async messages | Kafka/AMQP/MQTT | decoupling, fan-out, replay | eventual consistency, ops | inter-service events, analytics |
| SOAP | RPC + XML | HTTP/other + XML | WS-* standards | verbose, legacy | enterprise/banking legacy |
GraphQL
Schema and query
type Query {
post(id: ID!): Post
posts(first: Int = 20, after: String): PostConnection!
}
type Post {
id: ID!
title: String!
author: User!
comments(first: Int = 10): [Comment!]!
}
type User { id: ID!, name: String! }
type Comment { id: ID!, body: String!, author: User! }
type Mutation {
createPost(input: CreatePostInput!): Post!
}
# the client asks for exactly what the screen needs
query Feed {
posts(first: 10) {
edges { node { id title author { name } comments(first: 2) { body } } }
pageInfo { endCursor hasNextPage }
}
}
Resolvers and the N+1 problem
import DataLoader from "dataloader";
// one loader instance per request (so caching never leaks between users)
const userLoader = new DataLoader(async (ids: readonly string[]) => {
const rows = await db.query("SELECT * FROM users WHERE id = ANY($1)", [ids]);
const byId = new Map(rows.map((u) => [u.id, u]));
return ids.map((id) => byId.get(id) ?? null); // same order as requested
});
const resolvers = {
Post: { author: (post) => userLoader.load(post.authorId) },
};
Operating GraphQL safely
| Concern | Practice |
|---|---|
| Abuse / expensive queries | depth limits, cost analysis, pagination caps, timeouts |
| Caching | persisted queries via GET + CDN; normalised client caches (Apollo, Relay) |
| Authorization | per-field/per-type checks in resolvers or a policy layer — never only at the gateway |
| Errors | partial data + errors array; HTTP 200 for field errors (monitor them!) |
| Federation | compose subgraphs owned by different teams (Apollo Federation, GraphQL Mesh) |
| Subscriptions | real-time over WebSockets/SSE |
gRPC and Protobuf
syntax = "proto3";
package payments.v1;
service PaymentService {
rpc CreatePayment(CreatePaymentRequest) returns (Payment);
rpc StreamPaymentEvents(StreamRequest) returns (stream PaymentEvent);
}
message CreatePaymentRequest {
string idempotency_key = 1;
int64 amount_minor = 2;
string currency = 3;
reserved 4; // field removed — never reuse number 4
string customer_id = 5;
}
Schema evolution rules: never reuse field numbers, add fields rather than change them, treat enums as open, version the package for breaking changes, and run breaking-change checks in CI (buf breaking).
Choosing a style: decision guide
| Situation | Choose |
|---|---|
| Public API for third-party developers | REST (+ OpenAPI), webhooks for events |
| Many client apps with different data needs | GraphQL or a BFF per client |
| High-throughput internal calls, polyglot services | gRPC |
| Streaming between services | gRPC streams or a log (Kafka) |
| Fire-and-forget, fan-out, decoupled teams | events on a broker |
| Simple full-stack TypeScript app | tRPC / server actions |
| Browser real-time | SSE / WebSockets |
Backend-for-Frontend
Event-driven / async APIs
Document event contracts like any other API: event name, version, schema (JSON Schema, Avro, Protobuf with a schema registry), producer, ordering and delivery guarantees. AsyncAPI is the OpenAPI equivalent for message-driven APIs. See Queues & streams.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.