Yami Odymel
Yami Odymel

Reputation: 1898

Should I create a message per method or use a shared message in gRPC?

Currently I'm using gRPC as the communication between my servers, but I don't know which is the best pattern.

Should I create a shared request message (UserRequest is treated like an User object):

service User {
    rpc Create (UserRequest) returns (Reply) {}
    rpc Update (UserRequest) returns (Reply) {}
    rpc Delete (UserRequest) returns (Reply) {}
}

message UserRequest {
    string username = 1;
    string password = 2;
    string email = 3;
    string gender = 4;
    string birthday = 5;
}

Or create a message per method like this to define the fields that the method actually needed? But since the methods are using almost the same fields, this is kinda verbose for me.

service User {
    rpc Create (CreateUserRequest) returns (Reply) {}
    rpc Update (UpdateUserRequest) returns (Reply) {}
    rpc Delete (DeleteUserRequest) returns (Reply) {}
}

message CreateUserRequest {
    string username = 1;
    string password = 2;
}

message UpdateUserRequest {
    string username = 1;
    string password = 2;
    string email = 3;
    string gender = 4;
    string birthday = 5;
}

//...

Upvotes: 1

Views: 1061

Answers (1)

Eric Anderson
Eric Anderson

Reputation: 26414

Generally, create a different message for each RPC, to allow you to extend them separately. There are exceptions, but it would be unlikely when the methods do different things (create, update, delete).

As an example similar to your situation, take a look at pubsub:

rpc CreateSubscription(Subscription) returns (Subscription) {...}
rpc UpdateSubscription(UpdateSubscriptionRequest) returns (Subscription) {...}
rpc DeleteSubscription(DeleteSubscriptionRequest) returns (google.protobuf.Empty) {...}

I will note it uses google.protobuf.Empty, which I generally wouldn't suggest using for your own service as it prevents further extension. It also would have been fine to have created a CreateSubscriptionRequest that just contained a Subscription. I expect they didn't so as to make REST API to feel more natural (those google.api.http options).

Upvotes: 2

Related Questions