Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing cross DB queries in microservices

i have users and chats microservices, with their separate databases, currently i decided to not use data duplication due to its high maintenance demands, and went for giving read access to chats microservice for users database, but now i have a problem, i need to fetch recent chats list which includes profile picture of user, name and text preview of last message. Problem is that i save only sender and receiver ids in message schema (mongodb) and i can not look it up in users database, because it would be very expensive to lookup each user separately, i know there is no correct way of doing it but i think this scenario can be quite common so how would you go for the solution?

like image 462
Iliaaaa Avatar asked Dec 27 '25 21:12

Iliaaaa


1 Answers

I'd recommend to give a look here and read about 'Database per service' approach. In general, this is not a good practice to give microservice x direct access to the DB of microservice y. Each microservice should be aware of its own database only. Instead of giving the ChatService access to users database, you can expose an API like getUserById in the UserService, and such that the ChatService (which holds the ID of a user) will request the user's details (name, picture, etc.) from the UserService. If you want to reduce calls from ChatService to UserService, you can consider caching of the users' data in the ChatService and then you don't have to do a call for each and every user.

Such that, you preserve the 'Database per service' pattern, you avoid making the users database a bottleneck, and you might even get better performance since with the right architecture API call should be faster than database call.

like image 115
idanz Avatar answered Dec 30 '25 22:12

idanz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!