Ch.7: gRPC Streaming Explained: Server, Client, and Bidi
Outline
Transcript
0:00 Picture a nightly export, 90,000 order rows, coming back from a gRPC call as one response. The client sees nothing until the very last row is built, and the server holds the whole thing in memory first. That's the problem: a long, silent wait, and one giant message at the end. We've all written that endpoint. And the usual fix is paging, right? Ask for 1,000, then the next thousand, over and over. You could. Or you change one word in the service definition, the proto file. Put the word stream before the response type, and the first row reaches the client while the server's still reading the rest.
0:42 One word? So what's the catch? There is, and the official gRPC docs flag it themselves. But that word actually picks one of four shapes. We'll match each one to a job, and the catch tells you when not to stream. Okay, four shapes out of one word. Let's hear it. Where does the word go? Start with the normal kind of gRPC method, called unary. One request in, one response out, like calling a function. Now add stream on the response side. That's server streaming: one request, many responses. So our export. The client asks once, and rows keep arriving.
1:20 Yep. Move the word to the request side instead, and that's client streaming, many messages up, one answer back. Put it on both sides, and that's bidirectional, both ends sending as much as they want. So three places to put it, plus leaving it off. Four shapes. But does the call itself change underneath? Less than you'd think. A lot of people think streaming is a separate protocol bolted on. It isn't. Every gRPC call already rides its own HTTP two stream, and every message on it carries a small length prefix.
1:52 The gRPC wire spec lets any call carry any number of those messages each way. Unary just happens to send one. Okay, so unary is really the special case, and the other three aren't exotic at all. So let's build the export as server streaming. In Python, the handler turns into a generator. Instead of building the full result first, it yields each row as it reads it. Hold on. So it's not really just one word. The handler changes too. Fair. The word changes the contract, and the generator is what actually sends early.
2:26 On your side, as the caller, you get an iterator back and loop over it. Each pass hands you the next row as it arrives. So it's like looping over a list that's still filling in. That feels almost too easy. Do the rows at least show up in order? They do. gRPC guarantees message order within a single call. Row one arrives before row two, every time. Then how do I know it actually finished, and didn't just stop? The very last thing on the stream is the status, sent after the final row. Once rows are flowing, success or failure only shows up at the end.
3:04 Wait, so it can fail after I already have rows? Yep. Let's say you've processed 60,000 rows and written them to a file, and then the status says the call failed. Now your code has to decide what a half-finished export means. Keep the rows? Start over? Oof. With 1 big response, it was all or nothing. I guess I'd want to resume, right? Send the ID of the last row I got, and ask for everything after it. That's the usual move, and it only works if you design the request for it from day one. And exports are only one use of server streaming.
3:40 What's the other big one? Anything that behaves like a feed. Tailing a log, watching a long job's progress. Or take a delivery app. A customer's order moves from placed, to packed, to out for delivery, and the app wants each change the moment it happens. And without streaming, the app asks, anything new, every few seconds, for the whole time the order's open. Yeah, we've all shipped that refresh-every-5-seconds loop. Most of those calls come back empty. Streaming asks once and waits. It also fits when nobody knows the size up front.
4:14 For example, a search that keeps finding matches, where the server can't count the results before it starts sending. Right, it just sends until it runs out. And the mirror image of that is where the client does the sending. Now client streaming. When would I want to send many messages and get a single reply? Uploads, mostly. Imagine a phone app pushing a 2-gigabyte video to a service. It sends the file in chunks, one message each, and when the last chunk lands, the server replies once, with the size and a checksum.
4:44 Yeah, or metrics. Say you've got a fleet of sensors sending readings all day. Why not just save them up and send one big batch, though? Then nothing arrives until the batch is done. And a big enough batch can hit gRPC's cap on how large one message can be. As a stream, each reading goes up as it happens. And on the Python server, the method receives an iterator of those incoming messages, loops over it, and returns one response at the end. So how does it know the client's finished? It can't guess from a pause.
5:17 The client closes its half of the stream. That's called a half-close. It means, I'm done sending, but I'm still listening for your answer. Like finishing your side of a phone call, then staying on the line for the reply. That's it exactly. And one nuance from the official docs. The server's single answer usually comes after it's read everything, but not necessarily. It can answer early, say, to reject a bad upload after the first chunk, so the client doesn't send 2 gigabytes for nothing. And that leaves the last shape, stream on both sides. Bidirectional.
5:52 That's the one I'd have been tempted to use everywhere, honestly, just because it sounds the most powerful. What's actually going on in there? It's two independent streams inside one call. The docs say each side can read and write in whatever order it likes. So chat is the classic example. I send whenever I type, you send whenever you type, nobody waits for a turn. Sure. But plenty of bidirectional calls actually take turns. Send a message, wait for an acknowledgement, send the next. It's still one open call, so you skip setting up a new request every time.
6:27 And ordering? Same promise as before? Order is preserved within each direction. But there's no promise about how my messages line up against yours. Oh, that's sneaky. So if we both hit send at the same moment, your screen and mine could show them in different orders? Yep. Which is why chat systems stamp messages with a sequence number or a server timestamp. Got it. Two ordered lanes, no ordering between the lanes. So that's the full set of four. Which reminds me of a Java thing that always bugged me.
6:58 In a normal Spring controller, you just return the object. Over in Java gRPC, even the simplest unary handler is weirdly ceremonious. Why? Because in grpc-java, the server doesn't return the response. You get an object called a stream observer, you push your one response into it with on-next, and then you call on-completed. Wait. That's the streaming shape, isn't it? Push messages, then say done. Yep. For server streaming, you just call on-next more than once. So a unary method is really a stream that happens to carry one message.
7:33 Huh. So the ceremony is really the four shapes sharing one interface. Pretty much. Java's the manual gearbox, Python's the automatic: unary handlers return, streaming ones yield. And in the official Java tutorial, the client-streaming side uses observers too. Which explains a Java code review I once sat through. Callbacks on both ends, for a call that just uploads a file. And all that flexibility has a price, which is the catch I promised. The official performance guide, linked in the description, says streams can't be load balanced once they've started.
8:08 Meaning a stream stays on whichever server it first landed on? For its whole life. Take a team, made up but realistic. They add a 5th server because the other four are running hot. But their clients each hold one long-lived stream, so the new server sits almost idle, the hot ones stay hot, and latency keeps climbing. Oh, that's a nightmare to spot. The load balancer did its job exactly once, back when each stream opened. So how do you get traffic onto the new one? The standard answer is on the server side: cap how long a connection may live.
8:45 gRPC calls it max connection age. The server politely tells clients to reconnect, and any stream still open after a grace period gets cut. Each reconnect is a fresh chance to land on the 5th one. The guide also warns that streams can be hard to debug when they fail, and can hurt scalability, so use them only when they buy a real performance or simplicity win. And I think there's a Python one too, right? Yeah. The guide says that in gRPC Python, streaming creates extra threads and is much slower than unary, unlike the other languages.
9:18 So my paging idea wasn't so dumb after all. For a Python export, maybe not. And long streams have one more enemy. A proxy or load balancer in the middle can decide a quiet connection is idle and cut it. gRPC's keepalive pings can help, but a proxy may still enforce its own timeout. So any stream meant to live for hours needs reconnect logic, and a way to pick up where it left off. Streaming's bill doesn't show up in the proto file. It shows up in operations. So, with the bill on the table, how do you actually pick?
9:53 From how the data flows, not from what sounds impressive. One answer, unary, the default. A flow of answers, server streaming. A flow of uploads, client streaming. Real back-and-forth, bidirectional. I'd push back a little, though. I think our ops lead has a point after that load-balancing story. Her line is, just poll. Every poll's its own call, and each one shows up in the access log. Fair, and for something you check every few minutes, she's right. But if you're asking every second and mostly hearing nothing new, that's a stream you're faking.
10:29 And the reverse mistake is streaming one answer. If there's one response, make it unary, so a balancer that routes each request can still spread them out. So, one word, and where you put it picks the shape. Before someone ships one of these, what should they remember? Server streams send the status last, so a call can fail halfway through. Client streams finish with the sender saying, I'm done, though the server may reply before the upload is finished. Bidirectional keeps each direction in order, but not the two against each other.
11:02 And every stream sticks to the server it started on, costs extra in Python, and can get cut when it goes quiet. Which is why paging's still on the table. Coming up next, what happens when calls fail, the extra details that ride along with each one, and code that wraps every call, like logging. Thanks for listening to Learning Podcasts.