Middle+
How to implement the Waiter pattern for an API?
sobes.tech AI
Answer from AI
The Waiter pattern for API is implemented by periodically sending requests to the service until a certain condition is met or a timeout occurs.
Main components:
- Target Request: The request that is executed and whose result is checked.
- Completion Condition: A logical expression that determines when the wait should be stopped. This could be a specific response status (e.g., 200 OK), a value in the response body, the presence or absence of a resource, etc.
- Polling Interval: The time between consecutive target requests.
- Timeout: The maximum time during which the Waiter will perform requests before terminating with an error.
Example implementation in Python using the requests library:
import time
import requests
def wait_for_resource(url, expected_status=200, interval=5, timeout=60):
"""
Implementation of the Waiter pattern for API.
Args:
url (str): URL of the resource to wait for.
expected_status (int): Expected HTTP response status.
interval (int): Waiting interval between requests in seconds.
timeout (int): Maximum waiting time in seconds.
Raises:
TimeoutError: If the timeout expires before reaching the expected state.
Exception: If an error occurs during the request.
"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
response = requests.get(url)
if response.status_code == expected_status:
print(f"Resource at {url} is available with expected status {expected_status}.")
return response
else:
print(f"Resource at {url} is not available. Current status: {response.status_code}. Waiting...")
except requests.exceptions.RequestException as e:
print(f"Error requesting {url}: {e}. Waiting...")
time.sleep(interval)
raise TimeoutError(f"Timeout waiting for resource {url}.")
# Usage example
# try:
# wait_for_resource("http://example.com/some_resource", expected_status=200, interval=10, timeout=120)
# except (TimeoutError, Exception) as e:
# print(f"Waiter error: {e}")
Variations of implementation:
- Wait based on response body: Checking for a specific value or structure in the response JSON/XML body.
- Exponential Backoff: Increasing the wait interval between attempts to reduce load on the service during frequent timeouts.
- Parameterized Waiter: Ability to pass parameters to the target request.
- Conditional Wait: Using more complex conditions, such as a combination of status and response content.
The Waiter pattern is useful for waiting for asynchronous operations to complete, service readiness after deployment, or the appearance of data generated by other processes.