Modern System Design & API Architecture · Chapter 3 · ~22 min · Intermediate
API Paradigms Deep Dive: REST vs. GraphQL vs. gRPC vs. tRPC
Master the architectural trade-offs of modern API protocols. Understand when to choose REST for public caching, GraphQL for flexible frontends, gRPC for high-throughput microservices, and tRPC for seamless full-stack type safety.
- Compare REST, GraphQL, gRPC, and tRPC trade-offs across bandwidth, type safety, and multiplexing
- Analyze over-fetching and under-fetching with practical schema queries
- Master HTTP/2 binary framing and Protocol Buffers (Protobuf) serialization
- Design type-safe client-server contracts with zero schema code-generation overhead
API Paradigms Deep Dive: REST vs. GraphQL vs. gRPC vs. tRPC: learn it visually
Compare HTTP/REST, GraphQL queries, Protobuf binary gRPC, and end-to-end type-safe tRPC with payload sizes, multiplexing, and schema contracts.
1The API Contract: How Systems Communicate
At scale, system performance is rarely constrained by raw CPU clock speed; it is constrained by network bandwidth, serialization latency, socket contention, and contract maintenance overhead. Every architectural boundary—between mobile clients and edge gateways, or between internal microservices—demands a deliberate protocol choice.
Resource-Centric
Universal HTTP semantics, stateless URIs, and native CDN cacheability. Perfect for public third-party APIs.
Query-Centric
Single endpoint query language. Eliminates mobile over-fetching by letting the client request exactly the needed fields.
Procedure-Centric
Binary Protocol Buffers over multiplexed HTTP/2 streams. Maximum throughput and ultra-low CPU serialization costs.
Type-Centric
End-to-end static type inference for full-stack TypeScript teams. Zero schema generation or boilerplate.
2REST vs. GraphQL: Over-Fetching, Under-Fetching & Caching
The classic REST pattern exposes fixed data shapes per endpoint (e.g., GET /users/:id). On rich client dashboards, this leads to two notorious problems:
Over-Fetching
Downloading 40 database columns (including bio, address, settings) when the mobile view only needs the user's name and avatar thumbnail. Wastes cellular data.
Under-Fetching (The N+1 Problem)
Fetching a user's profile requires call 1 to /users/1, then 10 subsequent HTTP calls to /posts/:id for each post. Multiplies round-trip latency.
// REST Response: Over-fetched payload (1.8 KB transmitted)
{
"id": "u_101",
"name": "Alex Mercer",
"email": "alex@mercer.dev",
"phone": "+1-555-0199",
"tax_identifier": "US-XX-9901",
"last_login_ip": "192.168.1.1",
"bio_history": ["...", "..."],
"internal_permissions": ["read:all", "write:posts", "audit:logs"]
}GraphQL solves this by allowing the frontend client to dictate the shape of the response:
// GraphQL Query: Client requests only what the view requires
query GetAuthorAvatar {
user(id: "u_101") {
name
avatar_url
}
}
// Result: Minimized payload (94 bytes transmitted)
{
"data": {
"user": {
"name": "Alex Mercer",
"avatar_url": "https://cdn.io/u_101.jpg"
}
}
}Why can GraphQL endpoints be significantly harder to cache at the edge (CDN) compared to REST endpoints?
3gRPC: HTTP/2 Binary Protocol Buffers for Microservices
When microservice A calls microservice B tens of thousands of times per second, string parsing of JSON and HTTP/1.1 connection negotiation become major bottlenecks. gRPC revolutionizes this with two foundations:
1. Protocol Buffers (Protobuf) Serialization
Instead of sending repetitive text keys like {"user_name": "Jane"}, Protobuf assigns field index tags (e.g., tag 1 = user_name). The wire format transmits binary tag-length-value bytes, yielding 5x to 10x faster serialization and 60–80% smaller payloads.
2. HTTP/2 Stream Multiplexing
HTTP/1.1 requires opening a separate TCP socket for each concurrent request or suffering Head-of-Line (HoL) blocking. HTTP/2 breaks requests into binary frames interleaved across a single persistent TCP connection.
Wrong idea: REST JSON is always the optimal default for every service-to-service call
Assuming readable JSON over HTTP/1.1 introduces negligible overhead for high-throughput internal microservice communication.
Real system: Binary Protobuf over HTTP/2 eliminates serialization and header bloat
gRPC encodes typed fields into compact numeric tags over multiplexed HTTP/2 streams, cutting payload size by up to 75% and speeding up CPU parsing.
How does HTTP/2 stream multiplexing in gRPC overcome HTTP/1.1 Head-of-Line (HoL) blocking?
4Hands-On: API Protocol Benchmarker & Wire Inspector
Experiment with REST, GraphQL, gRPC, and tRPC under varying network conditions and concurrency levels. Inspect the raw wire encoding and examine how serialization overhead scales under load:
API Protocol Benchmarker & Wire Payload Inspector
4G Mobile Network (65ms RTT)
Tests socket contention and multiplexing benefits
3.8 KB
Human-Readable wire representation620 B
HTTP/1.1 frame packing4.8 ms
CPU encoding/decoding~77 ms
RTT + wire xfer @ 25 Mbps5tRPC: The Zero-Codegen TypeScript Evolution
In modern monorepos where both client and server are written in TypeScript, generating OpenAPI specs or compiling Protobuf files introduces unnecessary toolchain friction. tRPC solves this by leveraging TypeScript's inference engine:
// server/routers/postRouter.ts
import { router, publicProcedure } from "../trpc";
import { z } from "zod";
export const postRouter = router({
getById: publicProcedure
.input(z.object({ postId: z.string().uuid() }))
.query(async ({ input, ctx }) => {
const post = await ctx.db.post.findUnique({ where: { id: input.postId } });
if (!post) throw new Error("Post not found");
return post; // Type inferred directly from Prisma database model
}),
});
// client/components/PostCard.tsx
// Zero code generation required! The return type and input parameters are 100% type-checked:
const { data, error } = trpc.post.getById.useQuery({ postId: "a10b-..." });When is tRPC the recommended API protocol choice over gRPC or public REST?
6Bug Hunt: Fix the API Gateway Contract & Security Config
A newly deployed API Gateway handles ingress routing for REST, GraphQL, and gRPC backends. However, the configuration contains three critical reliability and security flaws: HTTP/2 multiplexing is disabled causing socket pool exhaustion, GraphQL query depth is uncapped allowing recursive query DoS attacks, and sensitive authentication hashes are exposed through the response serializer.
Fix the gateway configuration below and click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Enable stream multiplexing: set
enableHttp2Multiplexing: true. - Cap GraphQL query recursion: change
maxGraphQLQueryDepth: 999to a safe limit between 3 and 8 (e.g.5). - Prevent credential leakage: set
maskSensitiveFields: trueto strip password hashes.
7Recap & System Design Decision Matrix
| Protocol | Best Used For | Strengths | Weaknesses |
|---|---|---|---|
| REST | Public third-party APIs | Universal adoption, standard HTTP caching | Over-fetching, rigid response shapes |
| GraphQL | Complex frontend dashboards & mobile | Tailored payloads, single-roundtrip aggregation | Complex edge caching, execution overhead |
| gRPC | Internal microservice RPCs | Ultra-fast binary Protobuf, HTTP/2 multiplexing | Binary format not human-readable; browser hurdles |
| tRPC | Full-stack TypeScript monorepos | Zero codegen, instant compile-time safety | Limited to TypeScript client/server environments |
Ready for Chapter 4 (Caching Strategies)? Mark this chapter as complete to proceed: