Since Verdalia extracted notification-service, two programs have to talk to each other over the network. In the previous lesson a simple HTTP request was enough to demonstrate it, and at the end we saw the first error a function would never have produced. In this lesson you will study the forms of communication between components, how a REST API is designed, and which precautions the network demands: timeouts, retries, idempotency, and circuit breakers. With them we will keep the promise from Module 2: that retrying a charge does not charge twice.
Forms of Communication Between Components
Any communication between two components can be described by answering three questions:
| Question | Options | Main difference |
|---|---|---|
| Where are they? | In the same process, or in different processes joined by the network | The network adds waiting and failures |
| Does the caller wait? | Synchronous: it waits for the response. Asynchronous: it carries on with its work | Coupling in time |
| What is exchanged? | Request and response, or messages deposited with an intermediary | Whether both must be available at the same time |
The most common combinations are three:
| Combination | Example at Verdalia | Characteristic |
|---|---|---|
| In-process and synchronous | OrderService calls calculate_shipping_cost |
Fast and reliable |
| Over the network, synchronous, request-response | The store calls PagoRaíz and notification-service |
The caller waits, and depends on the other being available |
| Over the network, asynchronous, with messages | None yet | The sender does not wait, and the receiver may be unavailable at that moment |
This lesson deals with the second. The third is the subject of the next lesson.
REST APIs: Resources, Verbs, and Status Codes
An API is the interface a component offers to other programs: what can be asked of it, with what data, and what it answers. It is the equivalent, between processes, of a module's public interface.
REST is the most widespread style for designing APIs over HTTP. It rests on four ideas.
1. Resources. The API exposes things, not actions. Each resource has an address: /v1/notifications is the collection and /v1/notifications/NOT-1 is one specific notification.
2. Verbs. The action is indicated by the HTTP method:
| Verb | Use | Modifies data? | Idempotent? |
|---|---|---|---|
GET |
Query | No | Yes |
POST |
Create a resource or start an operation | Yes | No |
PUT |
Replace a whole resource | Yes | Yes |
PATCH |
Modify part of a resource | Yes | It depends |
DELETE |
Delete | Yes | Yes |
An operation is idempotent when repeating it produces the same effect as doing it once. We will come back to this, because POST, the verb for charges and emails, is not.
3. Status codes. The response indicates the result with a number:
| Code | Meaning | Who must act |
|---|---|---|
| 200 | OK | Nobody |
| 201 | Resource created | Nobody |
| 202 | Accepted: it will be processed later | Nobody |
| 400 | Malformed request | The caller: fix it, do not repeat it |
| 404 | The resource does not exist | The caller |
| 409 | Conflict with the current state | The caller |
| 429 | Too many requests | The caller: wait |
| 500 | Internal server error | The server |
| 503 | Service temporarily unavailable | The server; the caller may retry |
The general rule: 4xx codes indicate an error by the caller, and repeating the request unchanged is useless. 5xx codes indicate a server problem, which may be temporary.
4. Contract and versions. The API is a promise. Whoever publishes it commits to maintaining it, which is why it should be documented; the most widespread format for doing so is OpenAPI. Changes are classified like this:
| Kind of change | Examples | What to do |
|---|---|---|
| Compatible | Adding an optional field or a new resource | Release it in the same version |
| Incompatible | Removing or renaming a field, changing a type | Release a new version, /v2/, and keep the previous one for a while |
The Notification Service API
The entry point from the previous lesson was POST /send-confirmation. It worked, but it had four defects: the name is an action rather than a resource, it has no version, it does not check the data it receives, and it does not allow checking afterwards what happened. This is the revised version:
| Operation | Verb and route | Responses |
|---|---|---|
| Create a notification | POST /v1/notifications |
201 created; 200 if the key had already been received; 400 if data is missing |
| Get a notification | GET /v1/notifications/<id> |
200; 404 if it does not exist |
| Check the service | GET /health |
200 |
# notification-service/app.py
from flask import Flask, jsonify, request
app = Flask(__name__)
notifications = {} # id -> notification. In production, its own data store
seen_keys = {} # idempotency key -> notification id
FIELDS = ("order_id", "customer_email", "total", "shipping_cost")
@app.route("/v1/notifications", methods=["POST"])
def create_notification():
data = request.get_json(silent=True) or {}
missing = [field for field in FIELDS if field not in data]
if missing:
return jsonify({"error": "missing_fields", "fields": missing}), 400
key = request.headers.get("Idempotency-Key")
if key in seen_keys:
print(f"[service] Duplicate key: {key}. Not sending again")
return jsonify(notifications[seen_keys[key]]), 200
send_email(data["customer_email"], f"Order {data['order_id']} confirmed")
notification = {
"id": f"NOT-{len(notifications) + 1}",
"type": "order_confirmation",
"order_id": data["order_id"],
"status": "sent",
}
notifications[notification["id"]] = notification
if key:
seen_keys[key] = notification["id"]
return jsonify(notification), 201
@app.route("/v1/notifications/<notification_id>")
def get_notification(notification_id):
if notification_id not in notifications:
return jsonify({"error": "not_found"}), 404
return jsonify(notifications[notification_id])Explanation:
send_emailis the function from the previous lesson, which here prints[service] Email to ....- The function starts by checking the data. If any is missing, it responds 400 and says which, so that the caller can fix it.
Idempotency-Keyis a request header. If the service has already handled a request with that key, it returns the notification it created back then and does not send another email. We will explain it in detail later on.- The two dictionaries keep the data in memory so that the example can be run. The real service uses its own data store, which survives restarts.
- The
/healthroute, not shown, responds 200 with{"status": "ok"}. It allows checking from outside that the service is up.
Two test requests, with their real responses:
POST /v1/notifications with the body {"order_id": 7}
400 {"error":"missing_fields","fields":["customer_email","total","shipping_cost"]}
GET /v1/notifications/NOT-9
404 {"error":"not_found"}Alternatives to REST: gRPC and GraphQL
| Aspect | REST | gRPC | GraphQL |
|---|---|---|---|
| Central idea | Resources and HTTP verbs | Remote procedure calls | Queries tailored by the client |
| Format | JSON, readable | Binary, compact | JSON |
| Contract | Optional, with OpenAPI | Mandatory, in definition files | Mandatory, in a schema |
| Strength | Simplicity and universality | Performance between internal services | The client asks for exactly the fields it needs |
| Weakness | Several requests to compose one screen | Hard to use from a browser and to debug by hand | Complexity on the server |
| Fits | Public APIs and most cases | Many internal services with heavy traffic | Applications with very varied screens |
Verdalia uses REST: it has a single internal service and the team already knows HTTP.
What Changes When There Is a Network
Latency
Every network call adds waiting. Between two processes on the same machine it is tenths of a millisecond; between data centers, tens. The problem appears when chaining them: a page that makes 50 calls of 20 milliseconds, one after another, spends a second just communicating.
Partial Failures
In a single program, either everything works or nothing does. In a distributed system, one part can fail while the others keep working. And the caller does not always know what happened:
sequenceDiagram
participant T as Store
participant S as Service
Note over T,S: Case 1 - the request is lost
T-xS: Request
Note over T,S: Case 2 - the service fails before doing the work
T->>S: Request
Note over T,S: Case 3 - the work is done and the response is lost
T->>S: Request
S->>S: Does the work
S--xT: Response
In all three cases, the store observes the same thing: no response arrives. It cannot tell whether the work was done. If the work was a charge, the difference matters a great deal.
Timeouts and Retries
Timeouts
A timeout is the maximum time the caller is willing to wait. Without one, a slow service holds its caller indefinitely, which is what happened on November 26. It is worth distinguishing two:
| Timeout | What it limits | Value at Verdalia |
|---|---|---|
| Connection | Establishing the connection | 1 second |
| Read | Receiving the response | 3 seconds |
To choose the value, you start from measurements: a limit somewhat above the service's 99th percentile under normal conditions.
Retries With Exponential Backoff
Many network failures are transient, and repeating the request resolves them. But retrying immediately and without limit makes things worse: a saturated service receives even more requests. The rules are:
- Retry only what can fix itself. Connection errors, expired timeouts, and 5xx codes. Never a 4xx.
- Limit the number of attempts.
- Wait longer each time. With exponential backoff, the wait doubles on every attempt: 0.5 seconds, 1, 2, 4.
- Add jitter. That way, clients that failed at the same time do not all retry at the same instant.
- Retry only idempotent operations. It is the most important rule, and the one that leads us to the next section.
Idempotency and Idempotency Keys
The Problem
In Module 2 we added RetryingGateway and warned about its risk. Now we can describe it precisely: it is case 3 of the previous diagram. PagoRaíz charges, the response is lost, the store retries, and the customer pays twice.
The Solution
An idempotency key is a unique identifier that the caller assigns to each operation and sends with the request. The server remembers the keys it has handled. If it receives a repeated key, it does not repeat the work: it returns the result it obtained the first time.
sequenceDiagram
participant T as Store
participant P as PagoRaíz
T->>P: Charge €49.95 with key ORD-1042
P->>P: Charges and stores the result with the key
P--xT: The response is lost
T->>P: Retry with the same key ORD-1042
P->>P: Known key, does not charge again
P-->>T: Charge accepted, transaction PR-778201
Three conditions for it to work:
- The key is generated by the caller, before the first attempt, and is the same on every retry.
- The key identifies the business operation, not the request. The reference
ORD-1042is suitable: an order is charged only once. - The server stores the key together with the result, for long enough.
In the PagoRaíz adapter, the change is one line. The official library accepts the key as a parameter:
# verdalia/payments/pagoraiz_gateway.py (excerpt)
response = self._client.create_charge(
amount_cents=round(amount * 100),
currency="EUR",
description=reference,
idempotency_key=reference, # "ORD-1042": the same on every retry
)With this line, RetryingGateway becomes safe. What PagoRaíz does internally is the same thing our notification service does with the seen_keys dictionary.
A warning: everything related to charges has financial and legal implications. In a real system, the handling of retries and doubtful charges must be reviewed against the gateway's documentation and with the people responsible for finance and regulatory compliance.
The Complete Client
The HttpNotifier adapter brings the three techniques together:
# verdalia/notifications/http_notifier.py
import random
import time
import requests
from verdalia.orders.ports import Notifier
class ServiceUnavailable(Exception):
"""The service has not responded after exhausting the attempts."""
class HttpNotifier(Notifier):
def __init__(self, service_url, max_attempts=3, initial_wait=0.5):
self._url = f"{service_url}/v1/notifications"
self._max_attempts = max_attempts
self._initial_wait = initial_wait
def send_confirmation(self, order):
headers = {"Idempotency-Key": f"confirmation-ORD-{order.id}"}
body = {
"order_id": order.id,
"customer_email": order.customer_email,
"total": order.total,
"shipping_cost": order.shipping_cost,
}
for attempt in range(1, self._max_attempts + 1):
try:
response = requests.post(
self._url, json=body, headers=headers, timeout=(1, 3)
)
if response.status_code < 500:
response.raise_for_status()
print(f"[store] Attempt {attempt}: response {response.status_code}")
return response.json()["id"]
print(f"[store] Attempt {attempt}: error {response.status_code}")
except (requests.ConnectionError, requests.Timeout) as error:
print(f"[store] Attempt {attempt}: {type(error).__name__}")
if attempt < self._max_attempts:
wait = self._initial_wait * 2 ** (attempt - 1)
wait += random.uniform(0, 0.1)
print(f"[store] Waiting {wait:.2f} s before retrying")
time.sleep(wait)
raise ServiceUnavailable("notification-service")For the demonstration, we made the service take 5 seconds to answer the first request, after having sent the email. It is case 3. Output from the store:
[store] Attempt 1: ReadTimeout [store] Waiting 0.59 s before retrying [store] Attempt 2: response 200
Output from the service:
[service] Email to [email protected]: Order 1042 confirmed [service] Duplicate key: confirmation-ORD-1042. Not sending again
Explanation:
- The key is built from the order. Every attempt sends the same one.
timeout=(1, 3)sets the two limits: 1 second to connect and 3 to receive the response.- Responses with a code below 500 are not retried. If it is a 4xx,
raise_for_status()raises an exception: the error is the store's, and repeating will not fix it. - Connection errors, expired timeouts, and 5xx codes lead to the next attempt, after a wait that doubles.
2 ** (attempt - 1)is 1, 2, 4... random.uniform(0, 0.1)adds the jitter.- The customer received a single email, even though the store made two requests. The second attempt got a 200, not a 201, because nothing new was created.
The Cost of Retrying
Retries happen while the customer waits. In the worst case, three attempts of up to 4 seconds, between connection and read, plus the waits of 0.5 and 1 second, add up to 13.5 seconds. That is why Verdalia configured this adapter with 2 attempts. Retrying inside a synchronous request has a limit, and it is one of the reasons to take this work out of the request, as we will do in the next lesson.
Circuit Breakers
When a service has been down for a while, continuing to call it only serves to make customers wait. A circuit breaker watches the calls and, after several consecutive failures, stops attempting them for a time.
flowchart LR
closed["Closed: calls go through"] -->|"3 consecutive failures"| opened["Open: calls are rejected without being attempted"]
opened -->|"30 seconds pass"| half_open["Half-open: one test call is allowed"]
half_open -->|"the test works"| closed
half_open -->|"the test fails"| opened
import time
class CircuitOpen(Exception):
"""The circuit breaker is open: the call is not even attempted."""
class CircuitBreaker:
def __init__(self, max_failures=3, open_seconds=30, clock=time.monotonic):
self._max_failures = max_failures
self._open_seconds = open_seconds
self._clock = clock
self._failures = 0
self._open_since = None
@property
def state(self):
if self._open_since is None:
return "closed"
if self._clock() - self._open_since >= self._open_seconds:
return "half_open"
return "open"
def call(self, func, *args):
if self.state == "open":
raise CircuitOpen()
try:
result = func(*args)
except Exception:
self._failures += 1
if self._failures >= self._max_failures:
self._open_since = self._clock()
raise
self._failures = 0
self._open_since = None
return resultOutput of a simulation in which the service is down until second 40:
t= 0 s failed after attempting the call circuit closed t= 1 s failed after attempting the call circuit closed t= 2 s failed after attempting the call circuit open t= 3 s rejected without calling circuit open t=10 s rejected without calling circuit open t=33 s failed after attempting the call circuit open t=50 s rejected without calling circuit open t=64 s order 1042 email sent circuit closed
Explanation:
callreceives the function to be protected. If the circuit is open, it raisesCircuitOpenimmediately, without waiting for any timeout.- Each failure increments the counter. On the third, the opening moment is recorded.
- The state is deduced from the elapsed time. After 30 seconds, the circuit is half-open and lets one call through. At second 33 the test fails and the circuit opens again; at 64 it works and the circuit closes.
- The
clockparameter allows using a simulated clock in tests, so as not to really wait.
In production, an already proven library is usually used. This version is didactic: it is not prepared for several threads to use it at the same time.
What the Store Does If There Is No Email
One business decision remains. If the service does not respond, should the confirmation fail? No: the customer has already paid. A decorator, like those from Module 2, guards the call and lets things continue:
class GuardedNotifier(Notifier):
def __init__(self, notifier, circuit_breaker, logger):
self._notifier = notifier
self._circuit_breaker = circuit_breaker
self._logger = logger
def send_confirmation(self, order):
try:
self._circuit_breaker.call(self._notifier.send_confirmation, order)
except (CircuitOpen, ServiceUnavailable):
self._logger.warning("Email not sent: order %s", order.id)This is called graceful degradation: in the face of a failure, the system offers less, but keeps offering what is essential. It has a cost: in the second half of December, 7 customers paid for their order and did not receive the email. It was recorded in the log, but nobody resent it.
API Gateway
An API gateway is a component that sits in front of several services and offers clients a single point of access. It routes each request to the corresponding service and concentrates common tasks, such as rate limiting.
It is needed when there are several services exposed to external clients or to mobile applications. Verdalia does not need one: its only service is internal and only the store calls it. The entry point from outside is still Nginx.
When Synchronous and When Asynchronous
| Question | Synchronous | Asynchronous |
|---|---|---|
| Does the caller need the result to continue? | Yes | No |
| How long does the operation take? | Little | A lot, or unpredictably |
| What happens if the receiver is unavailable? | The operation fails | The work waits |
| Is the user waiting? | Yes, and needs the response | Does not need to see it finish |
| Complexity | Lower | Higher: an intermediary is needed |
Applied to confirming an order:
| Step | Is the result needed? | Suitable form |
|---|---|---|
| Charge | Yes: without a charge there is no order | Synchronous |
| Save the order | Yes | Synchronous, in-process |
| Send the confirmation email | No | Asynchronous |
| Notify the warehouse | No | Asynchronous |
The last two steps are being handled today in the least suitable way.
Common Mistakes and Tips
- Calling without a timeout. The
requestslibrary applies none by default. It has to be given on every call. - Retrying operations that are not idempotent. Before adding retries, ask yourself what happens if the work is done twice.
- Generating a new key on every attempt. The server would see different operations and the key would be useless.
- Retrying 4xx errors. A malformed request will still be malformed.
- Always responding 200 with the error inside the body. It forces the caller to interpret the content and confuses monitoring tools.
- Changing the API without notice. Renaming a field breaks every client. Incompatible changes require a new version.
- Stacking retries in a chain. If three chained components each retry three times, the last one receives 27 requests.
- Practical tip. For every remote call, write down three facts: the maximum wait, the number of attempts, and what the system does if all of them fail.
Exercises
Exercise 1: Verbs and Codes
Indicate the suitable verb, route, and response code for an orders API:
- Get order 1042, which exists.
- Create a new order.
- Cancel order 1042, which has already shipped and cannot be canceled.
- Get order 9999, which does not exist.
Exercise 2: Can It Be Retried?
Indicate whether each operation can be retried without further precautions:
GET /v1/notifications/NOT-1.POST /v1/notificationswithout an idempotency key.- Deducting one unit from a product's stock.
- Setting a product's stock to 12.
Solutions
Solution to Exercise 1
GET /v1/orders/1042, with 200.POST /v1/orders, with 201.DELETE /v1/orders/1042, or aPOST /v1/orders/1042/cancellation, with 409: the request is correct, but it clashes with the order's state.GET /v1/orders/9999, with 404.
Solution to Exercise 2
- Yes. It is a query.
- No. Every repetition would send another email.
- No. Every repetition deducts another unit.
- Yes. Repeating it leaves the same result. Setting a value is idempotent; adding or subtracting is not.
Common mistake: thinking that idempotency depends on the verb. It depends on what the operation does. The verb only indicates what the server promises.
Conclusion
In this lesson you have classified the forms of communication between components and designed a REST API with resources, verbs, status codes, and a version. You have seen what the network adds: waiting and partial failures in which the caller does not know what happened. And you have learned the four basic protections: timeouts, retries with exponential backoff, idempotency keys, and circuit breakers.
At Verdalia, the notification service has a versioned API, /v1/notifications. The charge sends PagoRaíz the order reference as an idempotency key, which fulfills the promise from Module 2. And a failure of the email service no longer prevents confirming an order.
But the last table exposes the current design. The customer keeps waiting while an email is sent whose result they do not need, and when the service fails, the email is lost: it has already happened 7 times. What is needed is a place where the work can wait without making the customer wait. That is what we will see in the next lesson, “Message Queues and Event-Driven Architecture.”
