REST vs GraphQL vs gRPC vs tRPC: Choosing an API Style in 2026
Derar SattoufUpdated Backend & databases

Every backend project eventually faces the question: how will clients talk to this thing? The honest answer is rarely "pick the trendiest". REST, GraphQL, gRPC, and tRPC each solve a different problem well and impose a different tax. Choosing wrongly does not usually break a project; it quietly taxes it for years in the form of awkward caching, over-fetching, brittle clients, hard-to-debug performance, or a tooling gap that blocks a team.
REST (HTTP plus JSON, described by OpenAPI) is the default for public and partner APIs. It works with every client, every proxy, every CDN, every debugging tool, and every AI agent, so choose it unless you have a specific reason not to. GraphQL shines when many different clients need different shapes of a deeply connected graph (mobile, web, partners) and you can afford to invest in resolvers, DataLoader, query cost control, and a caching strategy that is not "the CDN does it".
gRPC (Protobuf over HTTP/2) is the best fit for internal service-to-service calls: strong contracts, small payloads, streaming, deadlines, and generated clients in every language. It is awkward directly from browsers without Connect or gRPC-Web. tRPC gives the fastest development experience when the client and server are both TypeScript in one repository (a Next.js app, a monorepo). It is not a public API format; it trades interoperability for end-to-end type inference with no codegen.
You can mix them: REST or GraphQL at the edge, gRPC inside, tRPC for the first-party web app. The boundary where an API is published to outsiders needs the most stable, most boring style. Whatever you choose, write a machine-readable contract, version by evolution rather than by big-bang, standardize errors, plan pagination, idempotency, and rate limits (see the companion post on API rate limiting, idempotency and pagination design), and publish an OpenAPI document or MCP server so agents can use it.
Library APIs change. The code here targets current stable lines as of November 2026 (tRPC v11, Apollo and GraphQL Yoga-style servers, @grpc/grpc-js, and buf). Treat the snippets as the right shape and confirm exact signatures against the version you install.
A decision framework
Start with who the consumers are, not with technology preferences.
Questions in priority order
- Who calls this API? Anonymous third parties, known partners, your own web and mobile apps, or other services you own?
- Can you control the client release cycle? If not (public API, old mobile apps), you need long-lived compatibility.
- Is the client TypeScript in the same repo? If yes, tRPC becomes very attractive for that surface.
- Is the data a graph that clients traverse in unpredictable ways? Many entity types, many relationships, many client shapes suggest GraphQL.
- Is it service-to-service with high call volume or streaming? gRPC.
- Does it need to be cacheable by a CDN? Plain GET-based REST is by far the easiest.
- Must browsers call it directly? REST and GraphQL work natively; gRPC needs a bridge; tRPC needs a TypeScript client.
- Do AI agents need to call it? An OpenAPI-described REST API or an MCP server is the common path.
Decision table
| Situation | Best fit | Why | Avoid |
|---|---|---|---|
| Public API for unknown developers | REST plus OpenAPI | Universal tooling, cacheable, easy to explore with curl | gRPC alone, tRPC |
| Partner integrations (B2B) | REST plus OpenAPI, webhooks | Stable, versionable, simple auth | Complex graph APIs they must learn |
| Web and mobile apps with many views over related data | GraphQL (or REST plus BFF) | Clients ask for exactly what they need; one round trip | GraphQL without cost limits and DataLoader |
| Next.js or monorepo full-stack TypeScript app | tRPC (or server actions) | No codegen, instant type safety, fast iteration | Exposing it publicly |
| Microservices, internal calls | gRPC | Contracts, performance, streaming, deadlines | REST without a schema if many languages exist |
| Real-time streams (telemetry, bidirectional) | gRPC streaming, WebSockets, or SSE | Native stream semantics | Polling REST at high frequency |
| Public data that is heavily cached and read-mostly | REST with HTTP caching | CDN friendly | GraphQL POST queries without persisted GET |
| Mixed audiences | REST at the edge, gRPC inside, GraphQL as BFF optional | Right tool per boundary | One style forced everywhere |
| Agents and LLM tool use | OpenAPI REST, plus an MCP server | Self-describing, typed inputs and outputs | Hand-written undocumented endpoints |
Scoring by dimension
| Dimension | REST | GraphQL | gRPC | tRPC |
|---|---|---|---|---|
| Interoperability | Excellent | Good | Good (needs bridge for browsers) | Poor (TypeScript clients) |
| Type safety | Via OpenAPI codegen | Via codegen from SDL | Built in via Protobuf | Built in via inference |
| Over-fetching control | Weak (sparse fieldsets help) | Excellent | Fixed messages (field masks help) | Per procedure |
| HTTP caching and CDN | Excellent | Hard (needs persisted GET) | Not applicable | Possible for queries over GET, unusual |
| Streaming | SSE or WebSockets alongside | Subscriptions, defer and stream | First class | Subscriptions (SSE or WebSocket) |
| Payload size and speed | JSON, fine | JSON, fine | Binary, small and fast | JSON, fine |
| Learning curve | Low | Medium to high | Medium | Low (if you know TypeScript) |
| Tooling maturity | Huge | Large | Large | Focused |
| Operational complexity | Low | Medium to high | Medium | Low |
| Browser support | Native | Native | Needs Connect or gRPC-Web | Native |
| Good for AI agents | Excellent | Fair | Fair (via gateway) | Poor |
The honest default
If you cannot decide, build a REST API described by an OpenAPI 3.1 document. Add GraphQL later as a BFF if client needs diverge, add gRPC between services when latency or contracts demand it, and use tRPC inside a TypeScript monorepo for the app you control end to end. Starting with the simplest, most interoperable style and adding layers when pain appears is cheaper than starting with the most sophisticated one.
The running example
To compare fairly, we implement one small feature in each style: a shop orders domain.
- Read an order by ID, including its line items and the customer.
- List orders for a customer with cursor pagination.
- Create an order (idempotently).
- Watch an order's status updates in real time.
Shared domain types and a fake data layer, used by every example:
// domain.ts
export type OrderStatus = "pending" | "paid" | "shipped" | "cancelled";
export interface Customer {
id: string;
name: string;
email: string;
}
export interface OrderItem {
sku: string;
quantity: number;
unitPriceCents: number;
}
export interface Order {
id: string;
customerId: string;
status: OrderStatus;
items: OrderItem[];
createdAt: string; // ISO 8601
}
export interface Page<T> {
items: T[];
nextCursor: string | null;
}
// A tiny repository interface so each API layer stays thin.
export interface Repo {
getOrder(id: string): Promise<Order | null>;
getOrdersByIds(ids: string[]): Promise<Order[]>;
listOrders(customerId: string, limit: number, cursor?: string): Promise<Page<Order>>;
getCustomersByIds(ids: string[]): Promise<Customer[]>;
createOrder(input: { customerId: string; items: OrderItem[]; idempotencyKey: string }): Promise<Order>;
}The point of the repository interface: the API style is a transport detail. Keep business logic in a service layer that knows nothing about HTTP, GraphQL, or Protobuf. Then swapping or adding styles is cheap, which is also the foundation for every migration path in the Migration paths section.
REST with OpenAPI
REST here means resource-oriented HTTP APIs with JSON. In practice most "REST" APIs are pragmatic HTTP APIs and rarely HATEOAS; that is fine, as long as you are consistent.
Design conventions
| Concern | Convention |
|---|---|
| Resources | Plural nouns: /orders, /orders/ord_123, /customers/cus_9/orders |
| Methods | GET read (safe, cacheable), POST create or action, PUT replace, PATCH partial update, DELETE remove |
| Status codes | 200 OK, 201 Created with Location, 204 No Content, 400 validation, 401 unauthenticated, 403 forbidden, 404 missing, 409 conflict, 422 semantic validation, 429 rate limited |
| Pagination | Cursor based: ?limit=25&cursor=..., response includes nextCursor |
| Filtering and fields | Query params: ?status=paid&fields=id,status |
| Errors | RFC 9457 Problem Details (application/problem+json) |
| Idempotency | Idempotency-Key header on POST |
| Versioning | Evolve compatibly; major version in the path or header only when breaking |
Server (Hono with Zod and OpenAPI)
This uses @hono/zod-openapi, which derives the OpenAPI document from the same Zod schemas that validate requests. Check the package docs for the current import paths in the version you install.
// rest/server.ts
import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
import { serve } from "@hono/node-server";
import type { Repo } from "../domain";
declare const repo: Repo;
const OrderItemSchema = z.object({
sku: z.string().openapi({ example: "SKU-1" }),
quantity: z.number().int().positive(),
unitPriceCents: z.number().int().nonnegative(),
});
const OrderSchema = z
.object({
id: z.string().openapi({ example: "ord_123" }),
customerId: z.string(),
status: z.enum(["pending", "paid", "shipped", "cancelled"]),
items: z.array(OrderItemSchema),
createdAt: z.string().datetime(),
})
.openapi("Order");
const ProblemSchema = z
.object({
type: z.string(),
title: z.string(),
status: z.number(),
detail: z.string().optional(),
})
.openapi("Problem");
const app = new OpenAPIHono();
const getOrder = createRoute({
method: "get",
path: "/orders/{id}",
request: { params: z.object({ id: z.string() }) },
responses: {
200: { content: { "application/json": { schema: OrderSchema } }, description: "The order" },
404: { content: { "application/problem+json": { schema: ProblemSchema } }, description: "Not found" },
},
});
app.openapi(getOrder, async (c) => {
const { id } = c.req.valid("param");
const order = await repo.getOrder(id);
if (!order) {
return c.json(
{ type: "https://api.example.com/problems/not-found", title: "Order not found", status: 404 },
404,
{ "Content-Type": "application/problem+json" },
);
}
c.header("Cache-Control", "private, max-age=0, must-revalidate");
c.header("ETag", `"${order.status}-${order.items.length}"`); // illustrative; use a real version or hash
return c.json(order, 200);
});
const createOrder = createRoute({
method: "post",
path: "/orders",
request: {
headers: z.object({ "idempotency-key": z.string().min(8) }),
body: {
content: {
"application/json": {
schema: z.object({ customerId: z.string(), items: z.array(OrderItemSchema).min(1) }),
},
},
},
},
responses: { 201: { content: { "application/json": { schema: OrderSchema } }, description: "Created" } },
});
app.openapi(createOrder, async (c) => {
const body = c.req.valid("json");
const key = c.req.valid("header")["idempotency-key"];
const order = await repo.createOrder({ ...body, idempotencyKey: key });
return c.json(order, 201, { Location: `/orders/${order.id}` });
});
// The OpenAPI document is generated, not hand-maintained.
app.doc31("/openapi.json", {
openapi: "3.1.0",
info: { title: "Orders API", version: "1.0.0" },
});
serve({ fetch: app.fetch, port: 3000 });Client (generated types, typed fetch)
Generate types from the document and use a thin typed client. openapi-typescript and openapi-fetch are a popular pair; confirm current usage in their docs.
npx openapi-typescript http://localhost:3000/openapi.json -o src/api-types.ts// rest/client.ts
import createClient from "openapi-fetch";
import type { paths } from "./api-types";
const api = createClient<paths>({ baseUrl: "https://api.example.com" });
const { data, error } = await api.GET("/orders/{id}", {
params: { path: { id: "ord_123" } },
});
if (error) throw new Error(error.title);
console.log(data.status); // fully typed from the OpenAPI documentREST strengths and costs
| Strengths | Costs |
|---|---|
| Works everywhere: curl, browsers, every language | Over-fetching and under-fetching create chatty clients or bloated responses |
| HTTP caching, CDNs, ETags, conditional requests are free | No built-in typed contract unless you add OpenAPI discipline |
| Simple mental model and debugging | Versioning and evolution need conscious rules |
| Huge tooling ecosystem (gateways, mocks, SDK generators, linters) | Many endpoints for many views; BFF layers appear |
| Great fit for AI agents via OpenAPI | Real-time needs a second mechanism (SSE, WebSockets, webhooks) |
Pragmatic REST extras
- Sparse fieldsets and expansion:
GET /orders/ord_123?expand=customerlets clients opt into related data without a graph language. Keep expansion depth limited. - Compound endpoints: it is acceptable to offer
GET /orders/ord_123/summarythat returns exactly what a screen needs. That is a BFF in miniature. - Bulk and batch:
POST /orders:batchGetfor fetching many by ID avoids N requests. - Long-running operations: return
202 Acceptedwith a status URL rather than holding the connection. - Webhooks for server-initiated events, signed with HMAC and retried with backoff.
GraphQL
GraphQL gives clients a single endpoint and a typed schema; the client chooses the fields. The server resolves the requested fields through resolver functions.
Schema (SDL)
# schema.graphql
scalar DateTime
enum OrderStatus {
PENDING
PAID
SHIPPED
CANCELLED
}
type Customer {
id: ID!
name: String!
email: String!
}
type OrderItem {
sku: String!
quantity: Int!
unitPriceCents: Int!
}
type Order {
id: ID!
status: OrderStatus!
items: [OrderItem!]!
createdAt: DateTime!
customer: Customer!
}
type OrderEdge {
cursor: String!
node: Order!
}
type OrderConnection {
edges: [OrderEdge!]!
pageInfo: PageInfo!
}
type PageInfo {
hasNextPage: Boolean!
endCursor: String
}
input OrderItemInput {
sku: String!
quantity: Int!
unitPriceCents: Int!
}
input CreateOrderInput {
customerId: ID!
items: [OrderItemInput!]!
idempotencyKey: String!
}
type CreateOrderPayload {
order: Order
errors: [UserError!]!
}
type UserError {
field: String
message: String!
code: String!
}
type Query {
order(id: ID!): Order
orders(customerId: ID!, first: Int = 25, after: String): OrderConnection!
}
type Mutation {
createOrder(input: CreateOrderInput!): CreateOrderPayload!
}
type Subscription {
orderStatusChanged(orderId: ID!): Order!
}Note the design choices: mutations take a single input object and return a payload type with a typed errors list for expected failures (validation, business rules), reserving the top-level errors array for unexpected failures. Pagination follows the connection pattern, which clients like Relay and Apollo understand.
Server with DataLoader (GraphQL Yoga)
// graphql/server.ts
import { createServer } from "node:http";
import { createYoga, createSchema } from "graphql-yoga";
import DataLoader from "dataloader";
import { readFileSync } from "node:fs";
import type { Repo, Customer } from "../domain";
declare const repo: Repo;
// Loaders are created PER REQUEST so caching never leaks across users.
function createLoaders() {
return {
customer: new DataLoader<string, Customer | undefined>(async (ids) => {
const rows = await repo.getCustomersByIds([...ids]);
const byId = new Map(rows.map((c) => [c.id, c]));
return ids.map((id) => byId.get(id)); // MUST return in the same order as ids
}),
};
}
const schema = createSchema({
typeDefs: readFileSync("./schema.graphql", "utf8"),
resolvers: {
Query: {
order: (_root, { id }, ctx) => ctx.repo.getOrder(id),
orders: async (_root, { customerId, first, after }, ctx) => {
const page = await ctx.repo.listOrders(customerId, Math.min(first, 100), after ?? undefined);
return {
edges: page.items.map((o) => ({ cursor: o.id, node: o })),
pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
};
},
},
Order: {
// Without DataLoader this runs once per order: the N+1 problem.
customer: (order, _args, ctx) => ctx.loaders.customer.load(order.customerId),
status: (order) => order.status.toUpperCase(),
},
Mutation: {
createOrder: async (_root, { input }, ctx) => {
if (!ctx.user) throw new Error("UNAUTHENTICATED");
const order = await ctx.repo.createOrder(input);
return { order, errors: [] };
},
},
},
});
const yoga = createYoga({
schema,
context: async ({ request }) => ({
repo,
user: await authenticate(request),
loaders: createLoaders(),
}),
maskedErrors: true, // do not leak internals to clients
});
createServer(yoga).listen(4000);
declare function authenticate(req: Request): Promise<{ id: string } | null>;Client (typed with GraphQL Code Generator)
# queries/OrderWithCustomer.graphql
query OrderWithCustomer($id: ID!) {
order(id: $id) {
id
status
items {
sku
quantity
}
customer {
name
}
}
}// graphql/client.ts
import { request } from "graphql-request";
import { OrderWithCustomerDocument } from "./generated/graphql"; // produced by graphql-codegen
const data = await request("https://api.example.com/graphql", OrderWithCustomerDocument, { id: "ord_123" });
console.log(data.order?.customer.name); // typed to exactly the selected fieldsThe N+1 problem and DataLoader
A query for 50 orders and each order's customer triggers 1 query for orders plus 50 queries for customers if the customer resolver fetches one at a time. DataLoader batches all load(id) calls within the same tick into one getCustomersByIds call and caches within the request. The rules:
- Create loaders per request, never globally.
- The batch function must return results in the same order and length as the keys, with
undefinedor an Error for missing ones. - Batch at the data access layer where the batching actually reduces round trips (a
WHERE id IN (...)query), not merely at the resolver. - Verify with logging or tracing that the number of database queries per request is bounded and does not scale with result size.
The same problem exists in REST when a handler loops over rows and fetches related rows individually; GraphQL just makes it easier to trigger from the client, because the client controls the shape.
Protecting a GraphQL server
Because clients write queries, you must defend against expensive ones.
| Risk | Defense |
|---|---|
| Deeply nested queries | Depth limit (for example 8 to 10) |
| Wide, expensive queries | Query complexity or cost analysis with per-field costs |
| Query batching and aliasing abuse | Limit aliases and batch size; rate limit by cost, not just by request count |
| Introspection leaks | Disable or restrict introspection in production for private APIs |
| Arbitrary queries from the internet | Persisted queries (allow-list by hash) for first-party clients |
| Field-level authorization gaps | Authorize in the resolver or data layer, never only at the top level |
| Error leaks | Mask internal errors; return typed domain errors in payloads |
Persisted queries deserve emphasis: the client sends a hash (and optionally GET, which makes CDN caching possible) instead of the query text, and the server only runs registered operations. This one technique fixes most security and caching complaints about GraphQL for first-party clients.
GraphQL strengths and costs
| Strengths | Costs |
|---|---|
| Clients fetch exactly what they need in one round trip | Caching is harder; POST requests bypass CDNs |
| Strongly typed schema; excellent client tooling | N+1, cost control, and authorization at field level require discipline |
| Evolves by adding fields and deprecating, no versions needed | Errors are 200 responses by default; monitoring needs GraphQL-aware tools |
| Great for many clients and many shapes | File uploads and streaming are non-standard or extension based |
| Federation can compose multiple teams' schemas | Federation and gateways add real operational complexity |
gRPC
gRPC uses Protocol Buffers for the contract and HTTP/2 for transport. You define services and messages in .proto files, generate client and server code, and get compact binary payloads, multiplexed streams, deadlines, and cancellation.
The contract
// proto/shop/orders/v1/orders.proto
syntax = "proto3";
package shop.orders.v1;
import "google/protobuf/timestamp.proto";
enum OrderStatus {
ORDER_STATUS_UNSPECIFIED = 0;
ORDER_STATUS_PENDING = 1;
ORDER_STATUS_PAID = 2;
ORDER_STATUS_SHIPPED = 3;
ORDER_STATUS_CANCELLED = 4;
}
message OrderItem {
string sku = 1;
int32 quantity = 2;
int64 unit_price_cents = 3;
}
message Order {
string id = 1;
string customer_id = 2;
OrderStatus status = 3;
repeated OrderItem items = 4;
google.protobuf.Timestamp created_at = 5;
}
message GetOrderRequest {
string id = 1;
}
message ListOrdersRequest {
string customer_id = 1;
int32 page_size = 2;
string page_token = 3;
}
message ListOrdersResponse {
repeated Order orders = 1;
string next_page_token = 2;
}
message CreateOrderRequest {
string customer_id = 1;
repeated OrderItem items = 2;
string idempotency_key = 3;
}
message WatchOrderRequest {
string order_id = 1;
}
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order);
rpc ListOrders(ListOrdersRequest) returns (ListOrdersResponse);
rpc CreateOrder(CreateOrderRequest) returns (Order);
rpc WatchOrder(WatchOrderRequest) returns (stream Order); // server streaming
}Conventions worth following: a zero value UNSPECIFIED for every enum, request and response messages per RPC (never reuse the entity as the request), version in the package name (v1), field numbers are forever, and never reuse a removed field number (use reserved).
Schema tooling with buf
buf replaces ad hoc protoc invocations with linting, breaking-change detection, and managed code generation.
# buf.yaml
version: v2
modules:
- path: proto
lint:
use:
- STANDARD
breaking:
use:
- FILE# buf.gen.yaml
version: v2
plugins:
- remote: buf.build/bufbuild/es
out: gen
opt: target=ts
- remote: buf.build/connectrpc/es
out: gen
opt: target=tsbuf lint
buf breaking --against '.git#branch=main' # fails CI on wire-incompatible changes
buf generatePlugin names and options change between releases; check the buf and Connect documentation for the current plugin references (the Connect and protobuf-es libraries have both had major version transitions). The CI check buf breaking is the single most valuable habit: it makes incompatible changes impossible to merge by accident.
Server and client in TypeScript with Connect
Connect RPC (from the Buf team) is a family of libraries that implement gRPC, gRPC-Web, and a simple HTTP-friendly Connect protocol from the same service definition, which solves the browser problem. An equivalent using @grpc/grpc-js works for pure gRPC between services.
// grpc/server.ts (Connect, Node)
import { fastify } from "fastify";
import { fastifyConnectPlugin } from "@connectrpc/connect-fastify";
import { Code, ConnectError } from "@connectrpc/connect";
import type { ConnectRouter } from "@connectrpc/connect";
import { OrderService } from "../gen/shop/orders/v1/orders_pb";
const routes = (router: ConnectRouter) =>
router.service(OrderService, {
async getOrder(req) {
const order = await repo.getOrder(req.id);
if (!order) throw new ConnectError("order not found", Code.NotFound);
return toProto(order);
},
async createOrder(req, ctx) {
if (ctx.signal.aborted) throw new ConnectError("cancelled", Code.Canceled);
const order = await repo.createOrder({
customerId: req.customerId,
items: req.items.map((i) => ({ sku: i.sku, quantity: i.quantity, unitPriceCents: Number(i.unitPriceCents) })),
idempotencyKey: req.idempotencyKey,
});
return toProto(order);
},
async *watchOrder(req, ctx) {
// Server streaming: an async generator yields messages until the client cancels.
for await (const order of orderChanges(req.orderId, ctx.signal)) {
yield toProto(order);
}
},
});
const server = fastify({ http2: true });
await server.register(fastifyConnectPlugin, { routes });
await server.listen({ host: "0.0.0.0", port: 8080 });
declare const repo: import("../domain").Repo;
declare function toProto(o: import("../domain").Order): any;
declare function orderChanges(id: string, signal: AbortSignal): AsyncIterable<import("../domain").Order>;// grpc/client.ts
import { createClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { OrderService } from "../gen/shop/orders/v1/orders_pb";
const transport = createGrpcTransport({ baseUrl: "http://orders:8080" });
const orders = createClient(OrderService, transport);
// Deadlines are mandatory in practice: every call must have one.
const order = await orders.getOrder({ id: "ord_123" }, { timeoutMs: 800 });
for await (const update of orders.watchOrder({ orderId: "ord_123" })) {
console.log("status", update.status);
}The Connect API surface has changed across major versions (createPromiseClient became createClient, message construction changed with protobuf-es v2). Verify exact imports for your versions.
gRPC rules that prevent incidents
- Always set a deadline on every client call, and propagate the remaining deadline to downstream calls. Without deadlines, a slow dependency consumes all your threads.
- Retries belong in a service config with a retry policy and only for idempotent methods; use
UNAVAILABLEand similar transient codes. Never retry non-idempotent writes without an idempotency key. - Load balancing is a client concern. HTTP/2 multiplexes many requests on one long-lived connection, so a Layer 4 load balancer pins all traffic from a client to one backend. Use a Layer 7 proxy that understands gRPC (Envoy and others), client-side load balancing, or a service mesh. In Kubernetes, a plain ClusterIP Service gives you uneven load across pods.
- Use the right status codes:
NOT_FOUND,INVALID_ARGUMENT,ALREADY_EXISTS,FAILED_PRECONDITION,UNAUTHENTICATED,PERMISSION_DENIED,DEADLINE_EXCEEDED,UNAVAILABLE,RESOURCE_EXHAUSTED. Attach structured details (google.rpc.Statusdetails such asBadRequest) for field errors. - Message size limits default to 4 MB on many implementations; stream large payloads instead of raising limits.
- Health checking and reflection: implement the standard gRPC health service (Kubernetes can probe it natively) and enable reflection in non-production for tools such as
grpcurl.
grpcurl -plaintext -d '{"id":"ord_123"}' localhost:8080 shop.orders.v1.OrderService/GetOrdergRPC strengths and costs
| Strengths | Costs |
|---|---|
| Strict contracts, generated clients in many languages | Browsers need Connect or gRPC-Web, plus a proxy for the latter |
| Compact binary format, fast serialization | Binary payloads are not human-readable without tools |
| First-class streaming and deadlines | HTTP caching and CDNs do not apply |
| Backward compatibility rules are well defined | Load balancing and observability need L7 awareness |
| Great for polyglot internal systems | Harder for third parties to adopt than a curl-able REST API |
tRPC
tRPC lets you call server functions from a TypeScript client with full type inference and no schema language or code generation. The server router's TypeScript type is imported into the client. That is the entire trick.
Server
// trpc/server.ts
import { initTRPC, TRPCError } from "@trpc/server";
import { createHTTPServer } from "@trpc/server/adapters/standalone";
import { z } from "zod";
import type { Repo } from "../domain";
declare const repo: Repo;
type Context = { userId: string | null };
const t = initTRPC.context<Context>().create();
// Reusable middleware: require authentication
const authed = t.procedure.use(({ ctx, next }) => {
if (!ctx.userId) throw new TRPCError({ code: "UNAUTHORIZED" });
return next({ ctx: { userId: ctx.userId } });
});
export const appRouter = t.router({
order: t.router({
byId: authed.input(z.object({ id: z.string() })).query(async ({ input }) => {
const order = await repo.getOrder(input.id);
if (!order) throw new TRPCError({ code: "NOT_FOUND", message: "Order not found" });
return order;
}),
list: authed
.input(z.object({ customerId: z.string(), limit: z.number().int().min(1).max(100).default(25), cursor: z.string().optional() }))
.query(({ input }) => repo.listOrders(input.customerId, input.limit, input.cursor)),
create: authed
.input(
z.object({
customerId: z.string(),
idempotencyKey: z.string().min(8),
items: z.array(z.object({ sku: z.string(), quantity: z.number().int().positive(), unitPriceCents: z.number().int().nonnegative() })).min(1),
}),
)
.mutation(({ input }) => repo.createOrder(input)),
// Subscriptions can be async generators; the v11 HTTP transport streams them over SSE.
watch: authed.input(z.object({ orderId: z.string() })).subscription(async function* ({ input, signal }) {
for await (const order of orderChanges(input.orderId, signal)) {
yield order;
}
}),
}),
});
// The ONLY thing the client imports from the server:
export type AppRouter = typeof appRouter;
createHTTPServer({
router: appRouter,
createContext: ({ req }) => ({ userId: parseUserId(req.headers.authorization) }),
}).listen(3001);
declare function orderChanges(id: string, signal: AbortSignal | undefined): AsyncIterable<import("../domain").Order>;
declare function parseUserId(header: string | undefined): string | null;Client
// trpc/client.ts
import { createTRPCClient, httpBatchLink, httpSubscriptionLink, splitLink } from "@trpc/client";
import type { AppRouter } from "../server/trpc/server"; // type-only import: no server code ships to the client
export const trpc = createTRPCClient<AppRouter>({
links: [
splitLink({
condition: (op) => op.type === "subscription",
true: httpSubscriptionLink({ url: "http://localhost:3001" }),
false: httpBatchLink({
url: "http://localhost:3001",
headers: () => ({ authorization: `Bearer ${getToken()}` }),
}),
}),
],
});
const order = await trpc.order.byId.query({ id: "ord_123" });
// ^? Order, inferred from the server's return type
await trpc.order.create.mutate({
customerId: "cus_9",
idempotencyKey: crypto.randomUUID(),
items: [{ sku: "SKU-1", quantity: 2, unitPriceCents: 1999 }],
});
declare function getToken(): string;Refactoring a field name on the server produces compile errors in every client call site immediately. That feedback loop is why teams who adopt tRPC rarely go back inside a monorepo.
The tRPC client API was renamed across major versions (v10 to v11), and transport links for subscriptions have changed (WebSocket link and the newer SSE-based link). Verify against the current tRPC docs.
tRPC strengths and costs
| Strengths | Costs |
|---|---|
| End-to-end types with no codegen | TypeScript on both ends, ideally one repo |
| Excellent developer experience and refactor safety | Not a public interoperable protocol; no standard schema for other languages (though OpenAPI generation add-ons exist) |
| Easy to adopt incrementally in Next.js and Node apps | Type inference can slow the compiler in very large routers |
| Batching reduces round trips | Weak fit for third-party, mobile native, or polyglot consumers |
| Works with Zod (or other validators) for runtime checks | The type contract only exists at compile time; version skew between deployed client and server is your problem |
Version skew is the underrated tRPC risk. With a web app, you deploy client and server together, so it is fine. With a mobile app on user devices that call the same router, an old client can call a procedure whose input changed. Keep procedure inputs additive, or version the router, if clients cannot be force-updated.
Alternatives in the same slot
If the goal is "typed server functions for my own frontend", also consider framework-native options: Next.js Server Actions and route handlers, Remix and React Router loaders and actions, and Hono's RPC client. They solve the same problem with less ceremony for simple cases. tRPC wins when you want a procedure-oriented API with middleware, batching, and a framework-independent client.
Contracts and schema tooling
An API without a machine-readable contract is a rumor. Each style has its canonical contract.
| Style | Contract format | Source of truth | Key tools |
|---|---|---|---|
| REST | OpenAPI 3.1 (a 3.2 revision also exists; verify tooling support) | Code-first (generated from Zod, annotations) or design-first (YAML) | Spectral (linting), Redocly or Scalar (docs), openapi-typescript, Prism (mock), oasdiff (breaking changes), Schemathesis (property testing) |
| GraphQL | SDL | Schema-first or code-first (Pothos, Nexus) | GraphQL Code Generator, GraphQL Inspector (breaking changes), Apollo or other registries |
| gRPC | Protobuf .proto | Schema-first | buf (lint, breaking, generate), Buf Schema Registry, grpcurl |
| tRPC | TypeScript types | Code is the contract | tsc, optional trpc-openapi style generators |
Design-first or code-first?
- Design-first (write the contract, then implement): best for public APIs and when multiple teams agree on an interface before building. Review contract diffs in pull requests.
- Code-first (generate the contract from code): best for small teams, because the contract cannot drift from the implementation. Commit the generated artifact and diff it in CI.
Either way, the rule is the same: the contract is a reviewed, versioned file, and CI fails on unintended breaking changes.
A contract CI pipeline
# .github/workflows/api-contract.yml
name: api-contract
on: [pull_request]
jobs:
contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- name: Lint OpenAPI
run: npx @stoplight/spectral-cli lint openapi.json
- name: Breaking-change check (OpenAPI)
run: |
git show origin/main:openapi.json > /tmp/base.json
oasdiff breaking /tmp/base.json openapi.json --fail-on ERR
- name: Lint and breaking check (Protobuf)
uses: bufbuild/buf-action@v1
with:
breaking_against: "https://github.com/${{ github.repository }}.git#branch=main"Verify the action inputs and tool flags against the current documentation; they evolve.
Versioning and evolution
The cheapest version strategy is never needing a new version. Design for compatible evolution first.
Compatible changes by style
| Change | REST/JSON | GraphQL | Protobuf | tRPC |
|---|---|---|---|---|
| Add an optional field or output field | Safe | Safe | Safe | Safe |
| Add a required input field | Breaking | Breaking | Breaking at the app level | Breaking |
| Remove or rename a field | Breaking | Breaking (deprecate first) | Breaking (reserve the number, deprecate first) | Breaking, caught at compile time within a repo |
| Change a field's type | Breaking | Breaking | Mostly breaking (some numeric widenings are compatible on the wire) | Breaking |
| Add an enum value | Often breaking for strict clients | Risky; clients must handle unknown values | Safe if clients treat unknown enums correctly | Risky |
| Add a new endpoint or procedure | Safe | Safe | Safe | Safe |
Strategy by style
- REST: treat additive changes as non-breaking, and tell clients in the documentation to ignore unknown fields (the "tolerant reader" rule). For breaking changes, introduce
/v2/ordersor a version header, run both, and set a sunset date communicated with theSunsetandDeprecationheaders. - GraphQL: mark fields
@deprecated(reason: "Use X"), monitor usage by field with your schema registry or tracing, remove only when usage is zero. - gRPC: package versioning (
shop.orders.v1), never reuse field numbers, usereserved, runbuf breakingin CI, and publishv2as a separate package when truly needed. - tRPC: within a deployed-together app, evolve freely. For externally deployed clients, add new procedures rather than changing old ones.
Deprecation workflow
- Mark deprecated in the contract and docs.
- Emit warnings (
Deprecationheader, GraphQL deprecation, log line with client ID). - Measure who still calls it.
- Contact remaining consumers.
- Remove after the announced date, not before.
The tolerant reader pattern
Clients should ignore fields they do not recognize and handle unknown enum values with a default branch. Servers should accept slightly varying input where harmless, but validate strictly for correctness and security. This mutual tolerance is what makes additive evolution work.
Caching and CDNs
Caching is where REST's boring design pays off most.
| Style | Caching story |
|---|---|
| REST | Cache-Control, ETag, Last-Modified, Vary, conditional GETs, CDN caching of GETs. Works with zero special tooling |
| GraphQL | POST bodies are not cached by default. Options: persisted queries over GET for public data, response caching keyed by query hash and variables at the server or gateway, normalized client caches (Apollo Client, urql, Relay), CDN features that support GraphQL |
| gRPC | Not HTTP-cacheable. Cache at the application layer (Redis, in-process) or via a gateway for gRPC-Web or Connect GET-enabled idempotent methods (Connect supports GET for side-effect-free methods; verify your version) |
| tRPC | Queries can be made GET-cacheable by configuring the batch link and response headers per route; most apps rely on client caching (TanStack Query) |
REST caching recipe
# Edge or reverse proxy: let the CDN cache public GETs briefly
location /v1/products/ {
proxy_pass http://api;
proxy_cache api_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 30s;
proxy_cache_use_stale error timeout updating;
add_header X-Cache-Status $upstream_cache_status;
}# Response headers for a cacheable public resource
Cache-Control: public, max-age=60, stale-while-revalidate=300
ETag: "v42"
Vary: Accept-Encoding
# For per-user data, never share
Cache-Control: private, no-storeConditional requests save bandwidth and compute: the client sends If-None-Match: "v42", the server replies 304 Not Modified with no body. Make ETags cheap to compute (a version column or hash of the updated-at timestamp), or you lose the benefit.
GraphQL caching recipe
- Use persisted queries; send them via GET with the hash and variables in the URL for public, cacheable data.
- Cache at the resolver or data layer with explicit keys and TTLs for hot lookups.
- Rely on a normalized client cache for UI responsiveness.
- Do not cache authenticated responses at a shared layer unless the key includes the identity.
Cache invalidation basics
Prefer short TTLs plus stale-while-revalidate over clever invalidation. For data that must be fresh, use event-driven purges (surrogate keys or tags at your CDN) triggered by writes. Never cache responses that depend on Authorization in a shared cache without Vary or private.
Authentication, authorization and errors
Authentication
| Style | Typical mechanism | Notes |
|---|---|---|
| REST | Authorization: Bearer <JWT or opaque token>, OAuth 2.0 and OIDC, API keys for server-to-server, mTLS for high trust | Works at the gateway and per route |
| GraphQL | Same header; resolve identity into the context object | Authenticate once per request; authorize per field or object |
| gRPC | Metadata (authorization), TLS and mTLS between services | Use interceptors; service identity via mTLS or workload identity |
| tRPC | Header or cookie into createContext, middleware for authorization | Cookies need CSRF consideration for mutations |
Principles that hold everywhere:
- Authenticate at the edge, authorize at the resource. A valid token proves identity, not permission. Every handler or resolver must check that this user may touch this object (guard against IDOR, where changing an ID in the URL reads someone else's data).
- Use short-lived access tokens and refresh tokens; verify signature, issuer, audience, and expiry on every request.
- For browsers, prefer HttpOnly, Secure, SameSite cookies for first-party apps (and CSRF protection), or the BFF pattern, over storing tokens in localStorage.
- For GraphQL, authorization lives below the schema in a shared policy layer so that every path to an object (through any field) is protected.
- Never log tokens, and scrub
Authorizationheaders from traces.
Error models
| Style | How errors look | Best practice |
|---|---|---|
| REST | HTTP status plus Problem Details JSON | One error shape across the API, stable machine-readable type/code, human detail, a traceId |
| GraphQL | errors array with extensions.code, partial data possible; HTTP 200 mostly | Domain failures as typed payload errors; reserve errors for unexpected failures; mask internals |
| gRPC | Status code plus message plus typed details | Pick the canonical code; attach google.rpc.Status details for field violations |
| tRPC | TRPCError with codes mapped to HTTP statuses | Map domain errors to codes; return Zod issues for input errors |
Example Problem Details response:
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"detail": "SKU-1 has 1 unit available; 3 requested.",
"instance": "/orders",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"errors": [{ "pointer": "/items/0/quantity", "message": "exceeds available stock" }]
}Whatever the style, return actionable errors: what failed, which field, whether retrying is useful (Retry-After for 429 and 503), and a trace ID for support. Rate limiting, idempotency keys, and pagination are covered in depth in API rate limiting, idempotency and pagination design; apply those rules uniformly across whichever style you pick.
Streaming, real-time and file uploads
Real-time options
| Need | REST world | GraphQL | gRPC | tRPC |
|---|---|---|---|---|
| Server pushes updates | Server-Sent Events (SSE) or WebSockets | Subscriptions (WebSocket or SSE transport); @defer/@stream for incremental delivery (verify server support) | Server streaming | Subscriptions (SSE link or WebSocket link) |
| Client streams data | WebSockets, chunked upload | Not standard | Client streaming | Not typical |
| Bidirectional | WebSockets | Subscriptions plus mutations | Bidirectional streaming | WebSockets |
| Occasional notifications | Webhooks | Webhooks | Server streaming | SSE |
Guidance: SSE is underrated. It is plain HTTP, works through most proxies, reconnects automatically with Last-Event-ID, and is enough for most "live update" needs. Use WebSockets when you need bidirectional low-latency messaging. For service-to-service streams, gRPC is the natural choice.
A minimal SSE endpoint:
// rest/sse.ts
app.get("/orders/:id/events", (c) => {
const id = c.req.param("id");
return streamSSE(c, async (stream) => {
for await (const order of orderChanges(id, c.req.raw.signal)) {
await stream.writeSSE({ event: "status", id: String(Date.now()), data: JSON.stringify({ status: order.status }) });
}
});
});
declare const app: import("hono").Hono;
declare function streamSSE(...args: any[]): Response;
declare function orderChanges(id: string, signal: AbortSignal): AsyncIterable<{ status: string }>;Production concerns for any streaming design: heartbeats to keep idle connections alive through proxies, bounded buffers and backpressure for slow consumers, authentication on connect (and re-validation for long sessions), resumption (event IDs), and per-user connection limits. If events originate from a message broker, see the companion post on message brokers for delivery semantics.
File uploads
| Style | Recommended approach |
|---|---|
| REST | multipart/form-data for small files; for large files, return a pre-signed URL to object storage and have the client upload directly, then call your API with the object key. Resumable protocols (tus) for flaky networks |
| GraphQL | Avoid the multipart request spec extension for large files; use the same pre-signed URL flow, exposing a mutation that returns the URL |
| gRPC | Client streaming of chunks with a metadata message first; or pre-signed URLs |
| tRPC | Pre-signed URLs; tRPC supports FormData and file inputs in recent versions, but large files still belong on object storage |
Pre-signed uploads keep large bodies off your API servers, avoid timeouts and memory spikes, and let the storage layer handle scale. Validate the content type and size on the storage side (policy conditions) and scan after upload.
Performance and serialization
Performance claims about API styles are usually exaggerated in both directions. Reason about the actual bottlenecks.
| Factor | Effect |
|---|---|
| Serialization format | Protobuf is typically smaller and faster to encode and decode than JSON; for most web APIs, the difference is dwarfed by database and network latency. It matters for high-frequency internal calls and mobile networks |
| Round trips | The largest practical factor for clients. GraphQL and BFF endpoints reduce them. HTTP/2 and HTTP/3 multiplexing reduce the cost of many small REST calls |
| Payload size | Compression (gzip, brotli, zstd where supported) closes much of the JSON versus Protobuf gap for text-heavy payloads |
| Connection reuse | gRPC keeps long-lived HTTP/2 connections; REST clients should use keep-alive and connection pooling too |
| Database access | N+1 patterns, missing indexes, and chatty ORMs dominate real latency in every style |
| Server-side validation and auth | Usually small but measure; JWT verification and schema validation can add up at high throughput |
| Cold starts | In serverless, runtime and framework size matter more than the protocol |
How to measure instead of guess
- Define your SLOs (for example p95 under 300 ms for the order page).
- Trace one representative request across layers (OpenTelemetry) and find where time goes.
- Load test with realistic payloads (k6, Gatling, or
ghzfor gRPC). - Change one variable at a time: compression, batching, connection reuse, caching, query shape.
- Only then consider swapping the protocol.
# k6 smoke test for a REST endpoint
cat > orders.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
export const options = { vus: 50, duration: "60s", thresholds: { http_req_duration: ["p(95)<300"] } };
export default function () {
const res = http.get("https://api.example.com/orders/ord_123");
check(res, { ok: (r) => r.status === 200 });
}
EOF
k6 run orders.js
# gRPC load with ghz
ghz --insecure --proto proto/shop/orders/v1/orders.proto \
--call shop.orders.v1.OrderService.GetOrder -d '{"id":"ord_123"}' \
-c 50 -z 60s localhost:8080A rule of thumb that survives scrutiny: if your API latency is dominated by the database, changing from JSON to Protobuf will not rescue you. If you have tens of thousands of internal calls per second between services, it will.
Gateways, BFFs, testing and agents
API gateways
A gateway (Kong, Envoy-based gateways, cloud API gateways, Apigee, Tyk, or a Gateway API implementation in Kubernetes) centralizes authentication, rate limiting, TLS, routing, request logging, and sometimes transformation. Gateways are natural for REST and gRPC; for GraphQL, a federation router (Apollo Router, GraphQL Mesh, WunderGraph-style tools) plays the role.
Keep business logic out of the gateway. It is infrastructure: policy and routing, not domain rules.
Backend for Frontend (BFF)
A BFF is a server owned by a specific client (web, iOS, Android) that aggregates calls to internal services and shapes responses for that client. It gives you the benefits people want from GraphQL (fewer round trips, tailored payloads) with whichever protocol you like, and it is a clean place for session handling (keeping tokens out of the browser).
Browser ---> Web BFF (REST or tRPC or GraphQL) ---> orders-svc (gRPC)
Mobile ---> Mobile BFF (GraphQL) ---> users-svc (gRPC)
Partner ---> Public API gateway (REST/OpenAPI) ---> billing-svc (gRPC)This layering is common and healthy: the public face is REST, the first-party faces are whichever style optimizes that team's workflow, and the interior is gRPC.
Testing each style
| Level | REST | GraphQL | gRPC | tRPC |
|---|---|---|---|---|
| Unit | Test service layer directly | Test resolvers with a mocked context | Test handlers with generated types | Call procedures with createCaller |
| Contract | Schemathesis or Dredd against OpenAPI; oasdiff | GraphQL Inspector for breaking changes; schema snapshot | buf breaking; consumer-driven tests | Type checking; shared types |
| Integration | Supertest or app.request against an in-memory app | Execute operations against the schema with a test context | In-process server on an ephemeral port | createCaller or a test HTTP server |
| End to end | Playwright and API tests | Same | grpcurl scripts, ghz | Playwright |
| Load | k6, Gatling | k6 with realistic queries; test worst-case cost | ghz, k6 gRPC | k6 |
Test examples:
// REST: call the app in memory, no network
const res = await app.request("/orders/ord_123", { headers: { authorization: "Bearer test" } });
expect(res.status).toBe(200);
// tRPC: call procedures directly with a fake context
const caller = appRouter.createCaller({ userId: "u1" });
await expect(caller.order.byId({ id: "missing" })).rejects.toThrow("Order not found");
// GraphQL: execute against the schema
const result = await yoga.fetch("http://localhost/graphql", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ query: "{ order(id: \"ord_123\") { id status } }" }),
});
expect((await result.json()).data.order.id).toBe("ord_123");// Test declarations used above
declare const app: import("hono").Hono;
declare const appRouter: any;
declare const yoga: any;
declare function expect(v: any): any;Contract testing deserves a note: with multiple consuming teams, consumer-driven contract tests (Pact for HTTP, or schema-registry compatibility checks) catch breakage that unit tests cannot.
Exposing APIs to AI agents
AI agents call APIs the way developers do, but they cannot ask a colleague for clarification. They need machine-readable, well-described, safe interfaces.
| Approach | What it is | When to use |
|---|---|---|
| OpenAPI document | The REST contract; many agent frameworks and function-calling layers convert operations to tools automatically | You already have a REST API; descriptions are good |
| MCP server | A server speaking the Model Context Protocol, exposing tools, resources, and prompts to MCP-capable clients | You want a curated, agent-friendly surface rather than raw endpoints |
| GraphQL introspection | Agents can read the schema, but unbounded queries are a risk | Controlled use with persisted operations or a limited schema |
| gRPC reflection | Possible, but typically wrapped by a gateway or MCP server | Internal tools only |
| llms.txt and docs for agents | Plain-text docs pointing to the OpenAPI document | Public APIs wanting discoverability |
Do not expose your raw API one-to-one as tools. A REST API with 200 endpoints becomes 200 tools, which overwhelms a model's tool selection and wastes context. Instead, design a small set of task-oriented tools (for example find_orders, get_order, create_order_draft), with descriptions written for a model, strict input schemas, and bounded, concise outputs.
A minimal MCP server wrapping the orders API (verify the SDK's current API shape; names have evolved across releases):
// mcp/server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "orders", version: "1.0.0" });
server.registerTool(
"get_order",
{
title: "Get order",
description:
"Fetch one order by its ID (format ord_xxx). Returns status, line items, and createdAt. " +
"Use find_orders first if you only have a customer.",
inputSchema: { id: z.string().regex(/^ord_\w+$/) },
},
async ({ id }) => {
const res = await fetch(`${process.env.API_BASE}/orders/${id}`, {
headers: { authorization: `Bearer ${process.env.API_TOKEN}` },
});
if (!res.ok) {
return { isError: true, content: [{ type: "text", text: `Order lookup failed: HTTP ${res.status}` }] };
}
const order = await res.json();
return { content: [{ type: "text", text: JSON.stringify(order) }] };
},
);
await server.connect(new StdioServerTransport());Agent-ready API checklist:
- OpenAPI has an
operationId, asummary, and adescriptionthat explain when to use the operation, not only what it does. - Inputs have precise types, enums, formats, examples, and constraints. Free-form strings are the enemy.
- Responses are small and stable; support field selection or pagination so an agent does not drown in data.
- Errors are actionable and machine-readable, with hints for correction.
- Mutating operations are idempotent (idempotency keys) so retried tool calls do not duplicate work.
- Dangerous actions require confirmation tokens or two-step flows (create a draft, then commit).
- Credentials are scoped, least-privilege, and revocable per agent; log which agent did what.
- Rate limits and cost caps apply, since agents can loop.
- Treat everything an agent reads from your API as untrusted data when it re-enters a prompt (prompt injection through fields such as customer notes).
Migration paths
Most migrations are additive: you do not replace the old API, you build a new facade over the same service layer, then move consumers gradually.
| From | To | Approach |
|---|---|---|
| REST to GraphQL | Add a GraphQL layer whose resolvers call the existing REST services or data layer. Start with the screens that suffer most from round trips. Keep REST for partners | Federate later if multiple teams own subgraphs |
| REST to gRPC (internal) | Define the .proto, implement the gRPC server next to the REST handlers sharing the service layer, migrate callers service by service. Use a gateway (grpc-gateway, Envoy transcoding, or Connect) to keep REST for outsiders | Keep one source of truth for business logic |
| gRPC to REST at the edge | Generate a REST facade from annotations (google.api.http) with a transcoder | Publish OpenAPI generated from the proto |
| GraphQL to REST or BFF | Replace expensive queries with purpose-built endpoints; use persisted queries as the migration map (each persisted operation becomes an endpoint) | Reverse direction is rarer but valid when GraphQL cost exceeds benefits |
| REST to tRPC | For a first-party TypeScript app, add tRPC routers alongside existing handlers, move one feature at a time, share the service layer | Keep REST for any external consumers |
| tRPC to REST or OpenAPI | Introduce an OpenAPI layer (or Hono and Zod-based routes) when you need external consumers; reuse Zod schemas | Plan for external clients early |
The strangler pattern for API styles
- Put a thin facade in front of the old API.
- Implement the new style for one use case, calling the same service layer.
- Route a small percentage or a single client to it; compare behavior and latency.
- Move consumers progressively; track usage per operation.
- Deprecate the old path on a schedule; remove when traffic reaches zero.
Migration checklist
- Business logic lives in a transport-agnostic service layer before you start.
- Contract tests assert old and new APIs return equivalent data for the same inputs.
- Observability tags every request with API style and client ID.
- Rate limits, auth, and error conventions are mapped across styles.
- A rollback path exists at each stage (a feature flag or routing rule).
What tends to go wrong
- Choosing by fashion. GraphQL for a CRUD admin panel with one client, or gRPC for a public API that third parties must call from browsers.
- No contract. Without OpenAPI, SDL, or Protobuf in CI with breaking-change checks, clients break silently.
- Leaking the database schema as the API shape. Internal tables change; the API should not.
- Ignoring N+1 in GraphQL. Resolvers that query per item will melt a database at the first realistic list.
- Unbounded GraphQL queries. No depth, cost, or alias limits is an open invitation to a denial of service.
- Global DataLoaders. Caching across requests leaks one user's data to another.
- gRPC without deadlines. One slow dependency exhausts every caller's resources.
- Layer 4 load balancing for gRPC. One pod gets all the traffic; the others sit idle.
- Using tRPC as a public API. Outsiders cannot consume it, and your type contract is invisible to them.
- Verbs in REST URLs and inconsistent error shapes, so every client writes custom handling per endpoint.
- Returning 200 with an error body in REST (or ignoring status codes), which breaks monitoring, caches, and retries.
- Breaking changes without a deprecation path. Remove only after measuring zero usage.
- Authenticating but not authorizing objects (IDOR). Every identifier from the client is an attack surface.
- No idempotency on writes. Retries (from clients, proxies, and agents) will create duplicates.
- Exposing every endpoint as an agent tool. Curate; write descriptions for models.
- Mixing concerns in the gateway. Business logic in gateway config becomes untestable.
When NOT to use each style
- Do not use REST as the only choice for latency-critical, high-volume internal calls between many services in different languages that would benefit from strict contracts and streaming; gRPC is better there. Do not use REST-style resource modeling when the domain is a rich graph with highly varied client views, if a BFF is not an option.
- Do not use GraphQL if you have one client, a simple domain, no team capacity for schema governance, a heavy CDN-cache requirement, or a public API with unknown consumers where cost control would be a constant fight. Do not adopt federation before you have felt the pain it solves.
- Do not use gRPC for browser-first public APIs, for teams with no appetite for binary tooling, or where you need HTTP caching. Skip it if you have two services and a single language; plain HTTP is enough.
- Do not use tRPC when clients are not TypeScript, when consumers are external, when client and server are deployed independently with long-lived clients (mobile apps in the wild), or when you need a language-neutral schema.
- Do not build a custom RPC protocol. One of the four above (or a framework-native option) will cover you.
Short answers
Can GraphQL replace REST entirely? Technically yes for many products, but you give up easy CDN caching, simple tooling, and some agent friendliness, and you take on cost control and schema governance. Many teams run both.
Is gRPC faster than REST? Usually, per call, thanks to Protobuf and HTTP/2, but measure your own bottleneck. For typical web workloads the database dominates.
Can I generate OpenAPI from tRPC? Community and official-adjacent tools exist to expose tRPC procedures as REST with OpenAPI, but evaluate whether a first-class OpenAPI-first approach (such as Hono with Zod) fits better if external consumers matter.
Should I use JSON:API, HAL, or OData? Only if your ecosystem already does. A consistent, documented convention with OpenAPI is usually enough.
How should an AI agent authenticate to my API? With its own scoped credential (OAuth client credentials or a restricted token), not a shared human token, so you can audit and revoke it independently.
Which one for a new startup? A REST API with OpenAPI plus a TypeScript monorepo with tRPC or server functions for the first-party app is a pragmatic, low-regret combination. Add gRPC internally when you actually split services.
Links worth keeping
- OpenAPI Specification
- RFC 9457: Problem Details for HTTP APIs
- RFC 9110: HTTP Semantics
- GraphQL specification and learning resources
- GraphQL over HTTP specification
- DataLoader
- GraphQL Yoga
- gRPC documentation
- Protocol Buffers documentation
- Buf documentation
- Connect RPC
- tRPC documentation
- Hono and Zod OpenAPI
- Model Context Protocol
- Spectral, oasdiff, Schemathesis
- Related on this site: API rate limiting, idempotency and pagination design