Search code examples
javadesign-patternsgrpcprotobuf-java

Should i convert gRPC protobuf message to DTO? - Best Practice


Lately, I started using gRPC messages to interact with microservices. Until now I was using the REST API's with DTOs do keep on decoupling and encapsulation in the code itself.

Now I'm while using the gRPC protobuf msgs, I started wondering what shell be the best practice here - while thinking about it out loud I would say that when getting the message in the entry point of the application the best would be to convert it to DTO to keep on the decupling from gRPC protobuff messages and the code itself, from the other point of view - i'm just converting object to object and wondering if these overhead is mandatory / required

Looking forward to your thoughts around this one :)


Solution

  • Well it depends on your requirement and how decoupled your service needs to be (for the long run). As far as i know, some services/people even tend to write the proto directly to the database (i.e in proto-string / byte string or byte[]) to reduce the mapping overhead and for other reasons i guess.

    Having said that, personally i think Domain Model and Data Transfer Objects (Protobuf Message) should be separated as much as possible. So its better to have extra mapping for your request and response which would help you for future changes to the IDL or proto definitions.

    If you fully rely on the resource/api layer implementation which is gRPC in your case, even a little library update may break things and it would be a hassle to go through all the places where the proto model has been used

    Further more it would helps you accommodate with changes easily like if your system chooses to fully rely on another API schema

    Lastly i don't think there are any hard rules to follow but it is fully up-to you and your requirement, but it's better to convert it to your own models rather than using it directly, allows you to have more control over the api layer and your business layer segregation and would really matter on the long run.