protobuf:insert field number before exist item

Viewed 95

Considering we have a protobuf file defined as follows:

message MyMessage {
    string field1 = 1;
    string field3 = 3;
}

The server and client both use the protobuf file. The the server side change the file to this:

message MyMessage {
    string field1 = 1;
    string field2 = 2;
    string field3 = 3;
}

And the client side keep unchanged, could the client decode the data send from server side now?

2 Answers

This is a perfectly legitimate change, as long as there never was a field 2 historically. If there was, you can get huge problems and confusion, if any old data on disk etc might have the old meaning of field 2.

So as long as that holds, this change is perfectly valid on any compliant implementation; since this is proto3, the field is implicitly optional:

  • old code deserializing data that has the extra field will either silently ignore it, or store it in an opaque way for round-trip
  • new code deserializing data that lacks the new field will just mark it as lacking a value

As along as you don't reuse field numbers, this should be fine.

It should be straightforward for you to prove this for yourselves.

Here's the documentation on field numbering:

Related