Ch.5: gRPC Tutorial: Build and Call Your First Service
Outline
- 0:00 The Failed Call That Said 200
- 0:59 Step One: The Contract
- 2:09 Step Two: What the Generator Hands You
- 3:02 The Server Is One Method
- 4:11 Step Three: The Client and the Deadline
- 5:34 Step Four: Tracing One Unary Call
- 6:18 The Payload Is Not the Verdict
- 7:45 Why the Status Comes Last
- 8:56 Empty and OK, or NOT_FOUND?
- 10:22 Four Steps and One Check
Transcript
0:00 Imagine a team that just moved its first service to gRPC. Their dashboard is all green, every request answering HTTP 200. Meanwhile a 3rd of the calls are failing, and nobody on call notices. Yeah, and the dashboard isn't really broken. It's grading every call by the one number that never changes. gRPC is the framework for calling a function on another server like a normal method, and its spec answers 200 even when the call fails. Wait, the spec does that on purpose? Yep, deliberately, and for every response.
0:33 The real outcome travels somewhere else, tucked in at the very end. That team's made up, by the way, but the behavior is straight from the protocol spec linked in the description. So here's the plan: build the smallest real gRPC service in four steps, the contract, the server, the client, and one call traced end to end. By step 4, you'll know exactly where that outcome hides, and why your monitoring should read it. And step one is the contract, written in a proto file. That's protobuf, the schema language a compiler turns into typed classes.
1:07 Messages describe data, the nouns. Take the classic example, a greeter: a hello request carrying a name, and a hello response carrying a greeting. And the verbs come from the service block. Ours is called Greeter, with 1 method: say hello takes a hello request and returns a hello response. Yep. Think of it as an interface in Java or an abstract base class in Python: what callers may invoke, with no body saying how. Hmm, I think what got me the first time I read one is that the method line is basically the API documentation, except the generated code holds both sides to it.
1:46 Right, no URL to design, since the method name becomes the path for you, no JSON body convention, no wiki page for the client team to misread. Rename that say hello method or change what it takes, and every team that regenerates finds out fast. Java won't compile, and in Python the first test that calls it breaks, instead of you discovering it during a rollout. With the contract in hand, step 2 is the server, and it starts with 1 command: the protobuf compiler plus the gRPC plugin, which in Python ships as the grpc tools package.
2:20 You get two files back. Let me guess, one for the client and one for the server? Not quite. It splits by layer, not by side. One file holds your message classes. The other holds the calling machinery gRPC adds on top. Okay, so which pieces in there do I touch? Two you'll actually write against. The client holds a greeter stub, a local object whose methods make the remote call for you. The server gets a greeter servicer, a base class you fill in. There's also a small helper that plugs your servicer into the server, and none of it gets edited by hand, since it's regenerated whenever the proto changes.
2:58 Which leaves the one part nobody can generate for you. So it's one method, and it's almost anticlimactic. You subclass the greeter servicer and override say hello. It receives the request plus a context object, which is also where you'd set an error status, and we'll need that later. You read the name, build the response with a greeting, and return it. And no socket code, no parsing on my side? None. The framework decodes the bytes into a typed request before your code runs, and encodes whatever you return afterward.
3:30 Java's the same shape: you extend the generated base class, hand your reply to a response observer, and mark it completed. Okay, so the handler's tiny. The startup code is boilerplate straight from the gRPC Python tutorial: create the server, register your servicer, bind a port, start it, then wait for termination. Skip that last call and your script can run straight off the end and exit. Right, and none of those moves touch your logic. Routing and connections are the runtime's problem, which is kind of the entire pitch, honestly. Sure, and it's a good pitch.
4:03 It also means a lot of the interesting failures move out of your code and into the space between two processes. And step 3 is where your code actually crosses that space, from the caller's side. You open a channel to the server's address, a long-lived handle that manages the actual network connections for you. Then you wrap the channel in the greeter stub, build a hello request with a name, and call stub dot say hello. A typed response comes back. Which reads exactly like a local function call, and in Java the blocking stub looks identical.
4:40 That's sort of the magic trick and the trap at the same time. Why the trap, though? Because the stub is a stunt double for a process on another machine. A local call can't hang on a dead network, and this one can. And by default, gRPC sets no deadline, so the official deadlines guide warns a client can wait effectively forever. Oh, that's nasty. And we've all written a network call without a timeout. Let's say one server gets stuck: your caller just sits there holding the request, and so does whatever was waiting on that answer.
5:12 So what does a deadline actually look like in Python? A timeout argument on the stub call, let's say timeout equals 2 seconds, and you want it on every one. When it runs out, your own client library fails the call with a status called deadline exceeded, no server reply needed. Hold onto that word, status, because it's where this whole call is heading. Now step 4 is the trace, and first, a name for what we just built. gRPC calls this shape unary: one request in, one response out, the simplest shape it has.
5:45 Okay, let's hear it. What actually happens between my call and that typed response showing up? First, the client library turns your request into protobuf bytes. Second, those bytes go out with headers naming the method, plus any metadata, meaning key value pairs like an auth token. 3rd, the server routes the call to your handler, runs it, and sends the response bytes back. And that's usually where tutorials stop. Payload arrives, done. Except the status we just held onto never showed up anywhere in that picture.
6:18 And gRPC's own core concepts page spells it out. The reply arrives together with status details, a status code plus an optional message. Only if that status is OK does the client get the response. Where does that status physically travel, then? The gRPC over HTTP two spec sets the HTTP status to 200 for every gRPC response. The outcome goes into trailers, which are headers sent after the body. A key named grpc status carries a number, and zero means OK. Even for a call that fails instantly, before there's any payload at all?
6:54 Even then. When a call fails right away, the server can skip the body and send a single block of headers with the status folded in, still stamped 200. That 200 up top only means the conversation happened. Which is exactly how our made-up dashboard stayed green. It counted envelopes and never opened the letter. Yeah, and every envelope gets the same cheerful postmark, bad news included. And the letter's always there: even a successful call ends with a status, a zero. In Python, a failure never hands you a quiet empty object.
7:29 It raises an error that carries the code. Hang on, then my client has to decide per code? Retry some, give up on others? Right. A code like unavailable, you'd usually retry, with backoff. Not found, retrying won't conjure a record that isn't there. So, back to that status showing up last. Why put it there at all? Sending it up front with the headers sounds simpler. Mostly because the same protocol also carries streaming calls, where the server starts sending long before it knows how things end. It can hit an error, you know, halfway through.
8:02 The outcome doesn't exist until the call closes. Okay, that tracks. And the design is load bearing. Browser code can't read HTTP trailers. So when gRPC went to the browser, the gRPC web spec moved the trailers into the response body rather than drop the status. Huh. They'd rather bend the protocol than lose the verdict. They did. Without it, a browser client couldn't tell not found from OK. Right, and on-call depends on it too, whether they know it or not. Say you tell an on-call engineer their gRPC failures are invisible.
8:37 The reply is, we page on five hundreds, and that graph's been flat all quarter. Not for this. That page stays quiet whenever the server itself reports the failure, because the response still says 200. So point your proxy metrics, alerts, and dashboards at gRPC status codes instead. But the status only helps if your handler sets the right one. Suppose the say hello handler first looks the name up in your user table, and nobody by that name exists. Two options, then. Return an empty hello response marked OK, or set a not found status on that context object, and then the trailer literally reads grpc status five, not found, sitting right behind that cheerful 200.
9:21 And I once shipped the empty version on a user lookup. Every caller treated a blank profile as success, our error rates looked perfect, and it took us way too long to notice the missing users. Oof. The dashboard team's problem again, just moved into the handler. Same disease, and worse, because gRPC status monitoring won't catch it. The status says OK. Only the handler knows the user was missing. I'd push back a little, though. Sometimes empty is a legitimate answer. Think of a search that matches nothing: it hasn't failed. Fair, so this is a real design choice, not a beginner mistake.
9:59 So where's the line? The line is what they asked for. If they searched and nothing matched, empty is the honest answer. If they asked for one specific user by name and that user isn't there, that's not found. So decide on purpose, per method. gRPC guarantees every call gets a status. Whether it's an honest one is still on you. So let's pull the build back together. Step one, the service block lists the methods a caller can invoke. Step 2, the server: the generator hands you a base class to fill in, so your own code shrinks to one handler.
10:35 Step 3, the client calls the stub as if it were local, but always with a deadline, because it isn't local. Step 4, every call finishes with a status, and when the server sends it, it rides in the trailers, separate from the payload. And the one check to take back to work: open the letter. When you measure a gRPC service, read the gRPC status, not just the HTTP code. Next time, we open up the bytes themselves, what that request is made of on the wire. Thanks for listening to Learning Podcasts.