N
N
Nikolino2020-06-09 16:24:11
go
Nikolino, 2020-06-09 16:24:11

Grpc procedures to call synchronously or asynchronously?

For academic purposes, I wrote down a simple api with registration, authentication and several CRUDs.

Immediately after registration (adding a user to the database), you need to send an email with a confirmation code.

I decided to put it into a microservice generated through gRPC and protofiles.
The procedure in the microservice receives the email text and the address to whom to send as input. Generates an email and sends it to the Mailgun service.

In the application code, immediately after registration, this method is called:

func sendCode(code int, email string) error {
  conn, err := grpc.Dial(os.Getenv("MAILER_SERVICE_PORT"), grpc.WithInsecure())
  if err != nil {
    return err
  }
  c := pb.NewMailerClient(conn)

  _, err = c.SendEmail(context.Background(), &pb.EmailRequest{Email: email, Code: strconv.Itoa(code)})
  if err != nil {
    return err
  }

  return nil
}


If called synchronously, two problems may arise, the microservice takes a long time to respond or the email distribution server takes a long time to respond.

Is it good practice to run microservices in a goroutine?
Or is it better to connect to the distribution server (inside the microservice) asynchronously, and connect to the microservice synchronously?

After the SP with synchronous work, I want to do everything in goroutines because I can :)

PS Specifically with email distribution, it would probably be better to do all this asynchronously through the queue server. But I wanted to sniff GRPC and the microservice approach.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Kaznacheev, 2020-06-18
@Color

For gRPC, there is no good practice in this regard, it's just a remote action call.
If you expect everything to be done quickly, do it synchronously.
If you expect it *may* take a long time, do it asynchronously.
Email mailings are indeed often done through queues, but in your case, nothing prevents you from simply raising a goroutine (or several) at the start of the application, which will read emails from the channel and send them asynchronously, and then write to the channel from where you need to.
Yes, and by themselves, such actions as mailings and so on are usually performed asynchronously, so there is no need to wait for them to return a response to the request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question