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.

Easy Python 3.9+ Aug 9, 2026 Reliability & rate limiting 13 views 0 copies

Python code

40 lines
Python 3.9+
import 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

stdout
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

  1. Use a circuit breaker pattern with three states (closed, open, half-open) to handle dependency failures
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Reliability & rate limiting

Related tutorials and quizzes for this topic.