Ch.6: Why gRPC Is Faster Than REST (It's Not Just Binary)
Outline
- 0:00 Nine Bytes Versus Twenty-Eight
- 0:48 Reading the Nine Bytes
- 1:58 Varints Keep Small Numbers Small
- 3:05 Zero Costs Nothing, Minus One Costs Ten
- 4:32 The Five-Byte Envelope
- 5:29 One Slow Answer Blocks the Line
- 6:28 One Connection, Many Calls in Flight
- 7:34 The Two Catches
- 9:16 Where the Speed Really Comes From
- 10:46 The Bytes and the Road
Transcript
0:00 Take one book record from a REST API: title Dune, 412 pages. As compact JSON, that's 28 bytes. As protobuf, the format gRPC sends, it's nine. Okay, and let me guess the usual explanation. gRPC is faster than REST because it's binary. That's what most people think, and it's maybe half the story. The other half is the connection those bytes ride on, and that half is where the slow, hard to debug problems hide. Huh. I'll admit I always stopped at binary, therefore fast. I never counted the connection as part of the speed.
0:36 Right. So we'll open that one message byte by byte, then the connection it travels on. Sources are linked in the description, and each half has a catch that bites in production. Okay, let's unpack the bytes first, then. Walk me through the nine. What's actually in there? Byte one is hex zero A, which is just the number 10, and it does two jobs at once: it says which field this is, and what shape of value comes next. Every field in the schema has a number, and the math is field number times eight, plus the wire type.
1:11 So 10 means field 1, type two, and type two says a length comes next. So that single byte stands in for quote, title, quote, colon. The name lives in the schema file both sides compiled, and only the number travels. Then the next byte is four, the length, followed by the four letters of Dune. Yep, that's the whole first field. Let me try the second one. Its tag byte is 16. Two times eight, plus zero, so field 2, type zero. What does type zero mean? A whole number of flexible size follows. Here it's 2 bytes, and together they make 412.
1:50 If the book had 42 pages, that number would've fit in a single byte. Wait, so why the second byte? So that jump from 1 byte to two is the varint, short for variable length integer, and I think it's the cleverest trick in the format. Each byte holds 7 bits of the number, and its top bit is a flag that means, more bytes coming. And 7 bits tops out at 1:20-seven. Exactly. So 42 fits in 1 byte. 412 needs 9 bits, so it spills into a second byte, and the first byte raises the flag to say keep reading.
2:27 Which pays off because most numbers in real messages are small. Counts, enum values, and the field numbers themselves. And that last one gives you a real tip. The official language guide says field numbers one through 15 take 1 byte, type included. 16 through 2047 take two. So, let's say an order message. I'd give the order ID, the status, and the amount field numbers under 16, since they're in every message, and let a rarely set gift note live up at 20. And I'd pick those on day one, because renumbering later breaks every reader of the old bytes.
3:05 Now, varints aren't the only surprise in the encoding. A regular field left at its default, a zero or an empty string, costs nothing. It's just not in the bytes. So set pages to zero, and our Dune record drops to 6 bytes, but the reader can't tell zero from never set. The guides flag a nastier one, though. For example, put minus one into a regular int 32 field, and the value alone takes 10 bytes. Wait, really? 10 bytes, for minus one? 10. Minus one rolls over like an odometer running backward past zero, into an enormous positive number, and varints only stay short for small ones.
3:44 Declare the field as the zigzag type instead, spelled s-int 32. ZigZag takes turns between the signs: minus one becomes one, plus one becomes two, minus two becomes three, so small negatives stay small, and minus one is back to 1 byte. Oof. I've declared a temperature delta that way without a second thought. Most of us have. 10 bytes every time it dropped a single degree. 10 bytes to announce it got a little chilly. And while we're counting bytes, a lot of people think protobuf is compression. It isn't. It's just a compact way to write values the schema already describes.
4:20 Right, and gRPC does offer real compression, but that's a separate opt-in, per call or per message. Which means the 9 bytes we've got are plain protobuf, nothing squeezed. Once those 9 bytes are encoded, though, do they just go out on the wire like that? Not quite. gRPC wraps every message in a 5-byte envelope first, per gRPC's own protocol spec: 1 byte that says whether it's compressed, and 4 bytes of length. So our 9 bytes travel as 14. But why bother with a length? Doesn't the connection know where things end?
4:54 It knows where its own frames end, the small chunks the connection actually ships, and those chunks can split or bundle your bytes however they like. For instance, one big message might span several frames. So the receiver reads 5 bytes, learns it needs exactly nine more, and then it has one whole message. Oh, so that's also how one call can carry more than one message. Read an envelope, then read the next one. Yeah, that's the framing streaming builds on. For now, it's one call, one message, 14 bytes.
5:26 And those 14 bytes still need a road. And that road is the second half of the speed story. With classic HTTP 1.1, a connection effectively handles one response at a time. You send a request, wait for the answer, then send the next. There was pipelining, though, sending several requests without waiting. There was, and even the HTTP two spec admits pipelining still suffers from head of line blocking. Answers have to come back in order, so one slow response holds up every answer queued behind it. Like a one lane road behind a slow truck.
6:02 Doesn't matter how fast your car is. Yeah, and everyone's fix is more lanes. Clients open several connections side by side, each with its own handshake and its own memory. Now imagine a service making thousands of small calls a second to its neighbor, juggling a pile of connections, one answer at a time each, just to fake concurrency. That's a scaling nightmare, and it's the problem HTTP two set out to fix. And the fix is to stop giving each call a whole connection. In HTTP two, every gRPC call gets its own stream, a numbered conversation, and the gRPC spec literally uses that stream number as the call's ID.
6:42 And all those streams share one connection? One connection. Each call's data is chopped into small frames tagged with its stream number, and frames from different calls interleave on the wire. The other side sorts them back out by number. Okay, that's the part that finally clicked for me. A slow call is just a stream whose frames haven't shown up yet, so the fast call next to it finishes anyway. Take a checkout service that fires a price lookup, a stock check, and a fraud score at once, over one connection.
7:13 Right, and if the fraud score takes a full second, the price and stock answers still land in milliseconds instead of queuing behind it. That's multiplexing. So one warm connection, no fresh handshake per call, and nobody stuck behind the truck. At least at the HTTP layer. The connection's catches live one layer further down. Down a layer, huh. I thought multiplexing just got rid of the slow truck. It did, for HTTP. But the head of line blocking just moved underneath. Below HTTP two there's still one TCP connection, and TCP hands bytes over strictly in order.
7:48 So if one packet gets lost... Every stream on that connection waits for the resend, even calls whose data wasn't in that packet. That's part of why HTTP three runs on QUIC, a newer transport, instead of TCP. Ouch, all of them at once. And the second catch is the one I'd actually get paged for. The server caps how many streams a client can have open on one connection at once, and HTTP two's own spec recommends that cap be at least 100. So if the cap's 100, what happens to call 101? The gRPC performance guide says it waits in a queue inside the client until a slot frees up. The server doesn't even know it exists yet.
8:30 Consider a team, made up but realistic, whose latency spikes every afternoon while the server's own dashboards show every request finishing fast. And that's what makes it sneaky. The slow part is a waiting room on the caller's side, and the server can't see it. Honestly, I'd have spent a week staring at server traces before thinking to look at the client. Same, probably. And reuse is still right. A channel's just the long-lived connection handle, and a fresh one per call throws away the warm connection.
9:03 But when one connection's streams fill up, the guide suggests a small pool of channels, each set up a little differently so they really open separate connections. That gives the waiting calls somewhere else to go. So, with both catches on the table, let's be honest about where the speed comes from. Smaller messages, yes. And cheaper parsing, since the layout is agreed ahead of time, so nobody scans text hunting for quotes and colons. Right. Plus the connection gets reused, with many calls in flight at once.
9:34 And that part matters more the more calls you make. Though plain REST can ride HTTP two and get those same lanes, right? It can, if both ends negotiate it. gRPC just requires HTTP two, so it never quietly falls back to the old single-file lane. And even then, it's not always faster. For a tiny message, the headers can outweigh the body either way, so the byte savings barely register. And browsers can't speak it directly, they need a translating proxy in between. I'd push back on the byte obsession a little, too.
10:07 I mean, ask whoever's on call at two in the morning. They'll tell you, just let me curl it and read the response. With protobuf, those bytes are just numbered fields until you've got the schema and a tool to read them. Fair, that's a real cost. So where do you draw the line? I think for service-to-service traffic at volume, the bytes and the connection both pay off. For a public API that humans poke at, JSON's readability often wins. Right. For example, an internal dashboard polling 10 times a minute won't notice the difference, so the choice there comes down to what your team can debug. So, pulling the whole thing together. Start with the bytes.
10:49 A tag folds the field's number and its type into 1 byte, varints keep small numbers small, and defaults cost nothing. Watch your negative numbers, keep the hottest fields in one through 15, and remember the length prefix that tells the receiver where a message ends. Then the road. Each call rides its own numbered stream on one shared connection, so slow calls stop blocking fast ones. Until one lost packet stalls every stream, or call 101 waits in your client's queue. And next time someone says gRPC is fast because it's binary, you'll know it's the bytes and the road.
11:25 Coming up, we'll send a whole stream of those envelopes down one call, which is streaming RPCs. Thanks for listening to Learning Podcasts.