Chapter 3 of 12
Course Progress0 of 12 completed (0%)

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.

API Paradigms Deep Dive: REST vs. GraphQL vs. gRPC vs. tRPCCompare HTTP/REST, GraphQL queries, Protobuf binary gRPC, and end-to-end type-safe tRPC with payload sizes, multiplexing, and schema contracts.UNDERSTANDAPI ParadigmsFOLLOW THE FLOWRESTAPPLY ITGraphQLAPI Paradigms Deep Dive: REST vs. GraphQL vs. gRPC vs. tRPCCompare HTTP/REST, GraphQL queries, Protobuf binary gRPC, and end-to-end type-safe tRPC with payload sizes, multiplexing, and schema contracts.UNDERSTANDAPI ParadigmsFOLLOW THE FLOWRESTAPPLY ITGraphQL

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.

1. REST

Resource-Centric

Universal HTTP semantics, stateless URIs, and native CDN cacheability. Perfect for public third-party APIs.

2. GraphQL

Query-Centric

Single endpoint query language. Eliminates mobile over-fetching by letting the client request exactly the needed fields.

3. gRPC

Procedure-Centric

Binary Protocol Buffers over multiplexed HTTP/2 streams. Maximum throughput and ultra-low CPU serialization costs.

4. tRPC

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"
    }
  }
}
Concept Check

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

REST over HTTP/1.1: Text Headers + Redundant JSON Keys (4.2 KB)Flaw: High CPU serialization overhead and head-of-line blocking

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 Protobuf: Binary Tag-Length-Value Framing (820 B)HTTP/2 multiplexes hundreds of concurrent requests over a single TCP socket

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.

Concept Check

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

REST / JSON · Resource-Oriented
Network Link Simulation

4G Mobile Network (65ms RTT)

Concurrency Level50 Parallel Requests

Tests socket contention and multiplexing benefits

Payload Size (Single)

3.8 KB

Human-Readable wire representation
Header Wire Overhead

620 B

HTTP/1.1 frame packing
Serialization Cost

4.8 ms

CPU encoding/decoding
Total Turnaround Latency

~77 ms

RTT + wire xfer @ 25 Mbps
Wire Inspection & Protocol Frame Format: REST / JSON
Type Contract: Manual OpenAPI / Swagger schemas
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Cache-Control: public, max-age=3600 { "id": "usr_9921", "name": "Jane Doe", "email": "jane@example.com", "avatar_url": "https://assets.cdn.io/avatars/9921.jpg", "role": "admin", "created_at": "2026-03-12T08:22:15Z", "posts_count": 142, "recent_posts": [ { "id": "p_1", "title": "Scalable Microservices", "views": 18420 }, { "id": "p_2", "title": "Zero-Copy Buffers", "views": 9410 } ] }

5tRPC: 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-..." });
Concept Check

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:

API Gateway Contract & Security Hunt
TypeScript

🎯 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: 999 to a safe limit between 3 and 8 (e.g. 5).
  • Prevent credential leakage: set maskSensitiveFields: true to strip password hashes.

7Recap & System Design Decision Matrix

ProtocolBest Used ForStrengthsWeaknesses
RESTPublic third-party APIsUniversal adoption, standard HTTP cachingOver-fetching, rigid response shapes
GraphQLComplex frontend dashboards & mobileTailored payloads, single-roundtrip aggregationComplex edge caching, execution overhead
gRPCInternal microservice RPCsUltra-fast binary Protobuf, HTTP/2 multiplexingBinary format not human-readable; browser hurdles
tRPCFull-stack TypeScript monoreposZero codegen, instant compile-time safetyLimited to TypeScript client/server environments

Ready for Chapter 4 (Caching Strategies)? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us