type of communication between microservices (injecting microservice)

287 views Asked by At

I have API GATEWAY, user, role, mailer, user-role microservices.

I have a question which type of development use more in production code:

  1. I should send event to createUser from gateway to userMicroservice, then if response OK, i will send another request to roleMicroservice to get role. Then if OK i will send request to userRole microservice to assign role to user. if ok i will send event to mailerMicroservice to send user mail:

API GATEWAY - Dummy Code:

user = await userMicroservice - create user
if (OK) await roleMicroservice - get role for user
if (OK) await userRoleMicroservice - assign role to user (create relation)
if (OK) await mailerMicroservice - send mail to user

OR

  1. Just send createUser event to user microservice and do all logic in user microservice:

API GATEWAY:

user = await userMicroservice - create user
return user

User Microservice:

- create user
- get role (inject role microservice)
- assign role to user (inject user role microservice)
- send mail (inject mailer service)
return response

I understand what it's depends on project/requirements (tried chatGPT, and searched on internet) but i don't have much experiance with it and maybe one approach it's totally shit. Question for good backend developers.

Thanks:)

2

There are 2 answers

0
Mudzia Hutama On

Let one microservice to does complex thing make it very hard to maintenance later. Each microservice must independent. Processing another microservices in this one makes them tightly coupled. I think let them do their task as a asynchronous manner is the best choice.

0
Vikas Joshi On

Normally user/role/user-role are good to have in one microservice as they represent entities of same domain (authentication / authorization). This service will create user and associate role with it. Once user is created an event can be sent which can be consumed by mailer service to send mails. There would be some edge cases with this approach as well where if while sending event message broker has some issues and you are not able to send message. In such a scenario you would still like to create user but send mail after some time when message broker comes back. For such issues we can have different approaches.

  1. Keeping some flag in user service to indicate whether on-boarding mail event sent successfully or not. Some timer can check this flag and if the event is not sent can send it and update flag. Still it has the same problem of not able to update flag after sending event :-)
  2. We can have some CDC doing the heavy-lifting for us and putting event in message broker. Hope it helps!!