QuestDB's QWP under the hood: varints, ZigZag and bit packing
How QWP, QuestDB's binary wire protocol, packs lengths, symbol IDs and booleans into as few bytes as possible, and where ZigZag encoding shows up instead: in the Parquet files QuestDB writes.
QuestDB 10.0 introduced QWP, QuestDB's native binary wire protocol, which clients use both to write data and to read query results back. QWP sends data column by column, and on top of that layout it uses a few encodings that make each column smaller.
Part I of this series covered Gorilla delta of delta, the encoding QWP uses for timestamps. Instead of each timestamp, it sends how much the gap between rows changed, and when rows arrive at a steady pace that change is zero and costs one bit. Timestamps get that special treatment because the next one is usually predictable from the last two.
Everything else in a QWP frame, the lengths, counts, symbol IDs, booleans and nulls, uses encodings that assume much less about the data. Two of them do a lot of work: bit packing and varints. A third, ZigZag, is defined in the spec, but when I went looking for the field that uses it, there wasn't one, and the reason is a good way to understand what ZigZag is for. It does show up elsewhere in QuestDB: when a partition is written as Parquet, the designated timestamp is encoded with all three.
Bit packing: eight booleans in a byte
A boolean is one bit of information, and a byte per boolean wastes seven. QWP
packs BOOLEAN columns eight values to a byte, with the first row in the lowest
bit:
The passive column in the fx_trades table on
demo.questdb.com says whether each trade was the
passive side of the match. A thousand rows of it take 125 bytes on the wire,
against 1,000 bytes at one byte per value, which is how QuestDB stores a
BOOLEAN column on disk.
The same packing carries nulls. Every column in a QWP frame starts with a one-byte null flag. If the column has no nulls in this batch, the flag is zero and the values follow directly. If it has any, the flag is set and a null bitmap follows, one bit per row, packed the same way as the booleans above:
| Null marker for 1,000 rows | Size |
|---|---|
| One byte per row | 1,000 bytes |
| One bit per row, as QWP sends it | 125 bytes |
The values after the bitmap skip the null rows entirely, so a null DOUBLE
costs one bit instead of an 8-byte placeholder. The bitmap pays for itself once
a 1,000-row batch has about 16 nulls, and a batch with none doesn't send one.
Varints: small integers in fewer bytes
Most integers in a protocol are small. A table name is a few dozen bytes long, a batch has a few thousand rows, a symbol column has a few hundred distinct values. Written as a fixed 64-bit integer, the number 3 costs the same 8 bytes as the number 3 billion.
A varint spends bytes in proportion to the size of the number. It splits the
value into 7-bit groups, sends the lowest group first, and uses the eighth bit
of each byte as a flag: 1 means another byte follows, 0 means this is the
last one. Here's 300:
This flavour is unsigned LEB128, the same one Protocol Buffers, WebAssembly and the DWARF debugging format use. The cost goes up a byte every seven bits:
| Value | Bytes |
|---|---|
| 0 to 127 | 1 |
| 128 to 16,383 | 2 |
| 16,384 to 2,097,151 | 3 |
| Up to 264 - 1 | 10 |
QWP uses varints for every length and count in a frame: the table name length, the row count, the column count, the length of each column name, and the size of each new symbol dictionary entry. Queries going the other way use them for the SQL length, batch sequence numbers and row counts.
Column values are a different matter. LONG, INT and DOUBLE columns go on
the wire at their native width, and the Java client copies each one from its
buffer in a single block. A varint per value would turn that copy into a loop
with a branch on every byte, and values in a LONG column are rarely small
enough to save anything.
Symbol IDs on a real FX feed
The one column type that does travel as varints is SYMBOL. QWP sends each
distinct symbol string once per connection, in a dictionary section at the start
of the frame, and from then on every row refers to it by an integer ID. That
dictionary is shared by every symbol column of every table on the connection,
and IDs are handed out in the order the client first sees each string.
To see what that costs I replayed the first 10,000 rows of one day of
fx_trades on demo.questdb.com through the same ID
assignment the Java client does, in batches of 1,000 rows. The demo keeps only
the most recent month of this table, so the rows change from day to day and a
rerun gives slightly different numbers, but the shape stays the same: four
symbol columns, with 30 currency pairs, 4 ECNs, 2 sides and 2,000
counterparties. By the tenth batch:
| Column | Distinct values | Varint IDs | As 4-byte integers | As raw strings |
|---|---|---|---|---|
symbol | 30 | 1,210 bytes | 4,000 bytes | 6,000 bytes |
ecn | 4 | 1,000 | 4,000 | 5,436 |
side | 2 | 1,000 | 4,000 | 3,482 |
counterparty | 2,000 | 1,954 | 4,000 | 20,000 |
| Total | 5,164 | 16,000 | 34,918 |
The counterparty IDs mostly need two bytes, because there are more than 127 of
them. The less obvious one is symbol: only 30 values, but some currency pairs
first appeared after the counterparties had used up IDs 0 to 127, so they got
two-byte IDs too. Order of first appearance matters when one dictionary serves
every column.
The dictionary itself costs bytes as well. The first batch carried 818 new strings, 16,670 bytes of dictionary. By the tenth only 10 counterparties were new and the dictionary section was down to 213 bytes, so the four symbol columns took about 5.4 KB per thousand rows against 35 KB as raw strings.
Why a varint can't hold a negative number
Varints work on unsigned numbers, and a negative number in two's complement is not small at all. -1 as a 64-bit integer is sixty-four 1 bits. Read as unsigned, that's the largest value there is, and as a varint it costs the full ten bytes, two more than the fixed-width form it was meant to improve on.
Protocol Buffers ran into this early on. Its plain int64 field type sends
negative numbers in ten bytes, which is why it also has sint64, which applies
ZigZag encoding first.
ZigZag: interleaving negatives and positives
ZigZag maps signed integers onto unsigned ones by alternating between them:
A number that's small either side of zero becomes a small unsigned number, and a small unsigned number is a short varint. The whole thing is two operations:
def zigzag_encode(n): # 64-bitreturn (n << 1) ^ (n >> 63)def zigzag_decode(z):return (z >> 1) ^ -(z & 1)
Shifting left moves the value up a bit and leaves bit 0 free. The arithmetic shift right by 63 is all zeros for a positive number and all ones for a negative one, so the XOR does nothing to a positive number and flips every bit of a negative one. For -3 in eight bits:
n = 11111101 -3n << 1 = 11111010n >> 63 = 11111111 all ones, because n is negativeXOR = 00000101 5
Positive numbers end up even, negative numbers end up odd, and -3 sits at 5, between 2 and 3.
ZigZag varints on eighteen real trade timestamps
The eighteen trades timestamps we
compressed with Gorilla in the first post
are a good test, because their delta of delta values are small numbers on both
sides of zero. There are sixteen of them: nine zeros, two -1s, and five changes
of about a millisecond, three of them negative. Here's what each value costs as
a plain varint, as a ZigZag varint, and in Gorilla:
| Delta of delta (microseconds) | Rows | Unsigned varint | ZigZag varint | Gorilla |
|---|---|---|---|---|
| 0 | 9 | 1 byte | 1 byte | 1 bit |
| -1 | 2 | 10 bytes | 1 byte | 9 bits |
| -1,001, -1,000, -999 | 3 | 10 bytes | 2 bytes | 16 bits |
| +1,000, +1,001 | 2 | 2 bytes | 2 bytes | 16 bits |
| Total, all 18 timestamps | 632 bits | 296 bits | 235 bits |
ZigZag more than halves the varint cost. Gorilla still wins on these rows, because it works in bits rather than bytes and a zero costs it one bit, where a varint can't go below eight.
That isn't always the case. On a longer run of the same feed, most delta of delta values are bigger than about two milliseconds, which puts them in Gorilla's 36-bit bucket, while a ZigZag varint holds anything up to about a million in three bytes. There's a full comparison further down.
Why QWP doesn't use ZigZag
The QWP spec defines ZigZag in its
encoding primitives,
and the server has a QwpZigZag class, but no field on the wire uses it. Every
varint in QWP is a length, a count, a sequence number or an ID, and none of those
can be negative. The Java client's varint writer checks this rather than relying
on it:
assert value >= 0 : "unsigned LEB128 varint requires a non-negative value: " + value;
The one place QWP carries signed integers is inside Gorilla's buckets, and there it doesn't need ZigZag either. The label in front of each value already tells the decoder how many bits follow, so the value is stored as a plain two's complement number of that width and the decoder sign-extends it. ZigZag solves a problem specific to formats where the size of a number depends on its value. Inside a fixed-width field, the sign bit is enough.
Where QuestDB uses ZigZag: Parquet's delta binary packed
When QuestDB writes a partition as Parquet, it encodes the designated timestamp
column with DELTA_BINARY_PACKED unless you
choose another encoding.
That encoding uses varints, ZigZag and bit packing together:
The header is three unsigned varints and the first timestamp as a ZigZag varint, since the format allows any 64-bit value there. After that, the deltas between consecutive timestamps go in blocks of 128. For each block the encoder finds the smallest delta, writes it as a ZigZag varint, and subtracts it from every delta in the block. What's left is never negative, so it can be bit-packed at the width of the largest remaining value, with no sign to worry about.
Subtracting the minimum is a second way to deal with negative numbers. Instead of ZigZag-encoding every value, the encoder moves the whole block up so the smallest value is zero, and only the minimum itself, which can still be negative, needs ZigZag. On a timestamp column sorted ascending the deltas are never negative in the first place, but the format has to allow for columns that aren't.
The Parquet format allows each block to be split into several miniblocks with their own bit widths. QuestDB's writer uses one miniblock per block, so all 128 deltas share a width.
ZigZag also turns up in the footer of every Parquet file, because Parquet's metadata is written with Thrift's compact protocol, which stores signed integers as ZigZag varints.
Gorilla, ZigZag varints and delta binary packed on the same timestamps
The same timestamp column now has three ways to encode it: Gorilla on the QWP wire, ZigZag varints of the delta of delta, and delta binary packed in Parquet. Here are all three on the same data, in bits, before any compression codec runs on top:
| Timestamps | Plain | Gorilla | ZigZag varints | Delta binary packed |
|---|---|---|---|---|
18 trades, one burst | 1,152 | 235 | 296 | 1,392 |
1,000 trades, µs | 64,000 | 29,079 | 20,456 | 21,224 |
1,000 fx_trades, ns | 64,000 | 35,889 | 28,368 | 28,976 |
1,000 rows of SAMPLE BY 1s, with gaps | 64,000 | 6,026 | 10,512 | 21,480 |
| 1,000 seconds, no gaps | 64,000 | 1,126 | 8,112 | 360 |
Each encoding wins somewhere, and the reason is where each one pays.
Gorilla pays per value. One missing second costs it two 36-bit values and
the next row is back to one bit, which is why it wins clearly on the sampled
series with gaps. What costs it is a gap that changes by more than about two
milliseconds from one row to the next. The 1,000 trades rows span two minutes,
with trades anywhere from the same microsecond to seconds apart, and 740 of the
998 delta of delta values needed the 36-bit bucket. Denser data helps it: the
eighteen-row burst, all inside five milliseconds, cost 235 bits.
A ZigZag varint pays per value too, but in whole bytes. It can't spend less than 8 bits on a zero, which costs it on the regular series. But it climbs one byte at a time instead of jumping from 16 bits to 36, and on the irregular tick feeds that makes it the smallest of the three.
Delta binary packed pays per block. Every delta in a block of 128 is stored at the width of the largest one, so a single gap of a few seconds widens all of them, and the sampled series with gaps comes out three and a half times bigger than in Gorilla. When nothing in the block varies the width is zero, and a block of 128 timestamps costs 4 bytes. It also has a fixed cost: the packed block is always 128 values wide, so eighteen timestamps come out bigger than the plain form.
That fits roughly how each is used. A QWP batch is often small and arrives all day long, and a lot of it is sampled or scheduled data, so a per-value encoding that does well on short regular runs suits it. A Parquet page holds thousands of rows written once and read many times, with a compression codec on top, LZ4 by default in QuestDB. The table above is before that codec, so the on-disk numbers will be smaller.
Run the numbers on your own tables
This extends the script from part I. It pulls the last thousand timestamps from a table over the REST API and works out all four sizes:
import json, urllib.parse, urllib.requestfrom datetime import datetimeTABLE = "trades" # or fx_trades, for nanosecond timestampsSQL = f"SELECT timestamp FROM {TABLE} LIMIT -1000"URL = ("https://demo.questdb.io/api/v1/sql/execute?query="+ urllib.parse.quote(SQL))# the demo rejects urllib's default User-Agent, so send our ownreq = urllib.request.Request(URL, headers={"User-Agent": "varint-check"})rows = json.load(urllib.request.urlopen(req))["dataset"]EPOCH = datetime(1970, 1, 1)def to_int(s):whole, frac = s.rstrip("Z").split(".")secs = int((datetime.fromisoformat(whole) - EPOCH).total_seconds())return secs * 10 ** len(frac) + int(frac)def varint_len(v): # unsigned LEB128: 7 bits per byten = 1while v > 0x7F:v >>= 7n += 1return ndef zigzag(n): # 64-bit ZigZag, as an unsigned Python intreturn ((n << 1) ^ (n >> 63)) & 0xFFFFFFFFFFFFFFFFdef gorilla_cost(dod):if dod == 0: return 1if -64 <= dod <= 63: return 9if -256 <= dod <= 255: return 12if -2048 <= dod <= 2047: return 16if -2**31 <= dod <= 2**31 - 1: return 36return Nonets = [to_int(r[0]) for r in rows]dods = [(ts[i] - ts[i-1]) - (ts[i-1] - ts[i-2]) for i in range(2, len(ts))]# QWP: Gorilla, or plain 64-bit if any value doesn't fitcosts = [gorilla_cost(d) for d in dods]gorilla = 64 * len(ts) if None in costs else 128 + sum(costs)# the same delta of delta values as ZigZag varintszz_varint = 128 + 8 * sum(varint_len(zigzag(d)) for d in dods)# Parquet DELTA_BINARY_PACKED as QuestDB writes it: blocks of 128,# one miniblock per block, before any compression codecdbp = varint_len(128) + varint_len(1) + varint_len(len(ts))dbp += varint_len(zigzag(ts[0]))deltas = [ts[i] - ts[i-1] for i in range(1, len(ts))]for b in range(0, len(deltas), 128):block = deltas[b:b + 128]width = (max(block) - min(block)).bit_length()dbp += varint_len(zigzag(min(block))) + 1 + 16 * widthprint(f"plain: {64 * len(ts):>7} bits")print(f"Gorilla (QWP): {gorilla:>7} bits")print(f"ZigZag varints: {zz_varint:>7} bits")print(f"delta binary packed: {8 * dbp:>7} bits")
Change TABLE, or change the query to a SAMPLE BY over one of your own
tables, to see which encoding your data favours.
What's on the wire, and where to read more
Between the two parts of this series, that's most of what a QWP frame does to save space. Timestamps get Gorilla, lengths, counts and symbol IDs get varints, booleans and nulls get bit packing, and everything else goes at its native width so it can be copied in one block. The QWP ingress specification has the byte-level layout of every column type, and the egress specification covers query results. To see that side of the protocol on real data, market data replay for backtesting streams a full trading day of US equities back from QuestDB as Arrow batches over QWP. For the Parquet side, Parquet in QuestDB covers conversion, encodings and compression, and One table, three readers shows those files being read by QuestDB, Polars and DuckDB.