Protocol Buffers

suggest change

Protocol Buffers (protobuf) is Google's binary serialization format. You describe your data in a .proto file, and the protoc compiler generates code for Kotlin, Java, Go, C++, Python and other languages. The binary encoding is compact and fast, and the format is designed so that old and new versions of a program can read each other's data.

In Kotlin you have two options:

This article covers:

For general serialization with kotlinx.serialization see Object serialization and JSON.

The .proto file

Put schema files in src/main/proto. This shop.proto is used in the rest of the article:

syntax = "proto3";

package shop;

option java_package = "com.example.shop";
option java_multiple_files = true;

import "google/protobuf/timestamp.proto";

enum Status {
  STATUS_UNSPECIFIED = 0;
  STATUS_PENDING = 1;
  STATUS_SHIPPED = 2;
}

message LineItem {
  string sku = 1;
  int32 quantity = 2;
  int64 price_cents = 3;
}

message Card {
  string brand = 1;
  string last4 = 2;
}

message Order {
  int64 id = 1;
  string customer = 2;
  repeated LineItem items = 3;
  Status status = 4;
  map<string, string> labels = 5;
  google.protobuf.Timestamp created_at = 6;
  optional string note = 7;

  oneof payment {
    Card card = 8;
    string voucher_code = 9;
  }
}

The numbers after = are field numbers. They, not the names, are written to the binary data, so once a field number is in use it must never change meaning.

Gradle setup

The protobuf Gradle plugin downloads protoc, runs it on every file in src/main/proto, and adds the generated sources to the build. protoc generates Java by default; the kotlin builtin adds the Kotlin DSL on top of it. In build.gradle.kts:

plugins {
    kotlin("jvm") version "2.4.21"
    id("com.google.protobuf") version "0.10.0"
    application
}

repositories {
    mavenCentral()
}

val protobufVersion = "4.36.2"

dependencies {
    implementation("com.google.protobuf:protobuf-kotlin:$protobufVersion")
    // only needed for JsonFormat and Timestamps
    implementation("com.google.protobuf:protobuf-java-util:$protobufVersion")
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:$protobufVersion"
    }
    generateProtoTasks {
        all().forEach { task ->
            task.builtins {
                create("kotlin")
            }
        }
    }
}

application {
    mainClass = "MainKt"
}

Keep the protoc version and the runtime library version the same. Code generated by a newer protoc can fail to compile or load against an older runtime.

gradle build generates the code into build/generated/sources/proto/main/java and .../kotlin. Never edit those files; change the .proto and rebuild.

On Android, use the lite runtime instead: depend on protobuf-kotlin-lite and add option("lite") to both the java and kotlin builtins. Lite code is much smaller but lacks reflection-based features such as JsonFormat.

Running protoc by hand

Without Gradle, download protoc from the GitHub releases and run:

protoc -I src/main/proto --java_out=gen --kotlin_out=gen src/main/proto/shop.proto

For each message you get a Java class (Order.java), a builder interface (OrderOrBuilder.java) and a Kotlin file (OrderKt.kt) with the DSL. The release zip includes the google/protobuf/*.proto files for well-known types like Timestamp in its include directory; pass it with -I if protoc can't find them.

Building messages

Generated messages are immutable Java objects. Java code builds them with Order.newBuilder().setId(...).build(). In Kotlin, use the generated DSL function named after the message, with a lowercase first letter:

import com.example.shop.Status
import com.example.shop.card
import com.example.shop.lineItem
import com.example.shop.order
import com.google.protobuf.timestamp

fun main() {
    val o = order {
        id = 1001
        customer = "alice@example.com"
        items += lineItem {
            sku = "BOOK-42"
            quantity = 2
            priceCents = 1999
        }
        items += lineItem {
            sku = "PEN-7"
            quantity = 10
            priceCents = 150
        }
        status = Status.STATUS_PENDING
        labels["channel"] = "web"
        createdAt = timestamp { seconds = 1_760_000_000 }
        card = card {
            brand = "visa"
            last4 = "4242"
        }
    }

    print(o)  // toString() is the protobuf text format
    println("---")
    println("total: ${o.itemsList.sumOf { it.quantity * it.priceCents }} cents")
    println("first sku: ${o.getItems(0).sku}, labels: ${o.labelsMap}")
}

Output:

id: 1001
customer: "alice@example.com"
items {
  sku: "BOOK-42"
  quantity: 2
  price_cents: 1999
}
items {
  sku: "PEN-7"
  quantity: 10
  price_cents: 150
}
status: STATUS_PENDING
labels {
  key: "channel"
  value: "web"
}
created_at {
  seconds: 1760000000
}
card {
  brand: "visa"
  last4: "4242"
}
---
total: 5498 cents
first sku: BOOK-42, labels: {channel=web}

Inside the DSL, repeated fields support +=, add() and addAll(), and map fields support [key] = value, put() and remove(). Well-known types have DSL functions too (timestamp {}, duration {} in com.google.protobuf).

To read a message, use the Java getters as properties. Repeated fields are exposed as itemsList and map fields as labelsMap; both are read-only.

Encoding and decoding

toByteArray() encodes a message and parseFrom() decodes it:

import com.example.shop.Order
import com.example.shop.lineItem
import com.example.shop.order
import com.google.protobuf.InvalidProtocolBufferException

fun ByteArray.hex() = joinToString(" ") { "%02x".format(it) }

fun main() {
    val o = order {
        id = 150
        customer = "bob"
        items += lineItem { sku = "A"; quantity = 3 }
    }

    val bytes: ByteArray = o.toByteArray()
    println("${bytes.size} bytes: ${bytes.hex()}")
    println("serializedSize: ${o.serializedSize}")

    val back = Order.parseFrom(bytes)
    println("equal: ${back == o}, customer: ${back.customer}")

    // ByteString is the immutable byte container used by protobuf
    val bs = o.toByteString()
    println("ByteString: size=${bs.size()}, same as parse: ${Order.parseFrom(bs) == o}")

    try {
        Order.parseFrom(byteArrayOf(0x0a, 0x05, 0x41))
    } catch (e: InvalidProtocolBufferException) {
        println("error: ${e.message}")
    }
}

Output:

15 bytes: 08 96 01 12 03 62 6f 62 1a 05 0a 01 41 10 03
serializedSize: 15
equal: true, customer: bob
ByteString: size=15, same as parse: true
error: While parsing a protocol message, the input ended unexpectedly in the middle of a field.  This could mean either that the input has been truncated or that an embedded message misreported its own length.

Each field starts with a tag that combines the field number and a wire type:

Field names aren't in the data, and fields with default values (status, price_cents) are not written at all. The same order as JSON ({"id":150,"customer":"bob","items":[{"sku":"A","quantity":3}]}) takes 62 bytes.

Messages implement equals() and hashCode() by value, so you can compare them and use them as map keys. Decoding never trusts its input blindly: malformed data throws InvalidProtocolBufferException, which is an IOException.

Default values and field presence

In proto3, a field that was never set reads as its default: 0, "", false, the zero enum value or an empty list or map. Getters never return null:

import com.example.shop.Order
import com.example.shop.Status
import com.example.shop.cardOrNull
import com.example.shop.copy
import com.example.shop.createdAtOrNull
import com.example.shop.order

fun main() {
    val empty = Order.getDefaultInstance()
    println("id=${empty.id} customer='${empty.customer}' status=${empty.status}")
    println("items=${empty.itemsList} labels=${empty.labelsMap}")
    println("createdAt (never null): '${empty.createdAt}' hasCreatedAt=${empty.hasCreatedAt()}")
    println("createdAtOrNull=${empty.createdAtOrNull}")
    println("note='${empty.note}' hasNote=${empty.hasNote()}")
    println("empty message size: ${empty.serializedSize} bytes")

    val o = order { note = "" }
    println("note set to empty: hasNote=${o.hasNote()}, size=${o.serializedSize}")

    val o2 = order { customer = "" ; status = Status.STATUS_UNSPECIFIED }
    println("customer and status set to defaults: size=${o2.serializedSize}")

    // messages are immutable; copy {} returns a modified copy
    val base = order { id = 1; customer = "carol"; note = "leave at door" }
    val changed = base.copy {
        customer = "dave"
        clearNote()
    }
    println("base: ${base.customer} ${base.hasNote()} / changed: ${changed.customer} ${changed.hasNote()}")
    println("cardOrNull=${changed.cardOrNull}")
}

Output:

id=0 customer='' status=STATUS_UNSPECIFIED
items=[] labels={}
createdAt (never null): '' hasCreatedAt=false
createdAtOrNull=null
note='' hasNote=false
empty message size: 0 bytes
note set to empty: hasNote=true, size=2
customer and status set to defaults: size=0
base: carol true / changed: dave false
cardOrNull=null

What you can tell apart:

copy {} is generated for every message. It works like copy() on a data class but uses the same DSL as the builder, so you can also call clearX() and modify lists.

oneof, enums and maps

import com.example.shop.Order
import com.example.shop.Status
import com.example.shop.card
import com.example.shop.copy
import com.example.shop.order

fun describePayment(o: Order): String = when (o.paymentCase) {
    Order.PaymentCase.CARD -> "card ${o.card.brand} ending ${o.card.last4}"
    Order.PaymentCase.VOUCHER_CODE -> "voucher ${o.voucherCode}"
    Order.PaymentCase.PAYMENT_NOT_SET -> "unpaid"
}

fun main() {
    var o = order { id = 1 }
    println(describePayment(o))

    o = o.copy { card = card { brand = "visa"; last4 = "4242" } }
    println(describePayment(o))

    // setting another member of the oneof clears the previous one
    o = o.copy { voucherCode = "WELCOME10" }
    println(describePayment(o) + ", hasCard=${o.hasCard()}")

    // enums
    println(Status.entries)
    println("${Status.STATUS_SHIPPED.number} ${Status.forNumber(2)} ${Status.valueOf("STATUS_PENDING")}")

    // an enum number this code doesn't know (sent by a newer program)
    val fromNewer = Order.parseFrom(byteArrayOf(0x20, 0x07))
    println("status=${fromNewer.status} statusValue=${fromNewer.statusValue}")

    // maps
    val labeled = order {
        labels.put("channel", "web")
        labels["region"] = "eu"
    }
    println(labeled.labelsMap)
    println(labeled.getLabelsOrDefault("priority", "normal"))
    println(labeled.copy { labels.remove("region") }.labelsCount)
}

Output:

unpaid
card visa ending 4242
voucher WELCOME10, hasCard=false
[STATUS_UNSPECIFIED, STATUS_PENDING, STATUS_SHIPPED, UNRECOGNIZED]
2 STATUS_SHIPPED STATUS_PENDING
status=UNRECOGNIZED statusValue=7
{channel=web, region=eu}
normal
1

Timestamps and JSON

google.protobuf.Timestamp stores seconds and nanoseconds since the Unix epoch. Converting to and from java.time.Instant takes two small extension functions:

import com.example.shop.Order
import com.example.shop.Status
import com.example.shop.lineItem
import com.example.shop.order
import com.google.protobuf.Timestamp
import com.google.protobuf.timestamp
import com.google.protobuf.util.JsonFormat
import com.google.protobuf.util.Timestamps
import java.time.Instant

fun Instant.toTimestamp(): Timestamp = timestamp {
    seconds = epochSecond
    nanos = nano
}

fun Timestamp.toInstant(): Instant = Instant.ofEpochSecond(seconds, nanos.toLong())

fun main() {
    val now = Instant.parse("2026-10-17T09:30:00.250Z")
    val o = order {
        id = 7
        customer = "erin"
        items += lineItem { sku = "MUG"; quantity = 1; priceCents = 1200 }
        status = Status.STATUS_SHIPPED
        createdAt = now.toTimestamp()
        voucherCode = "FREESHIP"
    }
    println("back to Instant: ${o.createdAt.toInstant()}")
    println("Timestamps.toString: ${Timestamps.toString(o.createdAt)}")

    val json = JsonFormat.printer().print(o)
    println(json)

    val compact = JsonFormat.printer()
        .omittingInsignificantWhitespace()
        .preservingProtoFieldNames()
        .print(o)
    println(compact)

    val builder = Order.newBuilder()
    JsonFormat.parser().ignoringUnknownFields().merge(
        """{"id": "8", "customer": "frank", "status": "STATUS_PENDING", "unknownField": 1,
           "items": [{"sku": "TEA", "price_cents": 450}]}""",
        builder,
    )
    val parsed = builder.build()
    println("parsed: id=${parsed.id} ${parsed.customer} ${parsed.status} ${parsed.itemsList.single().priceCents}")
}

Output:

back to Instant: 2026-10-17T09:30:00.250Z
Timestamps.toString: 2026-10-17T09:30:00.250Z
{
  "id": "7",
  "customer": "erin",
  "items": [{
    "sku": "MUG",
    "quantity": 1,
    "priceCents": "1200"
  }],
  "status": "STATUS_SHIPPED",
  "createdAt": "2026-10-17T09:30:00.250Z",
  "voucherCode": "FREESHIP"
}
{"id":"7","customer":"erin","items":[{"sku":"MUG","quantity":1,"price_cents":"1200"}],"status":"STATUS_SHIPPED","created_at":"2026-10-17T09:30:00.250Z","voucher_code":"FREESHIP"}
parsed: id=8 frank STATUS_PENDING 450

JsonFormat from protobuf-java-util implements the standard proto3 JSON mapping:

JSON is handy for debugging and for clients that can't decode binary protobuf, but use the binary encoding for storage and between services.

Many messages in one stream

The binary encoding of a message doesn't record where the message ends; a parser reads until the end of the input. To put several messages in a file or socket, prefix each one with its length. writeDelimitedTo() and parseDelimitedFrom() do exactly that:

import com.example.shop.Order
import com.example.shop.order
import kotlin.io.path.createTempFile
import kotlin.io.path.deleteIfExists
import kotlin.io.path.fileSize
import kotlin.io.path.inputStream
import kotlin.io.path.outputStream

fun main() {
    val file = createTempFile("orders", ".bin")

    file.outputStream().buffered().use { out ->
        for (i in 1..3) {
            order { id = i.toLong(); customer = "customer-$i" }.writeDelimitedTo(out)
        }
    }
    println("file size: ${file.fileSize()} bytes")

    file.inputStream().buffered().use { input ->
        // parseDelimitedFrom returns null at end of stream
        generateSequence { Order.parseDelimitedFrom(input) }
            .forEach { println("${it.id}: ${it.customer}") }
    }
    file.deleteIfExists()
}

Output:

file size: 45 bytes
1: customer-1
2: customer-2
3: customer-3

generateSequence stops at the first null, which parseDelimitedFrom() returns at the end of the stream. See Files and I/O for more on streams.

Changing the schema

Protobuf lets programs built from different versions of a .proto file exchange data. Say an older program was built from this version of Order:

syntax = "proto3";

package shop.v1;

option java_package = "com.example.shop.v1";
option java_multiple_files = true;

// The first version of Order, before items, status and payment were added.
message Order {
  int64 id = 1;
  string customer = 2;
}

Data flows in both directions:

import com.example.shop.Order
import com.example.shop.Status
import com.example.shop.lineItem
import com.example.shop.order
import com.example.shop.v1.order as orderV1
import com.example.shop.v1.Order as OrderV1

fun main() {
    // new writer, old reader
    val newOrder = order {
        id = 42
        customer = "gina"
        status = Status.STATUS_SHIPPED
        items += lineItem { sku = "LAMP"; quantity = 1 }
    }
    val old = OrderV1.parseFrom(newOrder.toByteArray())
    println("old reader sees: id=${old.id} customer=${old.customer}")
    println("unknown fields: ${old.unknownFields.asMap().keys}")

    // the old program modifies and re-serializes: unknown fields survive
    val roundTrip = Order.parseFrom(old.toBuilder().setCustomer("GINA").build().toByteArray())
    println("after round trip: ${roundTrip.customer} ${roundTrip.status} ${roundTrip.itemsList.map { it.sku }}")

    // old writer, new reader: missing fields get default values
    val fromOld = Order.parseFrom(orderV1 { id = 1; customer = "hank" }.toByteArray())
    println("new reader sees: id=${fromOld.id} status=${fromOld.status} items=${fromOld.itemsCount}")
}

Output:

old reader sees: id=42 customer=gina
unknown fields: [3, 4]
after round trip: GINA STATUS_SHIPPED [LAMP]
new reader sees: id=1 status=STATUS_UNSPECIFIED items=0

The old reader skips fields it doesn't know but keeps them, so a program in the middle doesn't lose data written by a newer one.

Rules that keep this working:

kotlinx.serialization ProtoBuf

If Kotlin owns the data and you don't need a .proto file shared with other languages, kotlinx.serialization can encode ordinary data classes in the protobuf format. It needs the serialization plugin and one library:

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21"
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.11.0")
}

@ProtoNumber assigns field numbers. If you leave them out, numbers are assigned by property order starting at 1, and reordering the properties would silently break existing data, so always set them. Because the bytes follow the protobuf wire format, a data class with matching numbers and types can exchange data with code generated by protoc:

@file:OptIn(ExperimentalSerializationApi::class)

import com.example.shop.Order
import com.example.shop.Status
import com.example.shop.lineItem
import com.example.shop.order
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
import kotlinx.serialization.protobuf.ProtoBuf
import kotlinx.serialization.protobuf.ProtoNumber

@Serializable
enum class OrderStatus {
    @ProtoNumber(0) UNSPECIFIED,
    @ProtoNumber(1) PENDING,
    @ProtoNumber(2) SHIPPED,
}

@Serializable
data class Item(
    @ProtoNumber(1) val sku: String,
    @ProtoNumber(2) val quantity: Int = 0,
    @ProtoNumber(3) val priceCents: Long = 0,
)

@Serializable
data class SimpleOrder(
    @ProtoNumber(1) val id: Long,
    @ProtoNumber(2) val customer: String,
    @ProtoNumber(3) val items: List<Item> = emptyList(),
    @ProtoNumber(4) val status: OrderStatus = OrderStatus.UNSPECIFIED,
    @ProtoNumber(5) val labels: Map<String, String> = emptyMap(),
    @ProtoNumber(7) val note: String? = null,
)

fun main() {
    val mine = SimpleOrder(
        id = 5,
        customer = "ivy",
        items = listOf(Item("CUP", 2, 800)),
        status = OrderStatus.SHIPPED,
        labels = mapOf("gift" to "yes"),
    )
    val bytes = ProtoBuf.encodeToByteArray(mine)
    println("kotlinx: ${bytes.size} bytes")

    // read it with the protoc-generated class
    val generated = Order.parseFrom(bytes)
    println("protobuf-java: ${generated.customer} ${generated.status} ${generated.labelsMap} hasNote=${generated.hasNote()}")

    // and the other way around
    val fromJava = order {
        id = 6
        customer = "jack"
        items += lineItem { sku = "BOWL"; quantity = 1; priceCents = 2500 }
        status = Status.STATUS_PENDING
        note = "fragile"
        voucherCode = "X1"   // field 9 is not in SimpleOrder and is skipped
    }
    println(ProtoBuf.decodeFromByteArray<SimpleOrder>(fromJava.toByteArray()))
}

Output:

kotlinx: 34 bytes
protobuf-java: ivy STATUS_SHIPPED {gift=yes} hasNote=false
SimpleOrder(id=6, customer=jack, items=[Item(sku=BOWL, quantity=1, priceCents=2500)], status=PENDING, labels={}, note=fragile)

Things to know:

Integer encodings

Protobuf has several encodings for integers. Plain int32/int64 use varints, which are inefficient for negative numbers: -1 takes 10 bytes. sint32 uses ZigZag encoding, which keeps small negative numbers small, and fixed32 always takes 4 bytes. In kotlinx.serialization you choose with @ProtoType:

@file:OptIn(ExperimentalSerializationApi::class)

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToByteArray
import kotlinx.serialization.protobuf.ProtoBuf
import kotlinx.serialization.protobuf.ProtoIntegerType
import kotlinx.serialization.protobuf.ProtoNumber
import kotlinx.serialization.protobuf.ProtoType

@Serializable
data class Plain(@ProtoNumber(1) val n: Int)

@Serializable
data class ZigZag(@ProtoNumber(1) @ProtoType(ProtoIntegerType.SIGNED) val n: Int)

@Serializable
data class Fixed(@ProtoNumber(1) @ProtoType(ProtoIntegerType.FIXED) val n: Int)

fun ByteArray.hex() = joinToString(" ") { "%02x".format(it) }

fun main() {
    for (n in listOf(1, 300, -1)) {
        println("n=$n")
        println("  int32:   ${ProtoBuf.encodeToByteArray(Plain(n)).hex()}")
        println("  sint32:  ${ProtoBuf.encodeToByteArray(ZigZag(n)).hex()}")
        println("  fixed32: ${ProtoBuf.encodeToByteArray(Fixed(n)).hex()}")
    }
}

Output:

n=1
  int32:   08 01
  sint32:  08 02
  fixed32: 0d 01 00 00 00
n=300
  int32:   08 ac 02
  sint32:  08 d8 04
  fixed32: 0d 2c 01 00 00
n=-1
  int32:   08 ff ff ff ff ff ff ff ff ff 01
  sint32:  08 01
  fixed32: 0d ff ff ff ff

Use sint32/sint64 for fields that are often negative (deltas, offsets) and fixed32/fixed64 for values that are usually large, such as hashes. In a .proto file you pick the encoding with the field type.

Generating a .proto from Kotlin classes

To give other teams a schema for your Kotlin classes, ProtoBufSchemaGenerator writes one:

@file:OptIn(ExperimentalSerializationApi::class)

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.protobuf.ProtoIntegerType
import kotlinx.serialization.protobuf.ProtoNumber
import kotlinx.serialization.protobuf.ProtoType
import kotlinx.serialization.protobuf.schema.ProtoBufSchemaGenerator

@Serializable
data class Reading(
    @ProtoNumber(1) val sensor: String,
    @ProtoNumber(2) @ProtoType(ProtoIntegerType.SIGNED) val delta: Int,
    @ProtoNumber(3) val values: List<Double> = emptyList(),
    @ProtoNumber(4) val unit: String? = null,
)

fun main() {
    val schema = ProtoBufSchemaGenerator.generateSchemaText(
        listOf(Reading.serializer().descriptor),
        packageName = "sensors",
    )
    print(schema)
}

Output:

syntax = "proto2";

package sensors;

message Reading {
  required string sensor = 1;
  required sint32 delta = 2;
  // WARNING: a default value decoded when value is missing
  repeated double values = 3;
  // WARNING: a default value decoded when value is missing
  optional string unit = 4;
}

The output uses proto2 syntax because it can express required fields, which match Kotlin properties without defaults.

Which one to use

protoc + protobuf-kotlin kotlinx.serialization ProtoBuf
Source of truth .proto file Kotlin classes
Code generation yes (Gradle plugin) no (compiler plugin)
Kotlin types Java classes + DSL, no nulls data classes, nullable types
Unknown fields preserved on re-encode skipped
JSON mapping JsonFormat (proto3 standard) separate Json format with its own rules
gRPC yes (grpc-kotlin) no
Platforms JVM, Android JVM, Android, Native, JS, Wasm

Pick protoc when the schema is shared with other languages or used for gRPC; the .proto file then becomes the contract between teams. Pick kotlinx.serialization for Kotlin-only data such as caches, files or Kotlin Multiplatform clients talking to a Kotlin server.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents