Microservice communication
medium 35 minMicroservices work together over the network, so every link between two of them is a design decision: a call that waits for an answer, or a message that does not.
See it run
One order placed five ways: a chain of calls, events, a saga that works, a saga that fails, and an outbox.
Operations
Chain of calls
Every service waits for the next one. The client gets one answer when all are done.
Step 1 of 8
Request
The client sends the order as an HTTP request to the gateway and waits.
Step 1: Request
def create_order(order): if not stock.reserve(order, timeout=3): raise NotEnoughStock try: payment.charge(order, key=order.id, timeout=3) except Declined: stock.release(order) raise return save(order)- User waits for
- All services
- Consistency
- When it returns
- Events
- the user waits for the order only
For every arrow say what happens if it times out.
In the real world
The same microservice communication doing real jobs. Pick one and step through it.
Payment slows down, and the callers have no timeouts.
Step 1 of 4
Normal
Payment answers in 200 ms. 100 orders a second keep 20 threads busy.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Save, then publish
criticalA crash between the two loses the event. The order exists and nobody ships it.
Wrongdb.save(order)bus.publish("OrderCreated", order)Rightwith db.transaction(): db.save(order) outbox.add("OrderCreated", order)A call without a timeout
criticalThe caller's threads wait for a service that may never answer.
Wrongrequests.get(url)Rightrequests.get(url, timeout=3)A fallback that hides a real answer
majorCatching every error turns not enough stock into a sale.
Wrongexcept Exception: stock = cache.get(product)Rightexcept (Timeout, CircuitOpen): return "try again later"Sharing the saga's state between orders
majorWith a list on the object, one failed order also undoes the steps of another.
Wrongself.completed.append(step)Rightcompleted = [] # inside run(), one per order
Interview tips
How to explain it
- Call when the answer is needed now.
- Event when the sender can go on.
- Saga when several services must agree.
Memory trick: MICRO TALK
- Message queues decouple, Idempotent, Circuit breakers, Retries with backoff, Observe.
- Timeouts always, Async when possible, Loose coupling, Keep services small.
- Undo like a stack: last first.
Say for every arrow
- Call or event, and why.
- What happens when it fails or repeats.
- Who owns the data.
Warning signs
- Services that must be released together.
- Two services writing one table.
- A user action that needs five calls in a row.