Ch.9: gRPC Deadlines, Timeouts, and Cancellation
Outline
Transcript
0:00 Picture a checkout service. It calls an inventory service over gRPC, and inventory runs a database query. Tonight that query is stuck behind a lock. It doesn't fail. It just never comes back. And nobody put a limit on how long any of those calls can wait? Nobody. So inventory waits on the database, checkout waits on inventory, and the customer gives up after 5 seconds and closes the tab. But every service is still holding a thread for that customer. Every one. More checkouts hit the same lock, the thread pools fill up, and now healthy requests are queuing behind stuck ones.
0:35 Nothing errored, so no error alert fires. Made-up example, but a very believable outage. Oof. We've all stared at a green dashboard during one of those. So what's the fix, a timeout on every call? Partly. You want a limit, but one that travels. So that's the plan: how to set it, how it travels through every hop, and how a server stops working on a request nobody's waiting for. Then checkout fails fast instead of freezing. So start with that missing limit. gRPC really doesn't have a default timeout?
1:08 No. The deadlines guide says it plainly, and links to all of these docs are in the description. By default, gRPC sets no deadline, so a client can end up waiting effectively forever. Huh. I honestly assumed there was some sane default buried in there. And deadline versus timeout, is that the same thing? Quick terms, because the docs use both. A timeout is how long you'll wait, like 2 seconds. A deadline is the moment you stop waiting, 2 seconds from now. You hand gRPC a timeout, and it turns that into a deadline.
1:41 Okay. So in Python, it's the timeout argument on the call, in seconds? Right. And in Java, you set it on the stub, with a method called with deadline after. For example, 2 seconds. If the server hasn't answered by then, the client gives up. Every gRPC call ends with a status code, and this one ends with deadline exceeded. Got it. But where does two come from? Teams I've worked with just copied whatever the last service used. Yeah, same. The guide basically says start with an educated guess, network time plus server time, and check it with load testing.
2:16 And the gRPC blog adds a trick. Make it a flag, so when a bad release slows things down, you raise it without a rebuild. So, a number on purpose, not a copy-paste. Now, once you know you need limits, it's tempting to add one everywhere. Let's say our checkout team does that, and each service picks its own. Checkout gives inventory 2 seconds, inventory gives its database call five, and the database query has a 10-second timeout of its own. And the inventory owner would push back. They'd say, my query takes 4 seconds on a bad night, so five is generous, not sloppy.
2:54 Sure, and on their own they're right. But follow the stuck query. At the 2-second mark, checkout gives up and tells the customer sorry. Inventory got that 2 seconds too, but nothing in its code uses it. It keeps waiting on the database until five. Ugh. And the query itself runs until 10. So for 8 seconds, the bottom of the chain is working for someone who already left. Right. Every hop runs its own stopwatch, and none of them checks the caller's. Yeah, I've seen that kind of config in code review and approved it.
3:27 Every number looked reasonable on its own. And that's the catch, nobody reviews the whole chain at once. What you need instead is one budget for the whole request, set at the edge. So that one budget from the edge. How does it actually travel? Does each hop just get a copy of it? Not copied. It shrinks. The guide walks through its own example. Imagine a request that starts at one p.m. exactly and has to finish within 2 seconds. First it hits a user server, which spends half a second on its own work, then calls a billing server.
4:03 That call goes out with 1 and a half seconds, not two. Wait, so billing never sees the original clock time at all? Just the leftover? Exactly. It never travels as a clock time. It travels as time remaining, in a header called grpc timeout. Why not just send the deadline itself, like, finish by 2 seconds past one? Because the two machines' clocks might not agree. Take a case where billing's clock runs a second ahead. It would think a second of the budget was already gone, and give up early. So the sender subtracts what's already been spent and sends what's left, and the receiver turns it back into its own deadline.
4:42 Ah, nice. So each machine only trusts its own clock, and the header just carries the countdown. So the countdown arrives at the server. Does the server have to do anything to pass it along? Depends on the language. Per the docs, Java and Go both propagate the incoming deadline to outgoing calls by default. In Go, as long as you pass the incoming context down. C++ needs it switched on. And Python? Because our inventory service is Python. Python doesn't do it for you. So inventory's next gRPC call, say to a pricing service, goes out with no deadline at all.
5:17 Oh, so we're back to waiting forever, one hop down. Unless I hand it the leftover time myself. Exactly. Every Python handler gets a context object, and on that outgoing call you set timeout to context dot time remaining. And if no deadline came in, that's just Python's None, which means no limit, so it's safe to pass either way. The same leftover time works as the database query's timeout, too, so inventory quits when checkout's budget is spent, not at five. Okay. And Java's just automatic, nothing to watch out for? One thing. Java keeps the deadline in, kind of, a gRPC context that lives on the request's thread.
5:54 Hand the work to your own thread pool, and the context stays behind. Oh, no. So that pool fires off its downstream call with no deadline, and nobody notices until the next stuck query. Right. The fix is to wrap the task, or the executor, with the current context, so the countdown rides along to the new thread instead of staying behind. Now the budget's on every hop. Say the 2 seconds run out. What happens on each side? The client stops waiting right away and gets deadline exceeded. On the server, gRPC cancels that call.
6:28 So the handler finally hears it and stops? No. The cancellation guide says the library generally can't interrupt your handler. The call is marked cancelled, but your code keeps running until it checks. Wait, really? Really. Your handler can finish an expensive query and build a whole response for a caller that's already gone. That's a nightmare for the stuck checkout. So do I just check myself before the expensive part? Pretty much. The deadlines blog says check before the heavy lifting, and return early if the time's gone.
6:59 And in a long loop, for example inventory pricing 10,000 items, check every so often. In Python that's context dot is active. In Java you ask the gRPC context whether it's been cancelled. Both are cheap yes or no checks. Okay. But what if my code is stuck waiting on something and can't check? Python's context has add callback. You register a function that runs the moment the call ends, and it can cancel whatever you're stuck on, like a downstream call you started in the background. Java has the same idea, a cancellation listener on the context.
7:33 So now your handler can actually let go. So far it's the clock doing the cancelling. Can the caller cancel on purpose? Sure. For example, a shopper walks away mid-checkout. Checkout notices and cancels its call to inventory, and the server gets the same signal a deadline would send. Does the client get to say why, though? Sort of. Some languages let you pass a reason to cancel, but it stays in the client's own exception or log. The server just learns that the call was cancelled. Huh, okay. And if checkout's call gets cancelled, does inventory's call to the pricing service die too?
8:12 In Java, yes, and in Go too. They automatically cancel the handler's outgoing calls. Let me guess. Python makes you do it. Yep. Keep a handle on that downstream call, and cancel it when your own call ends. So Python's the same story twice. Forward what's left of the budget, and pass the cancel along yourself, rather than trusting it to happen. Now back to the client for one more trap. When you get deadline exceeded, what do you assume happened? Honestly? That it didn't happen. I think we all read timed out as nothing happened.
8:46 That's the trap. The status codes page says, for operations that change state, deadline exceeded may be returned even if the operation completed. The reply just arrived too late. Oh, wow. So the client and the server can disagree about the same call. Right, and the gRPC team's deadlines post spells it out. Each side decides success on its own. Take a checkout calling a payment service. The charge goes through, the reply is late, and checkout sees deadline exceeded. And if checkout just retries, the customer pays twice.
9:20 Yup. So for anything that changes state, I mean, treat deadline exceeded as outcome unknown. Yeah. Then I'd make the charge safe to retry. Send a request ID with it, and have the payment service remember the IDs it already handled. That's not a gRPC feature, it's just good practice. I love that. Same ID, same result, one charge, instead of a refund ticket. So, before someone ships their next gRPC client, what's the short version? Set one deadline where the request comes in, because gRPC won't set one for you.
9:53 Let it travel. Java mostly carries it, Python needs time remaining passed along by hand, and either way it shrinks at every hop. Check it before expensive work, and stop when the call's cancelled, because nobody will stop your handler for you. And when a write comes back deadline exceeded, assume it might have happened. That stuck checkout? It fails fast, the customer sees an answer, and the threads go free. Coming up next, securing the call, and proving who's actually on the other end. Good, because a deadline won't help much if the wrong service answers.
10:26 Thanks for listening to Learning Podcasts.