Let's say there's a service called "CreateOrder". Let's say as well that the service depends on "Inventory" service to check whether the items in the order are available, and also "Location" service that determines whether the shipping destination is within the supported area (not necessarily an efficient design but put that aside for now).
In the classical approach it is easy. The client just call the "CreateOrder" service, then CreateOrder will call Inventory and Location services (either sequentially or parallel). Only then when both services returns "OK" that CreateOrder return successfully to the client with an OrderId, for example.
But how about the event driven approach? In my understanding an event driven approach works like this (please correct me if I'm wrong):
- The client calls the CreateOrder service
- Create order post the request into a message broker (let's say kafka) into a pre-defined topic (let's say "Inventory" and "Location" topics)
- The Inventory and Location service consume the event from the message broker and process the request
But then, what? How the CreateOrder service get the result so it can get back to the client? One approach that come to mind is that the Inventory and Location services can write to somewhere upon completion (maybe a database), which the CreateOrder service can regularly poll for a result based on some kind of identifier (presumably a request ID). But this sounds horribly inefficient to me.
Is there a better approach? Another idea that come to mind is that the Inventory and Location service can push an event to kafka again upon completion, which the CreateOrder service can subscribe to. But there are a lot of questions with this approach: there are pontentially many requests that are running in parallel, how can the CreateOrder service selectively get the event for the appropriate request? To make it more complicated, what if the "CreateOrder" service is deployed in multiple instances in multiple machine? If this is even possible, is it efficient to do so? And is this possible at all? How to make the RestController wait for the kafka event in the first place?
Please enlighten me. A sample code (preferably in Spring-Boot) is always welcome!
Thanks.