Ch.8: gRPC Status Codes, Metadata, and Interceptors
Outline
- 0:00 The Status Called Unknown
- 1:03 The Codes You'll Actually Use
- 2:23 Retry, or Stop
- 3:53 Sending a Code, and Catching It
- 5:21 When a Code Isn't Enough
- 6:32 Metadata, the Side Channel
- 8:11 Twenty Methods, One Check
- 9:40 What Lives in the Wrapper
- 11:18 The Order of the Wrappers
- 12:44 The Code Is an Instruction
Transcript
0:00 Picture an orders service written in Python. A customer types a coupon code, the gRPC handler looks it up in a dictionary, and the code isn't there. Key error. And nobody catches it. So the server doesn't crash. gRPC just fails that one call? It fails it with a status code called unknown. And in gRPC Python, the details read, exception calling application, followed by your exception's own text. So the caller gets a vague code plus a peek at your internals. Oof. And from the outside, a typo in the coupon and a bug in our own code look identical. Our tech lead's answer to that is, just retry everything three times.
0:40 And if it was our crash, that's three identical crashes. So we'll fix it on the server side, because that code isn't just a label. It's an instruction to the caller. Which code to send, when to retry, and what to attach. And then the stuff riding alongside every call, metadata and interceptors, so auth, logging, and tracing get written once instead of 20 times. So if a status is an instruction, how many instructions are we choosing from? 17, numbered zero to 16, and zero means OK. Every call ends with 1, even the successful ones.
1:15 But a typical handler only reaches for a handful. Let's hear it. Invalid argument, when the request itself is bad. Not found, when the thing they asked for doesn't exist. Already exists, when they try to create the same thing twice. Okay, those feel a lot like HTTP's four hundreds. Pretty close. Then two about identity. Unauthenticated means, I don't know who you are. Permission denied means, I know exactly who you are, and the answer's no. Ha. The bouncer who can't read your ID, versus the one who read it twice.
1:47 I love that. Then unavailable, meaning the server can't take this right now. And internal, meaning something broke inside that should never break. Oh, here's a detail I didn't expect from the official status codes page. It lists seven codes the gRPC library itself never generates. Only application code does. Invalid argument and not found are two of them. Oh, so if a dashboard shows not found, somebody's handler chose it on purpose. Every time. Which means unknown, like our coupon crash, is very often what you get when nobody chose anything.
2:22 And choosing matters most for what the caller does next. The official docs spell out a rule for three codes that sound alike: unavailable, aborted, and failed precondition. Okay, let's unpack this. Start with unavailable. Unavailable means retry just this one call, with backoff, so you wait a bit longer between each try. Aborted means retry at a higher level. Higher level how? Let's say a client reads an order and changes the address, but a support agent saves an edit first. The server answers aborted, because saving that stale copy would wipe out the agent's change. Oh, so the whole loop starts over.
3:01 Read it fresh, change it again, then save. What about failed precondition? Don't retry at all, not until something in the system gets fixed. Hmm, that's the one I'd mix up with invalid argument. Both sound like, your request was wrong. People assume that, and the docs draw the line by state. Invalid argument is wrong no matter what. For example, a refund of negative 5 dollars. Failed precondition depends on the current state, like refunding an order that hasn't been paid yet. so that exact refund could work next week, once the order's paid. And internal?
3:37 Reserved for serious errors, where something the system relies on is broken. A bug, basically, not a bad request. So now the caller has real instructions. Unavailable, try again shortly. Aborted, start the edit over. Failed precondition, stop until something changes. Now, with that rulebook, how do I actually send a code from the coupon handler? In Python, your handler gets a context object. You call context dot abort with a code and a message. Say, not found, and coupon spring 10 doesn't exist.
4:08 That ends the call right there. And in Java? I remember some observer object. Yep, the response observer, the object your Java handler pushes its reply into. You call on error on it, with a status turned into an exception. Same code, same message. Then on my side as the caller, Python raises an RPC error, and I ask it for the code and the details. Java throws a status runtime exception carrying both. And that message is for whoever reads the logs, not for the customer's screen. Wait, back to the crash, though.
4:43 Python stuffed my exception's text into the details. Does Java do that too? No. Java also sends unknown, but with a generic message, application error processing RPC. The exception stays on the server. Huh. So Python's version is chattier than I'd like. Imagine that exception text had a file path or a customer's email in it. The caller just got it. Yeah. Python says too much, Java says nothing, and neither one gives the caller an instruction. So catch exceptions yourself and decide what leaves the building, rather than trusting the default.
5:18 And there's one clean place to do that, coming up. Before that, though, there's a case where a code and a sentence just run out. Take a checkout form that sends three bad fields, and the server only complains about the first one. Ugh, we've all filled out that form. Fix one, resubmit, find the next. GRPC has a richer error model for this. Next to the code and the message, a server can attach detail messages, plain protobuf messages from a standard set. One's called bad request, and it lists every invalid field with what's wrong.
5:53 Nice. So the checkout client gets one error back and can highlight all three fields at once. Anything for the retry case? Retry info, where the server names the minimum wait before trying again, so the client isn't just guessing. And a failed call has no response message. So where does all of that ride? In the trailers, under one special key whose name ends in the word bin. Hold onto that. Okay. And can every client read it? Python and Java can, plus a few others. The official error guide lists Node and gRPC web as still waiting on it, so check what your callers run.
6:28 And the key itself leads straight into metadata. And that key is a piece of metadata. Each call can also carry key value pairs describing the call, rather than the business data inside it. So, basically HTTP headers? Basically, yeah. It literally travels in the HTTP two headers. The client sends its metadata up front. The server can answer with headers before its first reply, and trailers after its last one. Only the server sends trailers. And the trailers are where the status rides, too. So what actually goes in there?
7:01 For example, an auth token, a request ID, a trace ID. And three rules on the keys. Upper or lower case doesn't matter. Anything starting with grpc dash is reserved for gRPC itself. And a key ending in dash bin holds a binary value, which the library base64 encodes for you. And there's the bin I told you to hold onto. So the error details are a whole protobuf riding in a trailer. Exactly, and base64 is what lets those raw bytes travel as header text. Then how do I decide, metadata or a field in my request message?
7:38 I mean, my rule is, if only the business logic cares, it's a field. If every method needs it, or a proxy has to read it without decoding your message, it's metadata. The coupon code is a field. The auth token is metadata. Got it. Letter versus envelope, basically: the coupon's inside, the token's on the outside. And in Python, that's the metadata argument on the stub call, just a list of pairs. The server reads it back with context dot invocation metadata. That leaves the token on every call, and someone has to check it.
8:11 And that someone is the problem. Our orders service has 20 methods. Does every single one read the token, check it, and log the call? Please, no. We've all seen the one method that forgot, and that one becomes the security incident. Which is what interceptors are for. Middleware for gRPC calls, like Django middleware or a servlet filter: code that wraps every call, written once. Does that cover calls going out too, or just coming in? Both, with different APIs. A server interceptor runs before your handler.
8:44 It sees which method was called and the incoming metadata, and it can reject the call, say with unauthenticated, before the handler ever runs. Nice. So the handlers just get to assume the caller's been checked. In Python that's a class you subclass? Yep. In Python you subclass server interceptor and pass a list of them when you create the server. In Java you implement the interface and register it on the builder. Okay. And the client side? A client interceptor wraps every outgoing call. Stamp a fresh ID on each one, time it, log it.
9:19 In Python, grpc dot intercept channel wraps your channel. Could the token go on that way too? You could, but the official interceptors guide points you to a dedicated API, call credentials, and says it's better suited. That's really its own topic, security. The result is one gate on the way in, and one stamp on the way out. So with the gate and the stamp in place, what else belongs in there? The guide's list includes logging, metrics, caching, and policy checks. Logging and metrics are the usual starting point.
9:52 One interceptor records the method, how long it took, and the final status code, for every call. The gRPC status code, mind you. The HTTP one says 200 even when the call failed. Right. Then tracing. Consider a checkout that crosses five services. The trace ID arrives in metadata, the inbound wrapper picks it up, and the outbound one copies it onto every downstream call. Oh, wow, and then one customer's checkout shows up as a single timeline across all five. Do I have to write that myself? Nope. OpenTelemetry's gRPC instrumentation for Python is literally a pair of interceptors, one for each side. Nice.
10:30 Then here's the one I'd add first, given that coupon mess. An error-mapping interceptor. It catches exceptions from every handler, turns a coupon-missing error into not found, and logs the full stack trace on the server. Is that a simple try block in Python? Almost. The interceptor swaps in a stand-in handler, and the stand-in calls the real one inside a try. Streaming methods just need their own stand-in. Got it. And anything the mapper doesn't recognize? That's a bug, so it goes out as internal, with a safe message.
11:02 Honestly, I've shipped a gRPC service without one, and our callers saw a lot of unknowns. Ouch. So now the exception text stops leaking, and unknown stops being the default. That's one wrapper doing the work of 20 separate fixes. Once you've stacked four or five of these wrappers, though, their order starts to matter. The guide's own example is caching and logging. How does order change anything there? Picture a client with a caching interceptor answering repeat lookups without touching the network.
11:35 Put logging between the cache and the network, and it only logs calls that really went out. Put it between your code and the cache, and it logs every lookup, cache hits included. Huh. So both are right. They just answer different questions. And I've got a made-up team for you, but a realistic one. Imagine their auth interceptor runs first, and logging runs after it. One night, someone hammers them with a flood of bad tokens. Oh, no. Auth rejects every one before logging ever sees it. Right, so the logs look quiet.
12:09 The attack is invisible in exactly the place they'd look for it. That's a nightmare to spot. So logging goes outside auth, to catch the rejects too. Yeah, for that question. And teams that use both languages get bitten here. In Python, interceptors run in the order you list them. In Java, the ones you add on the server builder run in reverse order of adding. Wait, really? Really. Port the list from Python to Java unchanged, and it flips. Java's own docs say so. Then I'd write down the order I want, outermost first, and test it, instead of trusting the list.
12:44 So, before someone ships their next gRPC service, what's the short version? Pick the code on purpose. It tells the caller whether to fix the request, retry the call, start the whole sequence over, or stop. When a sentence isn't enough, attach details. And anything that travels with the call, like the token or the tracing info, rides in metadata, next to the message. Then write auth, logging, tracing, and error mapping once, as interceptors, in an order you chose. And the coupon crash becomes a not found the caller can actually act on.
13:18 Coming up next, deadlines, and what happens when a call doesn't fail at all. It just never comes back in time. Thanks for listening to Learning Podcasts.