Repeated Fields in Protobuf (Arrays/Lists)

Learn how to define repeated fields in protobuf for arrays and lists. Covers packed encoding, ordering guarantees, and common patterns for collection types.

Basic Messages

Detailed Explanation

Working with Repeated Fields

The repeated keyword turns a field into an ordered list of values. It is the protobuf equivalent of arrays, lists, or slices in most programming languages.

syntax = "proto3";

message ShoppingCart {
  string customer_id = 1;
  repeated CartItem items = 2;
  repeated string promo_codes = 3;
  repeated int32 saved_item_ids = 4;
}

message CartItem {
  string product_id = 1;
  string name = 2;
  int32 quantity = 3;
  double price = 4;
}

Key Characteristics

  • Ordering is preserved: Elements maintain their insertion order through serialization and deserialization.
  • Empty by default: A repeated field with no elements is its default value (empty list) and is not serialized on the wire.
  • Packed encoding: In proto3, scalar numeric repeated fields use packed encoding by default, which stores all values contiguously without field tags between them — significantly reducing wire size.
  • No null elements: Repeated fields cannot contain null entries. For message types, each element is a fully initialized message.

Packed vs. Unpacked

For scalar numeric types, proto3 uses packed encoding by default:

// Packed (default in proto3): [tag][length][value1][value2][value3]
// Unpacked: [tag][value1][tag][value2][tag][value3]

Packed encoding can reduce wire size by 30-50% for repeated numeric fields with many elements.

Common Patterns

Repeated fields are commonly used for: list responses in APIs, tags and labels, batch operations, time-series data points, and permission lists. When you need key-value semantics, consider using map fields instead.

Use Case

Defining API responses that return collections of items such as search results, product listings, user activity feeds, or any endpoint that returns multiple records.

Try It — Protobuf Definition Parser

Open full tool