hzQR

Get far more into a QR code than it should hold.

The largest QR code there is holds 2,953 bytes. That is not much. A restaurant menu, a train ticket with two legs, a month of hourly temperature readings — all of them blow past it the moment you write them as JSON.

hzQR gets an order of magnitude more through, by giving up the assumption that a code must stand alone. If the reader already knows what kind of thing it is about to read, the code only has to carry what is unique to this particular one.


The idea in one paragraph

Two documents of the same kind — two menus, two invoices, two prescriptions — share almost everything. The same keys, the same boilerplate, the same vocabulary, the same shape. Only the values differ. So: agree on the shape once, in advance, and the code carries the difference. That agreement is a profile, and it comes in two layers that do quite different jobs.


Layer one: the schema

The schema is a shared description of the document's shape. Because both ends have it, the keys are never transmitted at all, and values that come from a known set are sent as a number instead of a word.

Here is a real Swedish receipt, before and after:

before   1,066 characters of minified JSON
after      414 characters

What the schema did to it:

[409188, 0, ["Hemköp Storgatan","556914-3302","Storgatan 31","Härnösand"],
 30004902, "Kassa 4", [[25,1240],[12,3108]], 0, [[1,"Arla Mellanmjölk…

Every key is gone — position carries that meaning now. "KV-409188" became 409188, because the schema knows the receipt number always looks like KV-{n}. The type field became 0, an index into a table of known values. The timestamp became 30004902, minutes since the epoch. The amounts became integers: öre instead of kronor, so no decimal point and no trailing zeros.

Field types are const, int, number, string, bool, enum, datetimeMin, decimal2, pattern, object and array.

The schema is a contract, not a filter. If a document has a key the schema does not describe, or lacks one it does, encoding is refused. That sounds unhelpful until you see the alternative: an earlier version quietly dropped unknown keys, so a 41 kB ticket list "compressed" to 16 bytes and decoded into something else entirely. A schema that does not describe your document belongs to a different profile.


Layer two: the dictionary

Compression works by finding repetition. A single small document has almost none — that is why a 1 kB JSON file barely compresses. But across a hundred documents of the same kind, the repetition is enormous, and it is all in the wrong place: in the other documents, which the decoder never sees.

A shared dictionary fixes that. Both brotli and zstd can be handed a block of bytes before compression starts, and treat it as if it were text that came just before the real input. Anything in that block can be referenced instead of spelled out.

So a dictionary here is not a word list. It is literally a few example documents, concatenated. Here is how one actually begins:

{"venue":"Luleå lunch","menu":"lunch","validFrom":"2026-02-21",
 "currency":"SEK","address":{"street":"Nattviksgatan 24","city":"Östersund"},
 "type":"menu-lunch-sv","lang":"sv","items":[{"no":1,"name":"Ärtsoppa",…

When a new menu is compressed against that, "currency":"SEK","address": is not written out — it becomes a short back-reference. So does "Ärtsoppa", and every other phrase the examples happened to contain.

How a dictionary is built

  1. Collect samples of one kind of document — five is enough to start.
  2. Schema-encode them first, so the dictionary learns the compact form the encoder will actually produce, not the verbose JSON.
  3. Concatenate and keep the last 32 kB.
  4. Measure honestly on a sample that was held out of the dictionary.

That last step matters more than it sounds. Measuring a document against a dictionary that contains that document is meaningless — the compressor simply points at it. Doing so once reported 14 bytes where the truthful figure was 881.

Why 32 kB

Brotli allows a dictionary up to 110 kB, so the cap is a choice. Sweeping it across 100 types, measured on a document no dictionary at any cap had seen:

Dictionary capShare of plain
110 kB54.5 %
32 kB54.5 %
16 kB54.6 %
8 kB57.6 %

110 kB and 32 kB come out identical, which looks surprising until you notice the median dictionary is 8.3 kB. Five samples of one type rarely add up to 32 kB in the first place, so for most of the catalogue the cap never binds and the two settings produce exactly the same file. 16 kB costs a tenth of a point. Only at 8 kB, below the typical dictionary, does truncation start throwing away training material that was doing work.

So 32 kB is chosen as the point where the cap is still a genuine ceiling for the largest types while costing nothing measurable for the rest.

Why dictionaries are versioned and never edited

A brotli raw dictionary is an LZ prefix: back-reference distances are counted from the start of the data. Append one byte to a dictionary and every distance shifts, which silently breaks every code already printed against it.

So dictionaries are immutable. Extending a profile with new samples builds a new version; the old one is kept forever. The payload names the version it was packed with, and a code printed today will still decode in ten years.


The five payload types

TypeThe code carriesNeedsWho can read it from the codeWho learns you read it
Standardthe text as-isany scanneranyonenobody
Packedcompressed data, self-containedan hzQR decoderanyone with a decodernobody
Profileprofile id + compressed datathe decoder plus that profileanyone with the decoder and that profilenobody
Encrypted, fetch-freecodec, profile, a salt and encrypted datathe decoder, the profile and the passwordnobody without the passwordnobody
Encrypted, with a key recorda key id + encrypted datathe decoder, the key record and the passwordnobody without the passwordthe server, every read
Linka short addressconnectivity + the serverthe server, and anyone it tellsthe server, every scan

The last two columns are the ones people skip, and they answer different questions. Three of the five types are self-contained, so the content never leaves the code and nobody learns that you read it — but self-contained does not mean private. Compression is not encryption. Anyone who scans a Packed code and runs a decoder reads it in full, and a Profile code needs only the profile, which is published.

The Link type is a pointer, and whoever runs the server has your content in plain sight. It buys unlimited size and a tiny code; it costs privacy and permanence.

The Encrypted type, and exactly what it does and does not give you

Encryption is now wired, not merely designed, and the body costs nothing: the cipher is length-preserving, so the Base45 body is character for character as long as it would have been in the clear. Only the header changes, and there are two forms with opposite trades.

The fetch-free form, HZ1:F, needs no server, ever. The codec, the profile and a per-code salt travel in the header, so a reader with the profile and the password opens the code offline — with this server gone, for as long as the paper lasts. It costs six characters against a packed code and seven against a profile code; the body is unchanged.

The fetched form, HZ1:E, hides more and depends on the server. The key id replaces the codec letter and the profile id together, so the header is twelve characters where a profile header is thirteen — an encrypted profile code one character shorter than the readable one. Nothing on the paper says what kind of document it is.

One FHIR bundle, measured here, all three forms of the same document:

characters
profile code, readable318
the same, encrypted with a key record317
the same, encrypted fetch-free325

So the two forms answer different questions, and the choice is real:

HZ1:F fetch-freeHZ1:E with a key record
needs the serverneverevery read
survives the server disappearingyesno
document kind visibleyesno
can be revokednoyes
header cost+6 or +7 characters−1 character

In the fetched form the profile id leaves the code, so a bystander with a phone cannot tell a prescription from a train ticket; in the fetch-free form it is back, and they can. What remains visible in both is the prefix and the length — and the length leaks how large the document is and how well it matched its dictionary. The printed symbol's QR version leaks that much with no scanner at all. The body is indistinguishable from random; the envelope and the length are not, and cannot be made so at zero cost.

The password belongs to the profile, not to the code

A pharmacy is given the password for prescriptions once, enters it into its reader, and then scans all day without typing anything. That is why the expensive half of the key derivation is keyed on the profile: scrypt runs once per profile and is cached, and each individual code costs one HMAC instead of another 150–400 milliseconds on a phone. The site's decoder and scanner both remember a password per profile in the browser and ask only the first time they meet that profile.

A shared derivation per profile is not a weakening. Every code of a profile has the same password anyway, so breaking one already breaks all of them — a per-code derivation would have bought nothing against that attacker and cost the caching. The password's own entropy and scrypt's cost remain the entire defence.

Encryption is not part of the profile. A profile is public, shared and immutable; a key is per code, secret and revocable. Putting a key in a profile would mean either a secret published to everyone or a profile nobody else can use. The only coupling runs one way: a profile may demand encryption, and then the encoder refuses to produce a readable code for it.

Three suites, differing in what can be taken back:

SuiteWhat protects itWhat it buys
Password only, fetch-freethe password alonenothing is stored anywhere at all. No key record, no fetch, no server — the reader needs the paper and the password.
Password only, with a recordthe password alonenothing secret is stored, so a stolen server database reveals nothing; the record still has to be fetched.
Password + server keythe password plus 32 bytes held hererevocation — deleting the key record puts every code under it permanently out of service
Password + one-time matrixthe password plus a matrix as long as that one payloadunconditional secrecy against anyone who never gets the matrix, and the matrix can be destroyed on the first read

The password is the part that protects the content, and this is the sentence to read twice. The key record is public, because every decoder has to resolve it or no encrypted code could ever be read. So the server key and the matrix do not keep the content from someone who scanned the code and has a network. Without a password, encryption is obfuscation plus revocability — and that is why the site refuses to encrypt without one. The password is the only secret the server never sees.

What it still does not give you: proof of who wrote the code. Anyone holding the key can mint a code that decodes perfectly, so a pharmacy cannot distinguish a forgery from a genuine prescription. That needs a signature, and a signature is incompressible evidence that has to be transmitted — it cannot be free. The arithmetic is in what we measured.

Two more consequences of growing by zero bytes, both honest rather than unfortunate:

One limit that surprises people: hZqr-E1 refuses payloads under 16 bytes, and a profile whose dictionary fits a document exceptionally well can compress it below that. The dictionary working at its best leaves too little to encrypt.

Only the Profile type needs JSON, because only it has a schema to satisfy. Standard, Packed, Encrypted and Link take whatever you give them — an iCalendar file, a CSV, a vCard, a log, prose. JSON is minified before packing, which is free; everything else is packed exactly as written, because for plain content every byte is content. A 13 kB calendar file with 80 events packs to a 747-character payload and a version 15 code, with no profile involved at all.

The payload grammar:

HZ1:P<K>:<Base45>            packed      K: B = brotli, Z = zstd
HZ1:R<K><ID>[.<V>]:<Base45>  profile     ID = 6 chars, V = dictionary version
HZ1:E<KEYID>:<Base45>        encrypted   KEYID = 6 chars; codec, profile and
                                         dictionary live in the key record
HZ1:F<K><SALT>:<Base45>      encrypted, fetch-free — no profile
HZ1:F<K><ID>[.<V>].<SALT>:   encrypted, fetch-free — SALT = 6 chars, per code
https://host/r/<id>          link

Base45 (RFC 9285) is the final step, the same encoding the EU covid certificate used. Its alphabet is exactly QR's alphanumeric charset, which costs 5.5 bits per character instead of byte mode's 8.

It is worth being precise about why, because the obvious explanation is wrong: Base45 is not a capacity win over raw binary. At version 40/L a QR code holds 4,296 alphanumeric characters or 2,953 bytes, both confirmed by measurement, so:

EncodingFits at version 40/L
Raw bytes, byte mode2,953 B—
Base45, alphanumeric mode2,864 B−3 %
Base64, byte mode2,214 B−25 %

Base45 costs 3 %. What it buys is that the payload stays printable text: it survives any scanner, any clipboard, any text channel, with no binary handling anywhere. Base64 would buy the same thing for 25 %, because its lowercase letters fall outside the alphanumeric charset and force the whole code into byte mode.


The catalogue

Rather than make everyone train their own, 81 dictionaries ship ready to use, together 2.5 MB. They are not named after document types. They were found by clustering documents on what they actually contain, and then kept or discarded by how much each one measurably saved on documents it had never seen.

Dictionaries81
All of them together2.5 MB
What one decoder downloadsone dictionary — never more than 32 kB
Carrying a structure transform30, each chosen by measurement
Payload families covered33
Median payload, held-out920 B → 728 B

Why they are not named after types

An earlier catalogue was: 1,000 profiles, 25 families × 8 subtypes × 5 languages, 9.3 MB. It was replaced because naming lost to measuring.

Against the same held-out documents, 71 content-clustered dictionaries reached a median payload of 330 bytes where the 1,000 type-named ones reached 662, at a quarter of the storage. More tellingly, they still won on the type-named catalogue's own ground — the documents whose types those names were chosen for — 486 bytes against 590.

The reason is that a type name is a guess about which documents resemble each other, and the guess is often wrong in both directions. "JSON" is not one thing: a FHIR resource, a weather forecast and a package manifest share only the braces. Meanwhile documents from unrelated families sometimes share a great deal. Clustering finds the real neighbourhoods; naming imposes imagined ones.

What a dictionary is worth, and when it is worth nothing

Not every kind of document can use one. The gain tracks how much of a document is shared structure rather than unique content:

saving
FHIR clinical JSON69 %
Wikipedia summaries41 %
OpenAPI descriptions29 %
XML, both flavours18–42 %
Markdown documentation8–11 %
Plain prose~0 %

Prose is where it stops. A document that is mostly unique sentences has no shared vocabulary to point at, and no amount of training invents any.

Two things we got wrong here, and corrected

The first catalogue measurements were six points too good, because the harvested corpus was never deduplicated: documents that were near-copies of their own training data appeared on both sides of the split. One family fell from 90.7 % to 8.3 % once that was fixed, and another could no longer be measured at all. The current figures are after the correction.

And a dictionary must be general. One that is the best choice for a single document has memorised it, not learned anything, so a candidate now has to serve many unrelated documents before it earns a place.


What it actually saves

This is the part most compression write-ups fudge, so: one number, measured one way, over three populations. The number is the finished payload's length in characters, divided by the same document's length as a plain packed payload with no dictionary at all. Lower is better. Nothing being measured was in any dictionary.

Measured onDocumentsMedian sizeShare of plain
Synthetic catalogue documents, unseen seed1672.9 kB56.9 %
Hand-written set, written first111.1 kB75.6 %
Hand-written set, never used to fix anything150.9 kB74.6 %

The headline for anyone with real data is the last two: a catalogue profile saves about a quarter. The two sets agreeing to within one point is what makes it trustworthy — the second was written only after every bug the first had exposed was already fixed, so it could not have been tuned against.

Why the synthetic number is so much better, and why to ignore it

56.9 % against 75 % is a big gap, and the obvious suspicion is size: the synthetic documents are three times larger, and bigger documents behave differently. That turns out to explain none of it. Comparing only documents in the same 1–3 kB bucket:

1–3 kB documentsShare of plain
Synthetic51.6 %
Hand-written77.7 %

Same size, 26 points apart. The gap is real and it is the generator: synthetic documents draw their text from a bounded pool of phrases, so a dictionary built from five of them has genuinely seen most of what the sixth will say. Real text does not work that way. Treat 56.9 % as an upper bound that no real corpus will reach.

Size matters too, in the other direction

Separately from all that, the benefit shrinks as documents grow — a long document contains enough internal repetition to compress well on its own, so the dictionary has less left to contribute:

Synthetic documentsShare of plain
1–3 kB51.6 %
3–10 kB61.7 %
over 10 kB79.8 %

The hand-written sets show the same slope: under 1 kB they land at 64–67 %, at 1–3 kB at 78–80 %. A profile is worth most on exactly the documents that most need it — the small ones, where a QR code is a plausible container in the first place.

Best and worst

Within every set the same pattern: structured records gain most, prose gains least. Payload characters for real hand-written documents:

DocumentNo dictionaryWith its profile
ticket-train-en457267 (58 %)
contact-emergency-es453280 (62 %)
receipt-retail-sv646412 (64 %)
report-audit-es1,039877 (84 %)
contract-nda-en1,3171,189 (90 %)

A ticket is almost entirely structure the dictionary already knows. A non-disclosure agreement is unique sentences, and no dictionary can invent redundancy that is not there.

The reference case

The thing this was built for. A 35 kB order list, which is well past every limit a QR code has:

PayloadSmallest QR that fits
Plain compression4,251 charsversion 40/L — the largest code there is
With a profile2,719 charsversion 32/L

35,126 bytes of JSON down to 1,804 compressed bytes, and it decodes bit-for-bit identical.


Implementations

The format exists three times over. All nine encoder-to-decoder combinations are verified to round-trip the same document: each implementation reads what either of the others wrote.

They do not produce byte-identical payloads — the three brotli bindings make slightly different choices, so the Python encoder's output came out 402 characters against the other two's 385 for one test document. That is fine and expected. What has to hold is that every decoder reads every encoder, and it does.

WhereNotes
JavaScriptthe server and web UIzero dependencies
C++command line tool, and the Android corebrotli + zstd via system libraries
Pythonone filezstd needs nothing installed on Python 3.14
ComponentFilesLines
Server81,500
C++ core and CLI3787
Python1553
Web UI4983
Android, Kotlin4509
Android, JNI shim1187

Own code only. The scanner page also carries a vendored QR reader, which is someone else's 10,000 lines and is not counted here.

On the phone

The Android app carries the whole catalogue inside the installation — all 81 dictionaries, unpacked from the APK on first launch. Scanning a catalogue code makes no network call at all; verified in airplane mode. Only a Link code reaches out, and the app says which happened on every result.

There is also a mobile web app at /scan — an installable PWA that works on both Android and iPhone, with camera scanning, photo decoding and paste.

Reading a code that will not read

A frame that fails is usually not unreadable — it is noisy, dim, unevenly lit, or the hand moved. Each has a different remedy and the one that rescues a given frame spoils another, so both scanners keep reading and cycle through six treatments: the frame as it came, several frames averaged, contrast stretched, a 3×3 median against speckle, a hard Otsu threshold, and a local adaptive threshold for uneven light.

Averaging is the one that genuinely needs more than one photo, and it is the strongest. Sensor noise differs in every frame while the code does not, so averaging cancels the noise and leaves the code. Measured across 12 synthetic cases where no single frame could be read at all (Gaussian noise, σ 70 to 120), averaging plus a median plus a stretch read the code in all 12; a bare average managed 5. Six frames beat four, so six is the history depth. A frame taken while the camera moved is discarded rather than averaged in.

The remedies also pay on a single still photo. On deliberately degraded test images, heavy speckle was read only by the median pass, and a washed-out code only after a contrast stretch — in both cases the untouched image could not be read by anything.


Honest limitations


Where the numbers come from

Every figure on this page is measured on documents the dictionaries were never trained on, with the set used to choose what to ship kept apart from the set used to score it.


Source and decoders: the catalogue is public at hugowikstrom/hzqr-catalog under CC0.