How to Stop Receiving Requests Until Ready in Python
A mock server that refuses requests until a readiness gate is passed, simulating fail-stop behavior for production reliability.
Python code
40 linesimport random
import time
class MockServer:
def __init__(self):
self.ready = False
self.requests_received = 0
def readiness_check(self):
"""Simulates a readiness probe. Returns True only when ready."""
if not self.ready:
return False
return True
def receive_request(self):
"""Simulates receiving a request. Fails when not ready."""
if not self.readiness_check():
raise ConnectionRefusedError("Server not ready to accept requests")
self.requests_received += 1
return f"Request #{self.requests_received} processed"
def set_ready(self):
"""Mark server as ready, simulating a startup or recovery."""
self.ready = True
if __name__ == "__main__":
server = MockServer()
# Attempt to receive a request before readiness
try:
server.receive_request()
except ConnectionRefusedError as e:
print(e)
# Simulate delayed startup
server.set_ready()
print(server.receive_request())
print(server.receive_request())
Output
Server not ready to accept requests
Request #1 processed
Request #2 processed
How it works
This pattern simulates a readiness gate: readiness_check() returns False until set_ready() flips the flag. When not ready, receive_request() raises ConnectionRefusedError, preventing any work from being accepted. This mirrors real-world fail-stop behavior where a service rejects traffic until it has completed startup or recovery. The ready boolean acts as a simple state machine, and the exception provides clear feedback to the caller.
Common mistakes
- Forgetting to reset the ready flag after a health check failure
- Using a hard-coded sleep instead of an explicit state flag
- Catching the exception too broadly and swallowing readiness errors
Variations
- Use a circuit breaker pattern with three states (closed, open, half-open) to handle dependency failures
- Implement a thread-safe readiness flag with a lock or using `threading.Event`
Real-world use cases
- Kubernetes readiness probes returning 503 until the app has finished loading caches or DB connections.
- API gateways refusing traffic to a service that is still warming up its connection pools.
- Background workers that hold a record of the last successful heartbeat and reject work when stale.
Sponsored
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.