How to query data from multiple microservices

filteringmicroservicesquery

I have micro service architecture application. One of the services contains all user related information. Another service contains a set of business objects. The Angular UI calls rest APIs of user-service and business-service to perform operations like user management, business management. The tables in the business-service contain user ID from user-service for example owner of a business object. Since they are different databases, there is no referential constraint.

I want to display a list of business objects in UI. I want to be able to filter the results by the owner's first name. Note that the business-service does not know user's details except user ID.

What is the best way to query data belonging to multiple services ?

Some options in mind

  • store redundant data in business service – but this could go out of sync. May have to run a cron job to keep it in sync with user-service. But the solution is ugly.
  • First, get list of user ID's matching the user's first name. Pass those IDs to the business service to get the list of business objects there by achieving filtering.

Both solutions don't seem to be clean…

Best Answer

I typically have a service that is dedicated to serve the needs of each frontend app. This service does any backend lifting on behalf of the frontend. This has a couple of pros:

  • Format data for easiest consumption by the UI. Different UI's will have different requirements. For example if I have an Android app, I might choose the frontend service for this app to use an alternate serialization format to Json because device bandwidth is limited and there are smaller protocols out there.
  • Decouple the format of data that frontend requires from the backend--if you decide to change Json structure in one of your services, you can use the adapter pattern in the frontend service.
  • Single point of access for the frontend to the backend-- you can control access here and restrict domains for example.
  • Combine requests efficiently-- the frontend shouldn't send as few requests to the backend as possible, but sometimes the UI demands a bit of data from several different services. The frontend service is a good place for this logic and it can make several requests much more efficiently.

First, get list of user ID's matching the user's first name. Pass those IDs to the business service to get the list of business objects there by achieving filtering.

I recommend this approach. I would have the "frontend service" make a request to the user service to get all users by name, extract the ids and make a request to the business service to get business objects by user ids. You should implement endpoints in the services to facilitate these two requests. If you're making n requests, you've done it wrong.

Related Topic