A Scribe keeps the operational paper trail: the decisions, assumptions, and boundaries that help people trace failures and understand how a system is meant to behave. Hidden assumptions—such as believing a payment API is always fast—leave the next developer and the business guessing when things go wrong. section 10.4.1
For an external payment call, make the system’s contract visible:
- Record operational boundaries such as timeouts, retry policy, and a fallback plan. section 10.4.2
- Keep the resilience policy clear in the code, so developers can see how failures are handled without digging through hidden logic. section 10.4.2
- Provide traceability: if payment attempts fail, route the order to an asynchronous queue with a pending-payment status. section 10.4.2
Listing 10.2 The Resilient Way
import requests
import uuid
import os
from enum import Enum
import pybreaker
from tenacity import retry, stop_after_attempt, wait_exponential
# 1. Define the Circuit Breaker:
db_breaker = pybreaker.CircuitBreaker( fail_max=5, reset_timeout=30 ) #A
# The Domain Layer: Define our system's vocabulary
class OrderStatus(Enum): #B
PENDING_PAYMENT = "PENDING_PAYMENT"
PAID = "PAID"
FAILED = "FAILED"
# The Infrastructure Layer
class PaymentService:
def __init__(self, base_url): #Accept the configuration
self.base_url = base_url
# Wrap the call in both the Circuit Breaker and the Retry decorator
@db_breaker
@retry(stop=stop_after_attempt(3), #C
wait=wait_exponential(multiplier=1, min=2, max=10),
reraise=True
)
def charge_credit_card(self, amount, order_id, idempotency_key): #D
print(f"Attempting to charge card for order {order_id}...")
response = requests.post(f"{self.base_url}/charge", #E
json={"amount": amount, "order_id": order_id},
headers = {"Idempotency-Key": idempotency_key},
timeout=(2, 8) #F
)
response.raise_for_status() #G
return response.json()
# The Business Layer: Execute with a Fallback "Plan B"
def process_checkout(user_cart): #H
try:
api_url = os.getenv("PAYMENT_API_URL", "https://api.flakypayments.com") #I
# 1. The Happy Path (with retries built in)
payment_service = PaymentService(base_url=api_url)
order_key = str(uuid.uuid4()) #J
payment_service.charge_credit_card(
user_cart.total_amount,
user_cart.order_id,
order_key
)
print("Success! Order complete.")
except requests.exceptions.RequestException: #K
# 2. The Fallback Plan B
print("FALLBACK: FlakyPayments API offline.")
print("Routing order to background queue.")
send_to_async_queue({ #L
"order_id": user_cart.order_id,
"amount": user_cart.total_amount,
"status": OrderStatus.PENDING_PAYMENT.value
})See the resilient checkout code, where retry and circuit-breaker policies, order status, and the payment service make the operational contract more explicit. section 10.4.2
