Self-Contained Service
Design services to answer requests from local ownership data instead of chaining synchronous calls.
What you will be able to do
- Explain why chains of synchronous calls make a system fragile
- Calculate how availability falls as a call chain grows
- Design a service that answers from its own local data
- Keep that local copy up to date with events
- Explain the trade-off: duplicated data and eventual consistency
The idea, in plain English
Splitting a system into services creates a new way to fail. If the order service must call the user service, which calls the inventory service, on every request, then an order only works when all three are up - and the request is only as fast as all three together.
A self-contained service avoids that. It keeps a local copy of the data it needs from other services, and answers requests from its own database. No live calls to other services sit in the request path.
The copy is kept fresh by events: when a user changes their address, the user service publishes an event, and the order service updates its copy. The price is duplicated data that is briefly out of date - eventual consistency.
Worked example: An order service that keeps taking orders while the user service is down.
An everyday example: the delivery driver’s list
A driver starts the day with deliveries to make:
- Chatty way: before each delivery, phone the office to ask the address. If the office line is down, no deliveries happen.
- Self-contained way: take a printed list of today’s addresses. Deliveries go on, office or no office.
- If a customer changes their address, the office texts the driver, who updates the list. The text may arrive a few minutes late - the list is briefly out of date.
- The driver trades a small risk of stale data for never being stuck.
Phoning the office every timeA synchronous call in every request - and its failure becomes yours.The printed listA local copy (projection) of the data the service needs.The office texts a changeAn event updates the copy.The text arrives a bit lateEventual consistency.Why call chains are fragile
- When a request calls services one after another, it succeeds only if EVERY service is up.
- So availabilities multiply. Five services at 99.5% each give about 97.5% for the chain.
- In hours: a single service at 99.5% is down about 3.6 hours a month; a chain of five is down about 17.8 hours.
- Response times add up the same way - the slowest service sets the pace.
- And a slow service ties up callers waiting on it, which can spread the failure upstream (Circuit Breaker, Lesson 26, and Timeouts, Lesson 29, limit this).
each = 0.995 # every service is up 99.5% of the time
for chain in (1, 3, 5):
a = each ** chain
hours = (1 - a) * 24 * 30
print(f"chain of {chain}: {a:.2%} available, about {hours:.1f} hours down per month")
# chain of 1: 99.50% available, about 3.6 hours down per month
# chain of 3: 98.51% available, about 10.7 hours down per month
# chain of 5: 97.52% available, about 17.8 hours down per monthAnswer from local data, update it with events
- The order service keeps its own small table of the customer data it needs - name and address, not the whole profile.
- Placing an order reads that table. No call to the user service.
- When the user service changes an address, it publishes a UserAddressChanged event. The order service listens and updates its copy (Event-Driven Communication, Lesson 7).
- The model below takes the user service DOWN and runs both designs. The chatty one fails; the self-contained one keeps working.
- Then an event arrives with a new address, and later orders use it.
user_service_up = False
def get_user(user_id):
if not user_service_up:
raise ConnectionError("user-service unavailable")
return {"id": user_id, "name": "Ravi", "address": "12 MG Road, Pune"}
def place_order_chatty(user_id, item):
user = get_user(user_id) # a live call, on every order
return f"order for {item} to {user['address']}"
# Self-contained: a local copy of the user data this service needs,
# updated from "UserAddressChanged" events whenever it changes.
local_customers = {7: {"name": "Ravi", "address": "12 MG Road, Pune"}}
def on_user_address_changed(event):
local_customers[event["user_id"]] = {"name": event["name"], "address": event["address"]}
def place_order_self_contained(user_id, item):
customer = local_customers[user_id] # no call - read the local copy
return f"order for {item} to {customer['address']}"
for design in (place_order_chatty, place_order_self_contained):
try:
print(f"{design.__name__:<28} OK:", design(7, "pen"))
except ConnectionError as e:
print(f"{design.__name__:<28} FAILED:", e)
# The copy is updated by an event - later, not instantly
on_user_address_changed({"user_id": 7, "name": "Ravi", "address": "4 FC Road, Pune"})
print(f"{'after the event arrives':<28}", place_order_self_contained(7, "pen"))
# place_order_chatty FAILED: user-service unavailable
# place_order_self_contained OK: order for pen to 12 MG Road, Pune
# after the event arrives order for pen to 4 FC Road, PuneThe trade-off: copies and eventual consistency
- The same data now lives in more than one place. Only ONE service owns it and may change it - the others hold read-only copies.
- A copy can be briefly out of date: an order placed seconds after an address change may use the old address.
- For most data that is fine. Where it is not - a bank balance, the last item in stock - the owning service must decide, often with a direct call or a reservation step.
- Events can arrive twice or out of order, so updates to the copy should be safe to repeat.
- Keep the copy small: only the fields this service really needs.
Watch out: Self-contained does not mean no communication - it means none in the request path. The events still have to be delivered reliably (Transactional Outbox, Lesson 19).
Self-contained service, at a glance
Call chainSynchronous calls in the request path - availability multiplies down.
0.995 ** 5 = 97.5%
Local copy (projection)The few fields this service needs from others, in its own store.
local_customers
EventHow the owner tells others that data changed.
UserAddressChanged
Single ownerOnly one service may change the data; others read copies.
user-service owns addresses
Eventual consistencyCopies catch up a little later.
seconds, usually
What usually goes wrong
Each call adds latency and multiplies the chance of failure. Keep what you need locally.
✗ place_order() -> get_user() -> get_stock() -> get_price()✓ place_order() reads local copies, kept fresh by eventsA full copy of another service’s data couples you to its whole schema. Copy only the fields you use.
If two services both edit a customer’s address, the copies diverge. One service owns the data; the rest only read.
Stock for the last item, money, permissions - here a stale copy causes real harm. Ask the owner, or reserve.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
A checkout calls price-service, stock-service and user-service in order, each 99.9% available. What is the availability of checkout from these calls alone?
Show hintHide hint
Multiply.
Show solutionHide solution
print(f"{0.999 ** 3:.3%}") # 99.700%The order service needs each product’s name and price. Which service owns them, what event would keep a copy fresh, and which fields would you copy?
Show solutionHide solution
Owner: catalog-service
Event: ProductPriceChanged / ProductRenamed (or one ProductUpdated)
Copy: product_id, name, price - nothing else
Note: the price charged should still be checked or locked at payment time,
because a copy can be seconds out of date.Key points
- Chains of synchronous calls make a request depend on every service in them.
- Availability multiplies: five services at 99.5% give about 97.5%.
- A self-contained service answers from its own data - no live calls in the request path.
- It keeps small, read-only copies of other services’ data, updated by events.
- One service owns each piece of data; the others only hold copies.
- The price is duplication and eventual consistency - fine for most data, not for all.
- Use a direct call or a reservation where the data must be exact.
Quick check before you move on
Interview questions
How do you avoid cascading failures between microservices?
Remove synchronous dependencies from the request path where possible: keep local, event-updated copies of the data you need so a service can answer on its own. Where calls remain, use timeouts, retries with backoff, circuit breakers and bulkheads.
What is eventual consistency, and when is it acceptable?
Copies of data converge to the latest value shortly after a change instead of immediately. It is acceptable when a brief delay does no harm - profiles, catalogues, addresses - and not for invariants that must hold at every moment, such as balances or unique stock.
What is a local projection or read model?
A service’s own copy of data owned elsewhere, shaped for its needs and kept up to date by consuming the owner’s events. It lets the service serve requests without calling the owner.
Quiz
- 1.
Why does adding services to a synchronous call chain lower availability?
- 2.
When should a service NOT rely on its local copy?
- 3.
Who may change data that several services hold copies of?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...