← Back to roadmap

Saving and Sharing Strokes: Protobuf, Deltas and Last Writer Wins

How a pen stroke becomes a few hundred bytes and back: Ink's quantised, delta-encoded protobuf, varints and ZigZag, gzip, and what saving loses. Then two devices editing one stroke: last writer wins, tombstones, what a clock can break, and a short look at CRDTs. With two labs: a save lab and a merge lab.

  • Android
  • Storage
  • Protobuf
  • Sync
  • Internals
On this page
  1. What you’ll study
  2. The basics
  3. Try it: the save lab
  4. The high level
  5. The low level
  6. Try it: the merge lab
  7. A short section on CRDTs
  8. Checkpoint
  9. Why it helps
  10. The map
  11. Edge cases
  12. Cross questions
  13. Revision: key points
  14. Cheat sheet
  15. Read next
  16. The fine print

What you’ll study

  1. What has to be saved for a stroke, and why the same stroke takes 11,145 bytes as text and 1,208 as Ink saves it.
  2. How Ink’s storage turns pen samples into numbers that are small: quantising, saving changes instead of values, varints and ZigZag, then gzip.
  3. How protobuf lays those numbers out as bytes, worked by hand on three samples.
  4. What saving loses, and why the loss is smaller on a small stroke than on one that crosses a 4K board.
  5. What happens when two devices edit the same board while apart: last writer wins, per stroke, and the ways a clock can break it.
  6. A short section on CRDTs: what the rule is a case of, and what it can’t do.

How it connects

Guide 5 listed what a pen sample is: position, time, pressure. Guide 6 smoothed and predicted them. Ink saves the samples from before its own stroke modeler, so the stroke can be rebuilt with a different brush; samples your app filtered before giving them to Ink are saved as they were filtered. Guide 7 made a stroke from a brush and samples; this guide saves those two. Guide 9 cut strokes into pieces and removed them, which is the other kind of change a shared board has to carry. Guide 10 put many hands on one board, and guide 11 kept a big board fast; this one keeps it between sessions and between devices.

Read it at your level

Level Read You should be able to
Student The basics, the save lab Say why a stroke saved as text is many times bigger than one saved as Ink saves it
Fresher + The high level Name the four steps from a sample to a byte: quantise, changes, varint, gzip
Junior + Varints, ZigZag, the merge lab Work out the bytes of three numbers by hand, and say which write wins when two devices disagree
Mid + The snippets, tombstones Save and load a stroke with Ink, and stamp writes so every device ends in the same state
Senior + Edge cases, cross questions Say what a stroke’s precision depends on, what a clock can break, and what last writer wins can’t do

The basics

A stroke is a brush and a list of pen samples (guide 7). The brush is a few numbers. The samples are the bulk: at a sample every 4 milliseconds, a 2-second stroke is about 500 of them, and each has a position, a time and a pressure.

Written the obvious way, as text with a number for each, 200 samples take 11,145 bytes. As raw 32-bit floats, four numbers a sample, 3,200. Ink’s storage writes the same samples in 1,208 bytes, about 6 per sample. It gets there with four ideas, each of which the rest of this guide takes apart:

  • Quantise. Round every number to a step, so it is a whole number of steps. The cost is a small error, set by the step.
  • Save the change. Samples are close together, so the step count of each is close to the one before. Store the difference, which is small.
  • Small numbers take few bytes. Protobuf’s varint writes a number below 128 in one byte, and ZigZag keeps a small negative number small.
  • Compress. Ink gzips the result.

Sharing is the second half. When two devices hold the same board and both change it while offline, something has to decide what the board is when they meet. The simplest rule that gives every device the same answer is last writer wins, per stroke: each write carries a timestamp, and the larger one stays. It is simple, and it has sharp edges, which the merge lab is for.

Try it: the save lab

One pen stroke, written four ways. The table shows the bytes each takes, the bytes per sample, and the size after gzip as this browser does it. The line under it is what saving loses. The second table is what is inside the saved bytes, field by field.

Interactive save lab: one pen stroke of 50, 200 or 1,000 samples written as text, as raw floats, as whole quantised steps and as quantised changes (Ink's format), with the bytes each takes before and after gzip, the largest error saving introduces, and the fields inside the saved bytes. Needs JavaScript.

Things to try. Each starts from the lab’s defaults (Samples 200, Stroke size × 1) and names every setting it changes.

  • Text is the biggest. The first row is 11,145 bytes; raw floats are 3,200 (4 numbers × 4 bytes × 200); whole quantised steps are 1,765; quantised changes, Ink’s way, are 1,208, which is 6.0 bytes a sample.
  • Changes beat whole values. Rows three and four use the same rounding. Saving each number whole takes 1,765 bytes and saving the change takes 1,208: the change is small even when the number isn’t.
  • More samples, a little less per sample. Set Samples to 50: 404 bytes for the changes, 8.1 a sample. At 200 it is 6.0, and at 1,000 it is 5,590 bytes, 5.6 a sample. The fall is the fixed bytes (the scales, offsets, tags and seed) being spread over more samples; the floor is the bytes of each sample’s own changes.
  • What it costs. With the defaults, x moves in steps of 0.081 and the worst gap between a sample and what comes back is 0.040: under half a step, which is the most rounding can do. Pressure is off by at most 0.00012 and time by under a microsecond.
  • A big stroke has big steps. Set Stroke size to × 10: x now moves in steps of 0.814, because the steps are the stroke’s box divided by 4,096. This stroke was about 334 units wide, so × 10 is one that crosses a 4K board. The error is relative to the stroke, not to the pixel.
  • The bytes inside. Look at the second table: x, y, time and pressure are each a field, and together they are nearly all of it. The tool type is 2 bytes and the noise seed 5.
  • Gzip helps the least where it is least needed. The last column is this browser’s gzip. When I looked, it took the text from 11,145 to 3,653 bytes (about a third) and Ink’s format from 1,208 to 1,119 (7% less). With Samples at 50 it made Ink’s 404 bytes into 427: a gzip file has a ten-byte header and an eight-byte trailer (RFC 1952), which a small input can’t pay for. I haven’t pinned these, because two gzip implementations can write different bytes for the same input, and the library uses Java’s. The saved format is still far smaller than gzipped text.

The lab is a port of the rules in Ink’s storage code, not the code, and a made-up pen path (a seeded random walk), not a real pen’s.

The high level

Step What it does Where it goes wrong
Sample Position, time and pressure for each pen sample Nothing: these are the inputs Ink was given, from before its own modeler
Quantise Each axis is cut into 4,096 steps across the stroke’s box The error is the step, so it is bigger on a bigger stroke
Change Each number is saved as the difference from the one before One wild sample costs a big number, not a whole stroke
Varint A small whole number takes one byte, a large one up to five Nothing: but a ZigZag keeps small negatives small
Gzip The bytes are compressed The saved size depends on the implementation
Stamp Each edit to a stroke gets a timestamp A clock that is wrong makes the wrong edit win
Merge The device with the larger stamp wins, per stroke The edit that loses is gone, and it can be the one you meant

The low level

Source excerpts are from Jetpack Ink 1.0.0 (ink/storage) and from the protobuf encoding guide, trimmed with …; lines marked [note] are the author’s. Links are in The map.

1. What is saved

The storage module’s README says the at-rest format is gzip-compressed binary protobuf, and that it supports BrushFamily and StrokeInputBatch: the brush, and the pen samples. A stroke is made from those two (guide 7), so they are enough to build it again. A stroke’s samples are a CodedStrokeInputBatch:

// coded_numeric_run.proto
message CodedNumericRun {
  repeated sint32 deltas = 1 [packed = true];
  optional float scale = 2 [default = 1];
  optional float offset = 3;
}

// stroke_input_batch.proto
message CodedStrokeInputBatch {
  // The original (pre-stroke-modeler) sequence of input positions for the stroke, in stroke space. …
  optional CodedNumericRun x_stroke_space = 1;
  optional CodedNumericRun y_stroke_space = 2;
  // Time elapsed for each input point, measured in seconds from the start of the stroke.
  optional CodedNumericRun elapsed_time_seconds = 3;
  optional CodedNumericRun pressure = 4;
  optional CodedNumericRun tilt = 5;
  optional CodedNumericRun orientation = 6;
  optional ToolType tool_type = 7;
  optional float stroke_unit_length_in_centimeters = 8;
  optional fixed32 noise_seed = 9;
}

Every number a sample has is one numeric run: a list of whole numbers (deltas), a scale and an offset. The comment on the samples says they are the original ones, from before Ink’s stroke modeler, which is why a saved stroke can be drawn again with a different brush. Anything your own code did to the samples before handing them to Ink is already in them. Pressure, tilt and orientation are left out when the pen didn’t report them.

2. Quantising

Positions are saved relative to the stroke’s own box, so it doesn’t matter whether the app’s stroke space is pixels or millimetres:

// stroke_input_batch.cc  [note] (the last function comes before the code above it in the file)
constexpr float kInverseEnvelopeXScale = 4096;
constexpr float kDefaultInverseTimeScale = 1e6;  // microsecond resolution
constexpr float kInversePressureScale = 4096;
…
const float inverse_x_scale =
    bounds_semi_width > 0.f ? (0.5f * kInverseEnvelopeXScale) / bounds_semi_width : 1.f;
x_stroke_space->set_scale(1.f / inverse_x_scale);
x_stroke_space->set_offset(stroke_space_bounds.XMin());
…
int ToQuantizedInt(float value, float inverse_scale, float scaled_origin = 0) {
  return static_cast<int>(std::round(value * inverse_scale - scaled_origin));
}

The box’s half-width is mapped to 2,048 steps, so the whole width is 4,096 steps and a step is the box’s width divided by 4,096. Rounding to the nearest step means no value is off by more than half a step. Time is in microseconds (unless the stroke is long enough to overflow a 32-bit count, when the step grows), and pressure in 4,096ths. The code’s own comment says of these constants that they “were picked out of a hat, and should probably be tuned in the future”. [note] That is the source’s wording; it is why the guide says Ink 1.0.0 and not Ink.

3. Changes, and reading them back

The encoder keeps the last whole number of each run and saves the difference, and the decoder adds them up again:

// numeric_run.h
cumulative_delta_ += run_->deltas(index_);
…
value_ = static_cast<T>(run_->offset() + (double)run_->scale() * cumulative_delta_);

Ink’s own decode test shows it on small numbers: a run with scale 0.5, offset 2.5 and deltas 1, −2, 3, 4, 5 reads back as 3, 2, 3.5, 5.5, 8. The lab’s tests use that vector, and the one for a whole batch (x with offset 10 and deltas 0, −3, 1 is 10, 7, 8).

4. Bytes: tags, varints, ZigZag, packed fields

The protobuf encoding guide gives the rules the rest of this section uses. A message is a series of fields. Each starts with a tag, (field number << 3) | wire type, then the value. Wire type 0 is a varint, 2 is a length followed by that many bytes (sub-messages, strings and packed lists), 5 is 4 bytes (a float).

A varint writes a number seven bits at a time, least significant first, with the top bit of every byte but the last set. 1 is 01; 150 is 96 01. A number below 128 takes one byte, below 16,384 two.

ZigZag maps signed numbers to unsigned ones so small negatives stay small: 0, −1, 1, −2 become 0, 1, 2, 3. A sint32 is written as (n << 1) ^ (n >> 31). Without it, a negative number in an ordinary int32 field takes ten bytes, because as an unsigned 64-bit number its high bit is set.

A packed repeated field is written once: a tag, a length, and then the values one after another. The guide’s own example is a message with d = "hello" and e = 1, 2, 3, which is 22 05 68 65 6c 6c 6f 2a 03 01 02 03: tag 4, length 5, the letters, tag 5, length 3, the three numbers.

Now three samples with x = 10, 7, 8 and y = 3, 4, 2. The box of x is 7 to 10, so 3 units are 4,096 steps. 10 is step 4,096 from the offset 7, 7 is step 0 and 8 is step 1,365. The changes are +4,096, −4,096 and +1,365. ZigZag makes them 8,192, 8,191 and 2,730, which as varints are 80 40, ff 3f and aa 15. The whole x field is therefore:

0a 12                    field 1 (x), a sub-message of 18 bytes
   0a 06                    field 1 (deltas), packed, 6 bytes
      80 40  ff 3f  aa 15      +4096, −4096, +1365 as ZigZag varints
   15 + 4 bytes             field 2 (scale), a float: 3 / 4096
   1d + 4 bytes             field 3 (offset), a float: 7

The lab’s tests check these bytes. A packed field in a message with a thousand samples is one tag, one length and the numbers; there is no tag for each sample.

5. Gzip, and the Kotlin side

The Kotlin storage module writes the protobuf and gzips it. In Ink 1.0.0 the calls take a stream; later source also has forms that return a ByteArray.

class SavedStroke(
    val brushFamily: ByteArray,
    val colorArgb: Int,
    val size: Float,
    val epsilon: Float,
    val inputs: ByteArray,
)

private fun bytesOf(write: (OutputStream) -> Unit): ByteArray = ByteArrayOutputStream().also(write).toByteArray()

@OptIn(ExperimentalInkCustomBrushApi::class) // BrushFamily.encode and decode, in Ink 1.0.0
fun Stroke.save(): SavedStroke = SavedStroke(
    brushFamily = bytesOf { brush.family.encode(it) },
    colorArgb = brush.colorIntArgb,
    size = brush.size,
    epsilon = brush.epsilon,
    inputs = bytesOf { inputs.encode(it) }, // gzip-compressed protobuf: quantised, delta-encoded samples
)

@OptIn(ExperimentalInkCustomBrushApi::class)
fun SavedStroke.load(): Stroke {
    val family = BrushFamily.decode(ByteArrayInputStream(brushFamily))
    val brush = Brush.createWithColorIntArgb(family, colorArgb, size, epsilon)
    return Stroke(brush, StrokeInputBatch.decode(ByteArrayInputStream(inputs)))
}

Imports are androidx.ink.storage.encode and decode, java.io streams, and Ink’s brush and stroke classes; the dependency is androidx.ink:ink-storage:1.0.0. A brush that uses textures needs the version of BrushFamily.encode that takes a texture store as well. The brush’s colour, size and epsilon are saved by the app here, beside the family; a board file is a list of these records. The brush family is the same for thousands of strokes, so a real file stores each family once and has each stroke point at it. [note] That is this guide’s design, not Ink’s.

6. Two devices

When two devices change the same board while apart, each stroke is one register: a value with a timestamp. The rule is the LWW-Register of Shapiro, Preguiça, Baquero and Zawirski’s report on CRDTs (section 3.2.1): the timestamps are “assumed unique, totally ordered, and consistent with causal order”, which “may be implemented as a per-replica counter concatenated with a unique replica identifier”. When two copies meet, the merge keeps the entry with the larger timestamp. A board of many strokes is their LWW-element-Set (section 3.3.3): an element is in the set unless there is a remove with a higher timestamp, and merging is the union.

An erase is a write: the stroke’s entry becomes a marker that says erased, with a timestamp. The report calls this a tombstone (section 3.3.2), and notes why it has to be kept: if the erase reaches a device before the stroke it erases, the erase must still win. If the entry is deleted instead, a device that still has the stroke gives it back the next time they meet. The merge lab’s last row is that.

data class Stamp(val time: Long, val replica: String) : Comparable<Stamp> {
    override fun compareTo(other: Stamp): Int = compareValuesBy(this, other, Stamp::time, Stamp::replica)
}

data class StrokeEntry(val id: String, val stamp: Stamp, val colorArgb: Int?) // null colour: erased

class BoardCopy(private val name: String) {
    private val entries = HashMap<String, StrokeEntry>()
    private var counter = 0L

    fun write(id: String, colorArgb: Int?) {
        entries[id] = StrokeEntry(id, Stamp(++counter, name), colorArgb)
    }

    fun receive(theirs: Collection<StrokeEntry>) {
        for (entry in theirs) {
            val mine = entries[entry.id]
            if (mine == null || entry.stamp > mine.stamp) entries[entry.id] = entry
            counter = maxOf(counter, entry.stamp.time) // so the next write is after everything seen
        }
    }

    fun snapshot(): List<StrokeEntry> = entries.values.toList()
    fun visible(): List<StrokeEntry> = entries.values.filter { it.colorArgb != null }
}

The stamp is a counter and the device’s name, as the report suggests. A device that receives a larger counter moves its own counter past it, so a write after a merge is always newer than what it saw. [note] That is a Lamport clock.

Try it: the merge lab

Two devices, A and B, hold the same black stroke, then go apart. Each row is a scenario: what each device does while apart, and what the stroke is when they meet, whichever one receives the other first. Last in real time is what the write that actually happened last said. Choose how writes are stamped, how wrong B’s clock is, and whether an erase is kept.

Interactive merge lab: two devices edit one stroke while apart (recolour, recolour twice, erase against recolour, a stale copy after an erase), stamped by counters or by wall clocks with an adjustable error, with erases kept or forgotten, and a table of what the stroke ends as and whether that is the write that was last in real time. Needs JavaScript.

Things to try. Each starts from the lab’s defaults (Timestamps are Counters, An erase is Kept) and names every setting it changes.

  • Every row ends in agreement. Both devices show the same stroke after meeting, in every row, with every setting. That is what the merge rule is for.
  • Agreement isn’t the last write. Row 2, A is last: the stroke ends blue, though A recoloured it later. Each device’s counter was 2, and the tie is settled by the name, B. Row 3, A recolours twice: it ends green, A’s second write, though B wrote last: A’s counter reached 3.
  • Wall clocks with the right time. Set Timestamps are to Wall clocks, with B’s clock off by 0: every row ends with the write that was last in real time.
  • A clock that is a little wrong. With Wall clocks, set B’s clock off by −10: row 1 still ends blue, as 10 and 10 tie and the name settles it. Set it to −11: row 1 ends red, and row 4 ends erased, though B recoloured later. Set it to +11: row 2 ends blue, though A was last.
  • A clock that brings a stroke back. With Wall clocks, B’s clock off by −11, the last row ends black: B’s erase is stamped earlier than the stroke’s own creation, so it loses, and the erased stroke is back. At −10 it ends erased.
  • Forgetting an erase. Set An erase is to Forgotten, with Wall clocks and B’s clock off by 0: the last row ends black. B forgot the stroke, A still had it, and both devices agree on the wrong answer.

The lab is the report’s rule written for a stroke with one thing that can change, its colour. It has no network, no third device and no stroke order.

A short section on CRDTs

A CRDT is a data type designed so that copies that have each seen the same updates are in the same state, whatever order the updates arrived in. The state-based kind needs a merge that is commutative, associative and idempotent: merge in any order, or twice, and the result is the same. The report says the merge of its state-based types is a least upper bound, which is those three. The lab’s tests check them for the stroke rule, on random edits, with either clock.

Strokes suit it because a stroke’s points never change after it is drawn. The things that do change are small: a colour, a position if it is moved, and whether it exists. Each is a register, and the board is a set of them. Guide 9’s cut fits too: cutting a stroke makes new strokes with new ids and erases the old one.

What it doesn’t give you:

  • The edit you lose is gone. Last writer wins keeps one write and drops the others. For a recolour that is fine. For two people each moving a stroke, one move disappears.
  • Order. Which stroke is on top is the board’s other state. A register per stroke doesn’t decide it; a model of order does, and that is where real systems spend their effort.
  • Clocks. The report’s rule needs timestamps that follow causal order. Counters do, and tell you nothing about real time. Wall clocks tell you about real time and follow causal order only if the clocks are right, which the lab shows.
  • Tombstones stay. The model never drops one, so a board that is erased and redrawn for years only grows. Dropping one is only safe when every copy has seen it, and the model doesn’t track that.

Checkpoint

You should be able to say:

  • A saved stroke is a brush and the original pen samples, enough to build it again.
  • Ink quantises each axis into 4,096 steps over the stroke’s box, so a step is the box’s width over 4,096 and the error is at most half a step; time is in microseconds and pressure in 4,096ths.
  • It saves the change from one step to the next, as ZigZag varints in a packed field, then gzips.
  • A varint is seven bits a byte; 150 is 96 01; ZigZag maps 0, −1, 1, −2 to 0, 1, 2, 3.
  • Last writer wins per stroke keeps the entry with the larger stamp, so every device ends in the same state, and the stamp can be a counter and a device name.
  • An erase is a write that has to be kept, or a stale copy brings the stroke back.
  • Counters give agreement, not real time; wall clocks give real time only while they are right.

Why it helps

Symptom What is happening What to do
A board file is huge Samples saved as text or raw floats Save inputs with Ink’s storage, and gzip the file
Strokes shift slightly after a reload Saving quantised the samples That is half a step at most; check the step if strokes are very large
A very long stroke has moved a little after a reload The step is the stroke’s box over 4,096: in the lab, a stroke across a 4K board is off by up to about 0.4 px Accept it, or split very long strokes
A recolour vanished after sync Last writer wins dropped it Tell the user, or give that property a rule that merges both
An erased stroke came back An erase was forgotten, or a clock was behind Keep the erase as an entry; prefer counters, or fix clocks before stamping
Two devices show different boards The merge isn’t commutative, or one device missed an update Make merge a function of the two states only, and send state again
An old app can’t read a new file A field was added An old parser skips a field it doesn’t know by its wire type; test an old build against a new file

The map

Topic Code Where
What storage supports, gzip The module’s README ink-storage/README.md
Encode and decode a batch StrokeInputBatch.encode, decode StrokeInputBatchExtensions.jvmAndAndroid.kt
A brush family BrushFamily.encode, decode BrushFamilyExtensions.kt
Quantising, deltas EncodeStrokeInputBatch stroke_input_batch.cc
Decoding a run CodedNumericRunIterator numeric_run.h
The messages CodedNumericRun, CodedStrokeInputBatch stroke_input_batch.proto
Varints, ZigZag, packed fields The wire format Protobuf encoding
Last writer wins, tombstones LWW-Register, 2P-Set, LWW-element-Set Shapiro et al., Inria RR-7506

Edge cases

  • Precision is relative. The step is the stroke’s box over 4,096 in each axis, so a tall thin stroke has a fine step in x and a coarse one in y, and the step changes if the stroke does.
  • A saved stroke is the samples Ink was given. They are from before Ink’s own modeler, and the stroke is rebuilt by the brush each time it is loaded. If your app filters samples (guide 6) before giving them to Ink, the filtered ones are what is saved.
  • Gzip bytes differ. The lab uses the browser’s gzip and the library Java’s. The decoded stroke is the same; the byte count may not be.
  • Old readers. The protobuf guide says the wire type lets an old parser skip a field it doesn’t know, so a file with a new field can still be read by an old app. Changing a field that already exists is a different matter, and this guide doesn’t cover it.
  • The last one wins, twice. The protobuf guide says that if a singular field appears twice in the bytes, the parser keeps the last it sees. That is order in the bytes, nothing to do with time, and has no connection to the merge rule here.
  • Counters need saving. A device that forgets its counter after a reinstall can write stamps lower than ones it wrote before. Keep it with the board.
  • Version differences. This is Ink 1.0.0 for the API and Ink’s main for the README and the byte-array forms, read on 17 November 2026.

Cross questions

Why not save the mesh instead of the samples?

The samples are what a brush needs to make the mesh again, with a different brush or a different smoothing, and Ink's README lists a brush family and a batch of samples as what its storage supports. I haven't measured a mesh's size against its samples'. The tradeoff of saving samples is time on loading: every stroke is built again from them.

How much does quantising lose?

At most half a step in each number. A step is the stroke's box divided by 4,096, so a stroke 334 units wide moves in steps of 0.081 and is off by 0.040 at worst in the lab, and one ten times wider is off by up to 0.41. Time is rounded to a microsecond and pressure to a 4,096th.

Why save changes instead of values?

Because the changes are small and small numbers are cheap in a varint. The lab's stroke takes 1,765 bytes saved as whole steps and 1,208 as changes, from the same rounding.

What is ZigZag for?

A change can be negative, and a negative number in a plain varint is always ten bytes. ZigZag maps −1, 1, −2 to 1, 2, 3, so a small change in either direction is one byte.

Why does the merge need a replica name in the stamp?

Two devices can stamp writes with the same counter, and the merge must still pick the same one on both. The report asks for timestamps that are unique and totally ordered, and suggests a counter with a replica identifier. The name only settles ties; it says nothing about which write was later.

Why not just use the wall clock?

It gives the write that was last in real time while the clocks are right. A device a few seconds off makes the wrong write win, as the lab shows from 11 seconds in its scenarios, and a device far enough behind can make an erase older than the stroke it erases.

Why keep an erase?

A device that still has the stroke will send it back at the next merge. If the erase is an entry with a higher stamp, the stroke loses; if the erase was deleted, nothing says it should.

Is last writer wins a CRDT?

Yes: the report specifies the register and the set, and says their merge is the least upper bound. It is the simplest one, and the cost is the writes it throws away.

Revision: key points

  1. A saved stroke is a brush and the original pen samples; Ink’s storage saves both, and a stroke can be built again from them.
  2. Each number is quantised: positions into 4,096 steps over the stroke’s box, time in microseconds, pressure in 4,096ths. The error is at most half a step.
  3. Each run is saved as changes from the one before, as ZigZag varints in a packed field, then gzipped; the lab’s stroke is 11,145 bytes as text and 1,208 as Ink saves it.
  4. A varint is seven bits a byte, 150 is 96 01, and ZigZag maps 0, −1, 1, −2 to 0, 1, 2, 3.
  5. Last writer wins per stroke keeps the entry with the larger stamp; a stamp is a counter and a device name, and every device ends in the same state.
  6. An erase is a write that is kept as a tombstone, or a stale copy brings the stroke back.
  7. Counters give agreement and not real time; wall clocks give real time only while they are right.
  8. The edit that loses is lost, and the order of strokes is not decided by any of this.

Cheat sheet

Each concept in a few words.

Concept In a few words
Protobuf A compact binary format: numbered fields, each with a tag.
Tag Field number and wire type in one varint.
Varint A number in 7-bit pieces; small numbers take one byte.
ZigZag Maps 0, −1, 1, −2 to 0, 1, 2, 3 so small negatives stay small.
Packed field A list written as one tag, one length, and the values.
Quantise Round to a step; the error is at most half a step.
Delta encoding Save each number as the change from the one before.
Stroke step The stroke’s box width divided by 4,096.
Gzip Compression applied to the saved bytes.
Last writer wins Of two writes, the larger timestamp stays.
Tombstone An erase kept as an entry, so old copies can’t bring it back.
CRDT A type whose merge gives the same state in any order.

Search terms that find more: protobuf varint zigzag, delta encoding quantization, Ink storage CodedStrokeInputBatch, last write wins register, LWW-element-Set, tombstone CRDT, Lamport clock, state-based CRDT merge.

The fine print

The Ink storage sources were read on 17 November 2026: the C++ (ink/storage) from the google/ink 1.0.0 source tree (the links go to its main, which may have moved on), and the Kotlin API and README from the androidx-main branch; the Kotlin snippets compile against androidx.ink:ink-storage:1.0.0, which takes streams rather than the byte-array forms in main, and were linted at minSdk 26 with no findings; they were not run on a device. The protobuf rules and their worked examples are from the protobuf encoding guide. The CRDT report was read in sections 3.2.1, 3.3.2 and 3.3.3 and its statement about merge; the rest was not read. The save lab is a TypeScript port of Ink’s quantising and the protobuf wire format for x, y, time, pressure, tool type, unit length and noise seed (tilt and orientation work as pressure does and are not modelled); its tests use the protobuf guide’s examples and Ink’s own decode tests, and the encoder’s bytes were worked by hand, because Ink publishes no byte vectors for it. The pen path is a seeded random walk, not a pen. Gzip sizes are the browser’s. The merge lab is the report’s rule written for one stroke with one changing property, tested for the properties the report claims (commutative, associative, idempotent) and for the outcomes quoted above, with no library to check against. Nothing was run on a device or a panel. The page was checked in the built-in browser pane in dark theme, and every “Things to try” number was read back from the page. The light theme, narrow widths and a phone were not checked.

Part of the ink series: 1. Why naive drawing feels bad, 2. Canvas, Paint and Path, 3. Looper, epoll and vsync, 4. From glass to your app, 5. Reading a MotionEvent, 6. Smoothing and predicting the pen, 7. From points to a stroke mesh, 8. Drawing with low latency, 9. The eraser, 10. Many hands on one board, 11. Big boards, slow GPUs.

How useful was this guide?

Only the author sees ratings.

Friday's 5 best, plus one guide

The Friday email is on its way. Until then, follow by RSS.