An introduction to tRPC, and how it differs from REST, GraphQL and gRPC


Most API styles start by asking you to describe your API in something other than your code: an OpenAPI document, a GraphQL schema, a .proto file. tRPC starts from the opposite end. You write ordinary TypeScript functions on the server, and the client calls them with full type safety, with no schema language and no code generation step in between.

I’ve used tRPC at a consultancy client and I use it for PencilsDown, my 11+ exam platform, which is where the examples below come from. This post covers what tRPC is, what it puts on the wire, and how it compares with REST, GraphQL and gRPC.

The idea: the server’s types are the contract

A tRPC API is made of procedures, grouped into routers. A procedure is a function with an optional input validator. It’s either a query (reads) or a mutation (writes).

Here is a real router from PencilsDown, trimmed slightly. It lets an admin create and list codes that give a family free weeks of access:

// packages/domain: the input, declared once with Zod
export const FreeCodeInput = z.object({
  code: FreeCodeText,
  weeks: z.number().int().min(1).max(52),
  redeemBy: IsoDate,
  note: z.string().trim().max(200).nullable(),
});

// apps/api: the router
export const freeCodesRouter = router({
  create: staffProcedure('admin')
    .input(FreeCodeInput)
    .mutation(async ({ ctx, input }) => {
      const code = await freeCodes(ctx.db, ctx.actor).create(ctx.principal.orgId, input, clock(ctx));
      return { code: code.code, weeks: code.weeks, redeemBy: code.redeemBy, note: code.note };
    }),

  list: staffProcedure('admin').query(async ({ ctx }) =>
    (await freeCodes(ctx.db, ctx.actor).list(ctx.principal.orgId)).map((c) => ({
      code: c.code, weeks: c.weeks, redeemBy: c.redeemBy, redeemed: c.redeemed, paid: c.paid,
    })),
  ),
});

Three things to notice:

  • The input is validated at runtime. .input(FreeCodeInput) runs the Zod schema on every call. weeks: 53 never reaches the function body.
  • The output type is inferred. Nobody wrote a FreeCodeResponse type. Whatever the function returns is the response type.
  • Authorisation is a procedure builder. staffProcedure('admin') is a base procedure with middleware that checks the caller’s role and puts a typed principal on ctx. A procedure built on it cannot forget the check.

Routers nest into one root router, and the server exports a single thing to the client: its type.

export const appRouter = router({
  me: meRouter,
  family: familyRouter,
  freeCodes: freeCodesRouter,
  examSitting: examSittingRouter,
  // …and 18 more
});

/** The only thing the SPA imports from the API. */
export type AppRouter = typeof appRouter;

That’s a type-only import, so no server code ends up in the browser bundle. On the client it turns the whole API into autocomplete:

const trpc = useTRPC();

const list = useQuery(trpc.freeCodes.list.queryOptions());
//    list.data is { code: string; weeks: number; redeemBy: string; … }[]

const create = useMutation(
  trpc.freeCodes.create.mutationOptions({
    onSuccess: () => queryClient.invalidateQueries({ queryKey: trpc.freeCodes.list.queryKey() }),
  }),
);

create.mutate({ code: 'SPRING', weeks: 53, redeemBy: '2027-03-01', note: null });
//                              ^ fine for the compiler (it's a number); Zod rejects it at runtime

Rename a field on the server and every client usage goes red in your editor before anything is deployed. That feedback loop is the whole point of tRPC: the compiler is the contract test.

What actually goes over the wire

Despite the name, there’s nothing exotic underneath. tRPC is JSON over plain HTTP:

GET  /trpc/freeCodes.list
POST /trpc/freeCodes.create        {"code":"SPRING","weeks":4,…}
  • A query is a GET with the input JSON-encoded in the query string. A mutation is a POST with the input in the body.
  • The path is the procedure’s name: router, dot, procedure. There are no resources, no path parameters and no choice of verb to argue over.
  • Responses are {"result":{"data":…}} or an error with a code such as FORBIDDEN or NOT_FOUND, which tRPC maps onto HTTP statuses.
  • An optional transformer (PencilsDown uses superjson) carries types JSON can’t, so a Date arrives as a Date. With superjson each payload is wrapped one level deeper, as {"json":…}; I’ve left that wrapper out of the examples here.

Batching

There’s one wrinkle worth understanding, because it’s the first odd thing you’ll see in the network tab:

GET /trpc/me.get,freeCodes.list?batch=1&input=…

That is two procedure calls in one HTTP request. When the admin’s free-codes page loads, the page shell asks who is signed in (me.get) and the page itself asks for the codes (freeCodes.list). Those are two separate useQuery calls in two separate components, and neither knows about the other.

tRPC’s batching link collects every call made in the same tick of the event loop and sends them together:

  • the procedure names are joined with commas in the path;
  • batch=1 tells the server to split them apart again;
  • input is one JSON object keyed by each call’s position, so "0" is the input for me.get and "1" for freeCodes.list.

The server runs each procedure separately and answers with an array in the same order:

[
  { "result": { "data": { "id": "…", "displayName": "…", "roles": ["admin"] } } },
  { "result": { "data": [{ "code": "SPRING", "weeks": 4 }] } }
]

Each entry succeeds or fails on its own, so one FORBIDDEN doesn’t spoil the other result. When the entries disagree, the HTTP status of the whole response is 207 Multi-Status and each entry carries its own code. The client hands each component its own piece, and neither can tell it shared a request.

A note on monitoring. 207 is a 2xx status. Anything that only reads the status line, such as API Gateway’s 4xx and 5xx metrics, CDN logs or an uptime check, records a partly failed batch as a success, even when one of the calls inside it threw. With batching on, count failures per procedure from inside the server (tRPC’s onError hook is the place) and don’t rely on HTTP status codes at the edge.

This is how tRPC gets one of GraphQL’s benefits, a page’s worth of data in one round trip, without a query language. It’s also opt-in: use the plain HTTP link instead of the batching one and every call is its own request.

Because it’s just HTTP, the same router runs anywhere through an adapter: a standalone Node server, Express, Fastify, Next.js, a fetch handler, or AWS Lambda. PencilsDown runs one router on the Lambda adapter in AWS and on the standalone adapter on my laptop.

How it compares

RESTGraphQLgRPCtRPC
UnitResource + verbField on a typed graphService methodProcedure
ContractOpenAPI document (optional)Schema (SDL).proto fileThe server’s TypeScript types
Typed clientsCode generation from OpenAPICode generation from the schemaCode generation from .protoInference, no generation
Wire formatJSON over HTTPJSON over HTTP, one endpointProtobuf over HTTP/2JSON over HTTP
LanguagesAnyAnyAnyTypeScript on both ends
Who shapes the responseServerClientServerServer
HTTP cachingNativeHardNoPossible for queries, rarely used
StreamingSSE or WebSockets, bolted onSubscriptionsFirst-class, bidirectionalSubscriptions
Best audiencePublic and third-party APIsMany clients with different data needsService-to-service, polyglotOne team, one TypeScript codebase

tRPC vs REST

REST models your API as resources manipulated with HTTP verbs. Its great strength is that it is the web’s native language. Every client, proxy, cache and developer already understands it, which makes it the right default for a public API.

The costs show up inside a single product team. You spend design effort mapping operations onto nouns and verbs (“is cancelling a subscription a DELETE or a POST to /cancel?”), and the types don’t travel on their own. To get a typed client you maintain an OpenAPI document, by hand or generated, and run a code generator, and both can drift from what the server really does.

tRPC drops the mapping exercise and the generation step. A procedure is named for what it does (examSitting.submit), and its types can’t drift because they are the server code. What you give up is everything REST gets from being standard HTTP: cache-friendly URLs, a self-describing surface for strangers, and clients in any language.

tRPC vs GraphQL

GraphQL exists to solve a specific problem: many different clients needing different shapes of the same data. The client writes a query naming exactly the fields it wants, and the server resolves it against a typed graph. If you have a web app, two mobile apps and partners all reading overlapping data, that flexibility is worth a lot.

It isn’t free. You maintain a schema and resolvers, guard against N+1 queries and expensive client-written queries, give up straightforward HTTP caching, and still run code generation to get typed clients.

tRPC makes the opposite trade. The server decides what each procedure returns, as in REST, so there’s no query language and no resolver layer. If your only client is your own frontend, the flexibility GraphQL offers is solving a problem you don’t have, and tRPC gives you the end-to-end types with far less machinery.

tRPC vs gRPC

The names invite confusion, and they do share an idea: call a named remote function instead of manipulating a resource. Beyond that they’re built for different jobs.

gRPC is contract-first and polyglot. You define services in a .proto file and generate clients and servers in whatever languages you need. It speaks binary Protobuf over HTTP/2, which makes it compact and fast, and it has first-class streaming in both directions. It’s designed for service-to-service traffic inside a backend. Browsers can’t speak it directly, so web clients need gRPC-Web or a similar translation layer.

tRPC is code-first and TypeScript-only. There’s no IDL, no generated code and no binary format. It’s designed for the browser-to-server hop of a single application.

A reasonable rule of thumb: gRPC is for when the two ends are written by different teams in different languages, and tRPC is for when they’re written by the same team in the same repository.

When I’d reach for it, and when I wouldn’t

tRPC fits when:

  • the client and server are both TypeScript, ideally in one monorepo;
  • one team owns both ends and ships them together;
  • the API exists to serve your own frontend, not third parties.

I’d choose something else when:

  • the API is public, or consumed by teams who can’t import your types. tRPC publishes no schema by default, so to anyone outside the compiler it’s an undocumented JSON API. I saw this at the client: once one backend service needed to call another, working out what a procedure expected meant reading that team’s source code.
  • clients aren’t TypeScript. A Swift or Kotlin app gets none of the benefit.
  • you need heavy HTTP caching or long-lived, bidirectional streaming.

There’s also a quieter cost. The server and client are coupled at compile time, which is the feature, but it means they’re best deployed together, and a very large router can slow the TypeScript language server down.

What’s next

tRPC’s shape, small named procedures grouped into routers, happens to fit AWS Lambda very well, and that’s how both the client’s system and PencilsDown are deployed. But the type-safe loop only pays off if you can actually run the thing on your own machine, which is where the client’s setup fell down. In the next post I’ll cover running tRPC on Lambda and the local harness that makes it pleasant. After that, I’ll look at the same architecture in Ruby with Foobara, where the contract is a published manifest instead of a compiler’s types.