Sync versus async calls, gateways, BFFs and micro-frontends
Decide per interaction whether a service should wait for an answer, compute what that choice does to the availability and latency of a checkout, and place an API gateway, backends for frontends or micro-frontends where clients and teams need them.
Contentsand lesson path
On this page
- Why it matters
- Synchronous or asynchronous: the rule
- What the choice does to a checkout, in numbers
- API gateways and backends for frontends
- Micro-frontends
- Check your understanding
- Apply it
- Review prompt
Lessons of Microservices Architecture
- What microservices buy and what they cost Concept · 20 min
- Prerequisites and platform: automation, observability, sidecars and meshes Concept · 20 min
- Decomposing a retailer by capability and bounded context Worked example · 30 min
- Database per service and querying across services Concept · 25 min
- Sync versus async calls, gateways, BFFs and micro-frontends Concept · 25 min
- Service decomposition check Knowledge check · 10 questions
What you will learn
- Choose synchronous or asynchronous communication per interaction and place API gateways, backends-for-frontends or micro-frontends where clients and teams need them.
Prerequisites: Strategic Domain-Driven Design
01. Why it matters
When a Tarnside customer presses Place order, seven services have work to do: pricing, inventory, payments, loyalty, email, analytics and fulfilment. If checkout waits for all seven, the customer waits for the slowest and fails whenever any one of them fails. If it waits for none, it may confirm an order that cannot be paid for.
This lesson turns that choice into a rule you can apply per interaction, puts numbers on it, and then looks at the edge of the system, where web and mobile clients meet dozens of services: API gateways, backends for frontends (BFFs) and micro-frontends.
02. Synchronous or asynchronous: the rule
In a synchronous interaction the caller sends a request and waits for the reply, as with HTTP or gRPC. That stays true even if the client uses non-blocking I/O such as async/await: the code does not block a thread, but the business step still cannot finish without the answer. In an asynchronous interaction the sender publishes a message, often an event such as OrderPlaced, and moves on; consumers process it when they can.
The rule: call synchronously when the caller needs the answer to continue, and publish an event for reactions it does not depend on. Tarnside will not confirm an order without a price, a stock reservation and a payment authorisation, so those three are synchronous. Loyalty points, the confirmation email, analytics and shipment creation are reactions to an order that already exists, so they consume OrderPlaced.
Asynchronous messaging has its own costs. With the common at-least-once delivery a message can arrive twice, and order is not always kept, so consumers must be idempotent (delivery guarantees). The system is briefly inconsistent: the order exists before the points do. Debugging needs tracing across a broker. And a request that needs a reply over messaging needs a reply queue and correlation IDs, which is clumsier than an HTTP call. So async is not better; it removes waiting where waiting buys nothing. Designing the events themselves is the subject of event-driven architecture.
03. What the choice does to a checkout, in numbers
The price of distribution showed that a chain of required calls succeeds only if every call does. The script applies that to three checkout designs: (1) all seven calls one after another; (2) pricing and inventory called in parallel, then payments, then publishing OrderPlaced to a broker before answering; (3) the same, but the event is saved in checkout's own database in the same transaction as the order, and a separate relay publishes it later, the outbox pattern (outbox pattern).
The availabilities and latencies are invented scenario inputs, not measurements of real services; the latency of each call is drawn from a seeded random generator, so the output repeats exactly. Python 3.12 or newer.
"""checkout_paths.py: availability and latency of three checkout designs.
A model, not a measurement. The availabilities and latency shapes are made-up
inputs, failures are assumed independent, and a month is 30 days.
"""
import random
import statistics
# Monthly availability of each dependency (scenario inputs, not benchmarks).
AVAIL = {"checkout": 0.9995, "pricing": 0.9995, "inventory": 0.999,
"payments": 0.999, "loyalty": 0.995, "email": 0.995,
"analytics": 0.99, "fulfilment": 0.999, "broker": 0.9995}
# Typical latency of one call in ms; about 1 call in 50 is 8 times slower.
TYPICAL_MS = {"pricing": 25, "inventory": 30, "payments": 120, "loyalty": 20,
"email": 40, "analytics": 15, "fulfilment": 35, "broker": 5}
CRITICAL = ["pricing", "inventory", "payments"] # checkout needs these answers
REACTIONS = ["loyalty", "email", "analytics", "fulfilment"] # it does not
rng = random.Random(11)
def call_ms(service: str) -> float:
slow = 8 if rng.random() < 0.02 else 1
return TYPICAL_MS[service] * slow * rng.uniform(0.7, 1.3)
def all_sync() -> float: # every step called one after another
return sum(call_ms(s) for s in CRITICAL + REACTIONS)
def sync_core_then_publish() -> float: # price and reserve in parallel, then pay
core = max(call_ms("pricing"), call_ms("inventory")) + call_ms("payments")
return core + call_ms("broker") # publish OrderPlaced before answering
def sync_core_with_outbox() -> float: # event saved in checkout's own database
return max(call_ms("pricing"), call_ms("inventory")) + call_ms("payments") + 1
def availability(services: list[str]) -> float:
total = 1.0
for s in services:
total *= AVAIL[s]
return total
designs = [
("1 all synchronous", all_sync, ["checkout"] + CRITICAL + REACTIONS),
("2 core sync + publish", sync_core_then_publish, ["checkout"] + CRITICAL
+ ["broker"]),
("3 core sync + outbox", sync_core_with_outbox, ["checkout"] + CRITICAL),
]
print("design available down/30 days p50 p99")
for name, run, needs in designs:
a = availability(needs)
times = sorted(run() for _ in range(20_000))
p50 = statistics.median(times)
p99 = times[int(len(times) * 0.99)]
print(f"{name:<23} {a:9.3%} {(1 - a) * 30 * 24:5.1f} hours "
f"{p50:4.0f} ms {p99:5.0f} ms")Before you run it, predict: which design gains the most availability, and does the 99th-percentile latency improve as much as the median?
python3 checkout_paths.pydesign available down/30 days p50 p99
1 all synchronous 97.621% 17.1 hours 291 ms 1155 ms
2 core sync + publish 99.650% 2.5 hours 159 ms 1008 ms
3 core sync + outbox 99.700% 2.2 hours 154 ms 994 msWaiting for all seven multiplies eight availabilities, and the weakest dependencies dominate: 99.0% analytics and two 99.5% services pull checkout down to about 97.6%, the equivalent of 17 hours of downtime in a 30-day month. Moving the four reactions off the path lifts it to 99.65%. The outbox adds a little more, because a broker outage then delays events instead of failing orders. Its main purpose, though, is correctness, which the model cannot show: in design 2 a crash between saving the order and publishing loses the event. The outbox has its own costs: an extra table and a relay process to run and monitor, events that arrive later by the relay's lag, and duplicates when the relay crashes after publishing but before marking the row sent, so consumers must still be idempotent (distributed data patterns).
The median latency nearly halves, partly because fewer calls are waited for and partly because pricing and inventory now run in parallel. Note what parallelism does and does not do: it shortens the wait to the slower of the two calls, but checkout still needs both answers, so their availabilities still multiply. The 99th percentile falls by only 13 to 14%, against 45 to 47% for the median, because it is dominated by the slow tail of payments, which is still on the path. Asynchronous reactions do not fix a slow critical dependency; a timeout, a better provider or a different flow would.
The limits of the model matter. It assumes failures are independent, but real failures are often shared: one database, one deploy or one network fault can take several services down together, which makes the true numbers worse. The figures also count a calendar month of 30 days and ignore partial outages. Treat the output as a way to compare designs under stated assumptions, not as a prediction.
04. API gateways and backends for frontends
Letting clients call fifteen internal services directly has three costs: they must know the decomposition, make many round trips over slow networks, and break whenever a service is split or merged. An API gateway gives them one entry point and owns concerns that are the same for every service, such as TLS, token checks and rate limits (where gateways sit). For microservices its key value is that it hides the decomposition, so lesson 3's merges and splits do not reach the clients. Its risk is growth: a shared gateway that gains per-screen aggregation and business rules becomes a new monolith that every team waits for.
A backend for frontend (BFF), a pattern Sam Newman described in 2015, gives each user experience its own small backend, owned by the team that builds that client: one for the mobile app, one for the website. The BFF calls the domain services, aggregates their answers and shapes payloads for its screen, so the mobile team changes its BFF without waiting for anyone. The costs are more deployables and some duplication between BFFs. Duplicated plumbing is acceptable, but duplicated business rules are not: if two BFFs compute discounts, they will drift apart. Newman suggests moving such shared logic into a service modelled on the domain, here pricing, rather than merging the BFFs into one general backend.
When not to use BFFs: with a single web client and little aggregation, a BFF is one more service for no gain. Newman himself suggests one only when there is significant server-side aggregation, and per client type once mobile or third-party clients need something different. A query layer such as GraphQL is another way to let clients shape their payloads (beyond REST).
05. Micro-frontends
Services can be released independently, yet if the website is one front-end codebase, every team's screen change still waits for one front-end release. Micro-frontends, described by Cam Jackson on martinfowler.com in 2019, split the web UI into independently deliverable applications composed into one product, often one per business area: product pages, checkout, account.
How they are composed decides whether the independence is real. Composition on the server, or in the browser at run time through JavaScript, web components or iframes, lets each team deploy alone; module federation and import maps are two run-time mechanisms. Publishing each part as a package that a container app installs at build time looks simpler, but every change then needs the container rebuilt and released, the same lockstep releases microservices were meant to remove; Jackson recommends strongly against it.
They help when several teams own parts of one large web product and release contention in the front end is real. They hurt with one front-end team, with small apps, and on pages where download size matters, because independently built bundles can each carry their own copy of a library such as React. They also bring more repositories, pipelines and servers, and need a shared design system to keep the product looking like one product. What if a single team owns the whole site? Then a well-structured single app gives clear module boundaries in code without these costs.
06. Check your understanding
07. Apply it
Complete the practice deliverable for your online grocery and review it as a whole.
- From your ownership table, list every interaction of placing an order and booking a delivery slot. Mark each synchronous or asynchronous using this lesson's rule, and justify the three you deliberately keep synchronous.
- Edit
checkout_paths.pywith your own dependencies and estimates, and record which design you choose and the assumptions behind the numbers. - Decide the edge: one gateway, BFFs per client, micro-frontends or none, with the team structure that justifies it.
- Re-check the whole deliverable: no table with two owners, no synchronous cycle, and your library-versus-mesh paragraph from lesson 2.
08. Review prompt
Without looking back: state the rule for choosing synchronous or asynchronous interaction, and two costs of asynchronous messaging. Explain why availability multiplies along required calls, what parallel calls change and what they do not, and why the p99 in the model improved much less than the median. Say what an API gateway, a BFF and a micro-frontend each give, and one situation where each is the wrong choice.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.