Chapter 02 / 10 · Foundations

Bits, numbers and text

A total that went negative, an average that stopped moving and a title that turned into “Café”: three representation edges, found the hard way.

This chapter lets you choose a representation for a number or a piece of text knowing where it breaks. Every representation has an edge. The work is to find it in advance and decide whether your data will ever reach it.

hitcount stores three kinds of value. There are counters: views per page and the total across the blog. There are measurements that become averages: time on page, reported in milliseconds. And there is text: page paths and post titles. The code in the previous chapter uses 64-bit integers for all the numbers. The first draft did not, and in its first year three bug reports came in. The total on the stats page went negative. The blog-wide average reading time drifted for a few days and then stopped changing. And a post called “Café culture in Lisbon” appeared in the sidebar as “Café culture in Lisbon”. Each one is a representation meeting its edge.

How many views fit in a counter

A group of n bits has 2ⁿ possible patterns, and a type is an agreement about which number each pattern means. With 8 bits there are 256 patterns. Read as unsigned, they mean 0 to 255. Read as signed, the machine uses two’s complement: the top bit counts as −128 instead of +128. So 0111 1111 is 127, and 1000 0000 is −128. The scheme has a useful property: the same adding circuit works for signed and unsigned numbers, and −1 is simply all ones, so −1 + 1 wraps neatly to zero. It also has a consequence. Add one to 127 and the bits become 1000 0000, which is −128. Nothing in the hardware complains.

The first draft of hitcount declared total as an int32, reasoning that no blog gets two billion views. A signed 32-bit integer holds up to 2,147,483,647. At the ordinary rate of 50 hits a second, the counter reaches that in 2,147,483,647 ÷ 50 ≈ 43 million seconds, about 497 days. Every test passed. The service would have failed sixteen months after launch, on whatever day happened to be next. A viral week shortens the fuse: at 2,000 hits a second it is 12.4 days.

What happens at the edge depends on the language. Go and Java wrap silently, so the stats page shows −2,147,483,648 and starts counting upward from there. Rust panics on overflow in debug builds and wraps in release builds unless you use its checked arithmetic. In C, signed overflow is undefined behaviour, which means the compiler is allowed to assume it never happens and optimise accordingly, so the result can be stranger than a wrap. Python integers grow as needed and never overflow, at the cost of being objects on the heap rather than raw machine words. This is not a hypothetical failure. In 2014 YouTube reported that a music video had passed the largest view count its 32-bit counter could hold, and moved view counts to 64-bit integers.

The fix is int64. Its maximum is about 9.2 × 10¹⁸, and at 2,000 hits a second that lasts roughly 146 million years. The cost is four more bytes per counter: for two thousand pages, eight kilobytes. We write the decision down so it can be challenged: every counter of events in the world is a signed 64-bit integer, because the extra bytes are negligible and the alternative fails on a date nobody can predict.

Predict first

A moderation tool removes bot traffic after the fact with p.Views -= botHits. Someone declared Views as uint32, reasoning that a view count can never be negative. A page has 3 recorded views, and the tool decides 5 of them were bots. What does the sidebar show next?

Show the worked answer

3 − 5 in unsigned 32-bit arithmetic wraps to 2³² − 2, which is 4,294,967,294. The page jumps to first place in the sidebar with four billion views.

An unsigned type does not make “cannot be negative” true. It makes a negative result turn into a very large positive one, which is usually harder to notice than a negative number would have been. The fix is a signed type plus an explicit rule at the point of subtraction (clamp at zero, or refuse to remove more than was recorded), so the invariant is enforced by code rather than hoped for by a type.

Why the average reading time stopped moving

The second bug came from a field declared float32 “to keep the struct small”: a blog-wide running sum of reading time in milliseconds, divided by the number of reports to give the average shown on the stats page.

A floating-point number stores a value as a significand times a power of two, much like scientific notation in base 2. A float32 has 1 sign bit, 8 exponent bits and 23 fraction bits, which with an implied leading 1 gives 24 bits of precision. A float64 has 1, 11 and 52, giving 53 bits. The number of significant bits is the same at every scale, so the gap between one representable value and the next grows as the values grow. Between 2²⁴ and 2²⁵ the gap for a float32 is 2. The number 16,777,217 cannot be stored at all, and 16,777,216 + 1 rounds back to 16,777,216.

Now apply that to the sum. The blog gets about 50 reports a second, or 4.3 million a day, averaging around 45 seconds each. That adds about 1.9 × 10¹¹ milliseconds to the sum per day. When you add a small value to a large float, the result is rounded to the nearest representable number, so each 45,000 ms report is effectively rounded to a multiple of the current gap.

After a few hours the sum is past 2³⁴, and the gap is 2,048 ms. Each report is rounded by up to a second; the average is already slightly wrong. By the end of the first day the sum is near 2³⁷, the gap is 16,384 ms, and a 45,000 ms report becomes 49,152, nearly 10% high. A day later the gap is 32,768, and the same report rounds down to 32,768, 27% low. Past 2³⁹ the gap is 65,536 ms, and 45,000 rounds up to a full 65,536. Then, once the sum passes 2⁴⁰ (about 1.1 × 10¹² ms, reached in under a week), half the gap is larger than any typical report, so every addition rounds to zero. The sum stops growing while the report count keeps rising, and the average falls a little every day. Nobody had written a line of incorrect logic.

The fix is the representation in the current code: an int64 sum of milliseconds and an int64 count, both exact, divided only when someone asks for the average. An int64 of milliseconds holds about 292 million years. The division produces a float64, which is perfectly adequate for display. The cost is that we had to choose a unit in advance; we cannot record sub-millisecond reading times, and we do not want to.

The other famous float fact belongs here too. Most decimal fractions have no exact binary form, in the same way 1/3 has no exact decimal form. So 0.1 + 0.2 evaluates to 0.30000000000000004 in every language that uses IEEE 754 doubles. Two consequences follow. Do not compare floats with ==; compare within a tolerance that suits the quantity. And do not store money in floats. If hitcount ever billed advertisers per view, the bill would be kept in integer minor units (cents or paise) or a decimal type, because an invoice that drifts by rounding is wrong in a way accountants will find.

Numbers that cross into JavaScript

The stats dashboard is written in JavaScript, and a later version of hitcount gives each page a 64-bit ID derived from a hash of its path, so the dashboard can link to /page/<id>. The IDs travel in JSON. JavaScript’s ordinary number type is a float64, and a float64 represents integers exactly only up to 2⁵³, which is 9,007,199,254,740,992. A hash spread over 64 bits is usually much larger than that.

So the dashboard parses 13754893227394560123 as the nearest double it can represent, 13754893227394560000, builds a link with it, and the link returns 404. Most links are broken; occasionally two pages even round to the same ID. View counts are not affected, because they will never approach 2⁵³, which is exactly why the bug went unnoticed in testing on small numbers. The fix is to send IDs as strings. The cost is modest: clients must treat the ID as an opaque token, and they cannot do arithmetic on it, which they should never have wanted to do with an identifier anyway.

Text is bytes plus an agreement

Unicode gives every character a number, its code point, written like U+00E9 for é. An encoding decides which bytes carry those numbers. UTF-8 is the encoding the web settled on, and its design is worth knowing because it explains the failures. Code points 0 to 127 are one byte, identical to ASCII. Code points up to U+07FF take two bytes, shaped 110xxxxx 10xxxxxx. Larger ones take three or four bytes. Continuation bytes always begin with 10, so a decoder can tell where a character starts, and no byte inside a multi-byte character can be mistaken for an ASCII character such as / or ?.

characterscode pointsUTF-8 bytesread as Latin-1CU+0043aU+0061fU+0066éU+00E9 = 000 1110 1001430100001161011000016601100110C3110·00011A910·101001Cafésame five bytes · one decoder sees 4 characters, the other sees 5
Fig 1 · “Café” as characters, code points and UTF-8 bytes, and what a Latin-1 decoder makes of the same bytes

The figure shows the sidebar bug. é is U+00E9, binary 000 1110 1001. Split into five bits and six bits, it fills the two-byte pattern as 11000011 10101001, which is C3 A9. The script that imported titles from the content system read its export as Latin-1, an older encoding where every byte is one character. Latin-1 maps C3 to à and A9 to ©. The bytes were never damaged; they were read under the wrong agreement. That is all mojibake ever is.

It becomes damage if the wrongly decoded text is saved back. Encode “Café” as UTF-8 and you get C3 83 C2 A9 for the last two characters, and the original bytes are now buried under a second encoding. Repair means knowing exactly which wrong conversions happened, in which order. The defence is unglamorous: state the encoding at every boundary where bytes become text, including HTTP Content-Type headers, database column definitions and file readers, and never let a library guess.

A second bug hid in the sidebar’s title truncation. To keep the sidebar tidy, someone wrote title[:40]. In Go that slices bytes, not characters. When the 40th byte fell between C3 and A9, the sidebar received a string ending in half a character. That is invalid UTF-8, and browsers render it as the replacement character, a question mark in a diamond. Slicing by code points fixes that case, but not all of them, because what a reader calls one character can be several code points.

TextUTF-8 bytesCode pointsJS .lengthCharacters a reader sees
Cafe4444
Café, é as one code point (NFC)5444
Café, e + combining accent (NFD)6554
👨‍👩‍👧 (family emoji)18581

The family emoji is three person emoji joined by two invisible “zero-width joiner” characters. Each emoji takes four bytes in UTF-8 and each joiner three, giving 18 bytes. JavaScript strings count UTF-16 units, where each emoji takes two and each joiner one, giving 8. A reader sees one picture. The unit a reader perceives is called a grapheme cluster, and truncation for display should happen on those boundaries, using a Unicode-aware library. The cost is a dependency on Unicode’s tables, which change as Unicode adds characters.

The table’s middle rows lead to the bug that cost the most counts. The same post can reach hitcount as /posts/café with é as one code point, or as e followed by a combining accent, depending on the reader’s operating system and keyboard. It can also arrive percent-encoded (%C3%A9), with lower-case hex, or with a tracking query string attached. hitcount used the raw path as its map key, so it kept several counters for one post. Each held a fraction of the views, and none was large enough to reach the top ten.

The fix is to put every path into one canonical form before it becomes a key: decode the percent-encoding, normalise to NFC, drop the query string, and drop a trailing slash. The cost is that canonicalisation is a claim that two different inputs mean the same thing. Get the rules wrong and you merge pages that differ; we do not lower-case paths, for example, because the blog treats /posts/Go and /posts/go as different posts. The operating system chapter returns to this fix, because without it a crawler can make hitcount’s map grow without limit.

Byte order when a counter leaves the machine

One more agreement matters when numbers are written as raw bytes rather than as text. A 64-bit integer is eight bytes, and machines disagree about which byte comes first. x86 and most ARM systems store the least significant byte first (little-endian); network protocols traditionally send the most significant first (big-endian). hitcount’s snapshot file is JSON, which writes numbers as decimal text and so never meets the question. If we switched to a binary snapshot for speed, the format would have to state the byte order, and the code would write it explicitly (Go’s encoding/binary makes you choose), rather than dumping memory as it happens to be laid out. Formats such as Protocol Buffers exist partly to pin these details in writing.

The representations hitcount settled on

ValueRepresentationWhyWhat it costs
Views, totalint64exact; lasts geological time at our rate8 bytes per counter
Reading timeint64 ms sum + int64 countexact accumulation, no driftunit fixed in advance
Average shownfloat64, computed on readapproximate is fine for displaynever compared with ==
Page ID in JSONstringJS numbers are exact only to 2⁵³clients treat it as opaque
Path used as keycanonical UTF-8, NFC, no queryone counter per postcanonical rules must be right
Title for displayUTF-8, truncated on graphemesno half characters on screena Unicode library

When the simple representation is fine

None of this means every number needs a decimal type or every string needs grapheme-aware handling. float64 is the right representation for measurements that are approximate anyway: durations, averages, ratios, sensor readings, the weights of a machine learning model. Decimal arithmetic is slower and needs more code, and it buys nothing when the input was a rounded measurement to begin with. A string that is only ever stored and echoed back does not need normalising.

Revisit the representation when one of these is true: the value is money; the code compares values for equality; a counter could plausibly pass 2³¹; an identifier crosses into JavaScript or another runtime with different number types; or text is truncated, sorted, compared or used as a key. Those are the points where the edge stops being theoretical.

We now know what hitcount’s bytes mean. The next chapter, The machine underneath, asks where those bytes physically sit while the program runs, in registers, caches and main memory, and why the speed of /top depends more on that than on the sorting algorithm it calls.