Before applying the Ambassador pattern, each service implements its own retry logic, causing code duplication and inconsistent behavior. After applying the pattern, the main service calls the Ambassador service, which centralizes retries and error handling, simplifying the main service code.
### Before Ambassador pattern (direct call with duplicated retry logic)
import requests
def call_external_api():
for _ in range(3):
try:
response = requests.get('https://external.api/data')
if response.status_code == 200:
return response.json()
except requests.exceptions.RequestException:
pass
raise Exception('Failed after retries')
### After Ambassador pattern (service calls ambassador, ambassador handles retries)
# In Service A
import requests
def call_ambassador():
response = requests.get('http://localhost:9000/api/data')
response.raise_for_status()
return response.json()
# In Ambassador service
import requests
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data')
def proxy_data():
for _ in range(3):
try:
response = requests.get('https://external.api/data')
if response.status_code == 200:
return jsonify(response.json())
except requests.exceptions.RequestException:
pass
return jsonify({'error': 'Failed after retries'}), 500
if __name__ == '__main__':
app.run(port=9000)