Asynchronous Communication and Redundant Data
A digression accompanying the Scalability series.
Photo: D koi @ Unsplash - Unsplash license
An online shop’s search service is supposed to show price and availability in its result list. Both belong to the product service. The obvious solution is built in a morning: for every hit, search asks the product service via REST. It works, everyone understands it, and the data is always fresh.
Under load, though, the solution soon shows its downside. A search query returns twenty hits, so twenty calls go to the product service, and each time it queries its database. One request has become forty-one: the search query itself, twenty calls, twenty database queries. As long as everything answers quickly, nobody notices. It gets interesting on the day the product service is having a bad day.
Everything that hangs on the chain
From the search service’s point of view, the product service’s response time is part of its own service time. If it fluctuates because an expensive query happens to be running in the product database, the search service’s service time fluctuates with it. According to Kingman’s formula, it is this variability that makes queues grow: the more irregular the service times, the longer the queues, even at unchanged load. That is how a slow query in the product database causes a queue in search, a service that has nothing to do with that query.
Meanwhile, every waiting request stays open. By Little’s Law, the number of concurrent requests is throughput times response time. If the search service’s response time doubles because the product service is dawdling, twice as many requests are stuck in it – at exactly the same traffic. The thread pool fills up even though the search service itself is perfectly healthy. Non-blocking I/O saves the threads, but the requests stay open all the same.
Synchronous: every search query waits for the product service.
So search can no longer scale on its own. Ten additional search instances achieve nothing as long as the product service is the bottleneck. They even make things worse: while the search service’s thread pool was full, the product service received only as many calls as search had threads. With ten more instances, that brake is gone.
If the product service fails completely, search fails with it. Along a synchronous chain, availabilities multiply: two services at 99.9% each come to 99.8% together, five to 99.5%. That sounds like a rounding error, but with five services it means just under 44 hours of downtime a year. For a single service it would be just under nine.
Things get really nasty with timeouts and retries. If the product service answers slowly, calls run into the timeout and are retried. So the overloaded service gets extra load, at exactly the moment it can least cope with it.
This can be mitigated. A batch call turns twenty calls into one, a cache absorbs the most frequent requests, a circuit breaker limits the damage when the product service hangs. All of that is worth doing, even if none of it is as quick to build as it sounds: a cache needs invalidating, and a circuit breaker needs an answer to the question of what search should display without prices. More importantly, search still waits for the product service afterward, less often, but in the same call chain.
The problem here is not the cut into two services. Separate services can be scaled separately; that is exactly why you cut. The problem is waiting for each other, and even the nicest API does nothing to change that: a stable contract decouples the teams, but at runtime search still depends on the product service. The digression Loose Coupling and Shared-Nothing calls this runtime coupling, as opposed to design-time coupling.
Events instead of calls
The alternative reverses the direction: search gets told. The product service publishes every change as an event, such as “Product 4711 now costs €19.99” or “Product 0815 is sold out.” Search subscribes to these events, processes them at its own pace and writes the result into its own data store.
Martin Fowler calls this pattern Event-Carried State Transfer: the event carries the new state with it, and the receiver doesn’t have to ask back. That sets it apart from the mere notification “Product 4711 has changed,” after which search would have to go knocking at the product service’s door again.
How the events travel is secondary. Usually a message broker such as Kafka or RabbitMQ does the job. But it also works entirely without one – with a feed that the product service provides and search polls every few seconds.
When answering a search query, search then no longer has to ask anyone; it reads from its own index. If the product service gets slow, price changes arrive later, but search answers as fast as ever. If it goes down, search answers with the last known state.
Asynchronous: the product service is no longer in the request’s path.
The work moves from reading to writing. It is now done once per price change instead of on every search query. That is a good deal, because products are searched for far more often than they are changed.
As a side effect, the broker acts as a buffer. If the nightly import dumps 100,000 price changes at once, search works through them at the pace it can manage alongside the search queries. The surge backs up in the broker – all that users notice is that new prices arrive a little later.
Keeping data twice – on purpose
The consequence is that product data now lives in several places. The product service has the original. Search has a copy with exactly the fields it needs, in the shape that suits its queries. The recommendation service has yet another.
That feels wrong, at least to everyone who grew up with normal forms – me included. For decades, redundancy was considered a design flaw. But that rule comes from a world in which all data lived in a single database. Between services, the alternative to a copy is not “a single source of truth” but “ask on every request,” and how that ends is described further up.
One rule from the old world survives nonetheless: still only one party may make changes. Prices are set by the product service and nobody else. Everyone else reads their copy and never writes back. That makes the copy something like a cache that is fed rather than having to ask.
The catch is called eventual consistency: the copy lags behind the original, usually by seconds, sometimes by minutes. For a result list, that is bearable. A price from 30 seconds ago is better than a result list that takes two seconds to load, and much better than an error page.
What it costs
Not every part of the system can tolerate that. The checkout must not charge the price from the result list: at payment, the price that counts is the one the product service states at that moment.
Then there is work that didn’t exist before, and it starts with publishing: the product service has to store the price and send the event, and no transaction spans both. If one of the two goes wrong, or two changes overtake each other on the way, the copy diverges permanently from the original. It only becomes reliable when the event originates from the database itself: the product service writes it to an outbox table in the same transaction, or a tool reads the changes from the transaction log (change data capture). As a side effect, an event will occasionally arrive twice. A feed that the product service serves directly from its database needs no second write either.
So search has to cope with duplicate events and, depending on the setup, with events out of order as well. A new consumer first needs the entire data set, and someone has to notice when search can no longer keep up.
Events also need a schema, and that schema is a contract like any API. Once something is in the event, sooner or later somebody relies on it, and then it is hard to get rid of. So some design-time coupling comes back with the events.
Finally, the broker itself is a new component that everyone shares. Strictly speaking, that is a step away from shared-nothing, meaning services with no shared resources at all. The difference lies in the kind of failure: if the broker is down, data goes stale. If a synchronously called service is down, pages stay empty.
If the broker is down, the data goes stale: search keeps answering, but with an older state.
If a synchronously called service is down, the page stays empty: search waits for an answer that never comes.
At OTTO, asynchronous communication and redundant data were among the architecture principles from the very start of the Lhotse project. That had little to do with elegance: synchronous calls between dozens of teams and services simply would not have scaled. The price was real, but affordable. A shop that is down during the Christmas season because a single service is blocking all the others would not have been.
When it is worth it
A rule of “always asynchronous” does not follow from this. Coupling has many facets; Gregor Hohpe distinguishes eight of them, including data format and timing. For scalability, the subject of this series, two questions matter most, and they tend to get lumped together.
The first is: should one service be independent of the other’s internals? That is design-time coupling, and reducing it is comparatively cheap. A stable contract, hidden internals and no shared database cost discipline more than anything. This kind of decoupling belongs wherever two services meet.
The second is: should a service keep working when the other isn’t answering? That is runtime coupling, and getting rid of it costs everything in the previous section. That price is only worth paying where it hurts.
With the result list it hurts, for all the reasons in the first section. Where none of them applies, a synchronous call with a stable contract is the more sensible choice. A back-office tool that pulls a report once an hour does not need a Kafka cluster.
Whatever truly cannot tolerate stale data stays synchronous – or the boundary is drawn so that both sides of the transaction end up in the same service. That is less than you might think at first, though. And one combination is best avoided altogether: decoupled at runtime but not at design time. Two services that pass messages to each other via a shared database table have all the complexity of asynchrony and still depend on the same schema and the same database. So: the interface first, then asynchrony.
Decide early, build late
Runtime decoupling is hard to retrofit. Synchronous communication leaves behind assumptions that run through the entire code: that data is fresh, that an answer comes immediately, that a transaction spans both sides. The events themselves can, if need be, be pulled from the transaction log after the fact; those assumptions cannot be pulled out of the code again. I have seen projects fail because synchronous communication had stopped being viable but could no longer be removed. Asynchronous communication was never too hard in those cases – it was just that nobody had planned for it while it was still cheap.
Planning for it means sticking to two rules from the start: no consumer relies on data being fresh, and no transaction reaches across a service boundary. That costs little as long as nothing has been built yet. Brokers, data copies and lag monitoring come only when it starts to hurt somewhere. At OTTO, feeds were enough for the first few years, with no broker at all; Kafka only came later, with more and more product data and more and more event types. Abbott and Fisher recommend the same pattern for capacity, as the DID principle: design for the big load, but build only when it is foreseeable.
Asynchrony does not repair a wrong cut, however. If a service has to ask three others to answer a single request, the service boundaries are probably in the wrong place, and then Kafka won’t change that either.
References
- Abbott & Fisher (2016) – Scalability Rules: Principles for Scaling Web Sites. 2nd ed. Addison-Wesley. (DID principle, Rule 2; systems in series, Rule 38)
- Fowler (2017) – What do you mean by “Event-Driven”? martinfowler.com. (Event-Carried State Transfer)
- Hohpe (2024) – The Many Facets of Coupling. enterpriseintegrationpatterns.com.
- Kleppmann (2015) – Using logs to build a solid data infrastructure (or: why dual writes are a bad idea). Confluent Blog.
- OTTO (2013) – Steinacker, Guido: Architecture principles. OTTO Tech Blog.
Comments