Understanding gRPC Deadlines and timeouts
masterDeadlines in grpclib function as propagated timeouts. They allow a timeout constraint to be passed through a chain of services to ensure the entire call chain respects the initial time limit.
The Deadline Lifecycle:
- A service receives a request with a
grpc-timeoutin the metadata (e.g.,100mfor 100 milliseconds). - The service converts this into an absolute deadline:
deadline = time.monotonic() + grpc_timeout. - When making an outgoing request to another service, the service calculates the remaining time:
new_timeout = max(deadline - time.monotonic(), 0). - The outgoing request is sent with the new
grpc-timeoutmetadata.
This mechanism allows for simultaneous cancellation of an entire call chain, even in the event of network failures or broken connections.
# Example of converting timeout to deadline and calculating remaining time
import time
# 1. Convert incoming timeout to absolute deadline
grpc_timeout = 0.1 # 100ms
deadline = time.monotonic() + grpc_timeout
# 2. Simulate work
time.sleep(0.02) # 20ms work
# 3. Calculate remaining timeout for the next service
new_timeout = max(deadline - time.monotonic(), 0) # Result: ~0.08s (80ms)