Anton ZhiyanovEverything about Go, SQL, and software in general.https://antonz.org/https://antonz.org/assets/favicon/favicon.pngAnton Zhiyanovhttps://antonz.org/Hugo -- gohugo.ioen-usSun, 29 Nov 2026 11:00:00 +0000Go proposal trackerhttps://antonz.org/go-proposals/Sun, 29 Nov 2026 11:00:00 +0000https://antonz.org/go-proposals/Accepted and implemented proposals for the next Go release.I built a Go proposal tracker. It shows proposals already implemented in the upcoming Go version, as well as accepted and "likely accept" proposals. Each proposal includes some metadata and a short summary (2-3 paragraphs). There's also an RSS feed and a weekly digest.

Why

I like staying up to date with what's coming next in Go, but I don't want to dive deep into every proposal unless it really interests me. Right now, there's no easy way to quickly read a summary of a proposal — you usually have to scroll through long issue discussions on Go's GitHub (you might expect the proposal specification to be in the issue description, but too often it's hidden somewhere deep in the comments).

On top of that, the GitHub interface is painfully slow and often takes multiple "Load more" button-of-shame clicks to get to the specification. Finally, the specification itself might be a bit too much to review quickly.

That's why I decided to build a simple proposal tracker for anyone who wants a quick overview of accepted and implemented proposals.

What

The tracker has two main views: condensed (showing only proposal titles and metadata) and full (which also includes a brief description). The summary isn't meant to replace the proposal, of course. If you're interested in a proposal, I encourage you to read the original discussion — the link is in the metadata.

Proposal tracker

There's also a per-release view (here's the one for Go 1.28). It's a way to get a decent understanding of the release contents if you have half an hour to spare.

If you want to be notified about changes (like new proposals being accepted or accepted proposals being implemented), you can subscribe to the RSS feed or sign up for a weekly email digest.

Using Google Groups for a newsletter might seem like an odd choice, but it's refreshingly simple compared to regular newsletter services. The subscriber list is private, and I've turned off the "reply all" feature to avoid accidents.

How

The tracker is based on the proposal review meeting minutes and the issue statuses on GitHub. Proposal statuses are updated weekly based on the meeting minutes and daily based on changes to the issues. All are fetched through the GitHub API.

Proposal summaries are generated by an LLM and reviewed by me before they're published, to make sure there are no hallucinations. Currently, I use Claude Opus 5.5 — its language is a bit robotic, but the summaries are usually quite accurate.

The tracker's site is just plain HTML and CSS, so it should load much faster than GitHub issues. The RSS feed is updated daily. The weekly digest is put together and sent out manually.

Who

I'm the person behind the interactive Go tours for versions 1.22 to 1.26. I'm no longer working on those, but this tracker is another small way I can contribute to the Go community. I hope people find it useful.

Proposal tracker: go.antonz.org

]]>
Probabilistic data structures in Go, part 2https://antonz.org/probabilistic-data-structures-2/Sat, 21 Nov 2026 12:30:00 +0000https://antonz.org/probabilistic-data-structures-2/Binary fuse filter, UltraLogLog, Log-linear histogram, and MinHash.Probabilistic data structures give you approximate answers to questions about the data they handle. Does the set contain a certain item? How many unique items are in the collection? What is the 99th percentile in a stream of numbers? How similar are two sets? Unlike deterministic structures, the answers might not be exact, but in return, you can save a lot of memory.

Previously, we reviewed the following data structures: Bloom filter (for checking if an item is in a set), Count-min sketch (for counting items), HyperLogLog (for counting unique items), T-digest (for finding quantiles), and Top-k (for finding the most frequent items).

In this post, we'll talk about other probabilistic structures and compare them to the ones we've already covered. We'll look at how they work and what kinds of guarantees they provide.

All examples use unsure — a package that implements these structures in Go.

Binary fuse filter • UltraLogLog • Log-linear histogram • MinHash

Binary fuse filter

A binary fuse filter is a set that trades certainty for space, like a Bloom filter1. It can tell you that an item is definitely not in the set, or that it probably is (which might be a false positive). The filter doesn't store the items, so it's much more compact than a regular set.

Unlike a Bloom filter, a binary fuse filter is static: you build it once from all the items, and you can't add more later. In exchange, it uses less memory than a Bloom filter with the same false positive rate. For example, a fuse filter for 1,000,000 items with a 0.39% false positive rate takes 1.13 MB (9 bits per item), while a Bloom filter takes 1.51 MB (12 bits per item).

This makes binary fuse filters a good fit for data that is written once and read many times, like the key set of an immutable file in a database (to skip files that don't have the key), or a list of known bad items, such as leaked passwords or malicious URLs.

items := [][]byte{[]byte("alice"), []byte("bob")}

// An 8-bit filter: 0.39% false positive rate.
filter := fuse.New[uint8](slices.Values(items), len(items))

filter.Contains([]byte("alice")) // true
filter.Contains([]byte("carol")) // false (or, rarely, true)

The fingerprint type (T in New[T]) determines the false positive rate and the memory use:

Type False positive rate Bits per item
uint8 0.39% 9
uint16 0.0015% 18
uint32 2.3e-10 36

The constructor takes an iterator of items to add to the filter and the expected number of items (0 if unknown). The number is only used to preallocate memory, so a good estimate makes the build faster.

You can check if an item is in the filter, but you cannot add or delete an item, count the number of items, or iterate over them.

How it works

The filter2 is an array of b-bit fingerprints (for example, b = 8 for uint8). Each item is hashed to a 64-bit value h, which gives the item's fingerprint f (b bits computed from h) and three positions in the array (cells). The array is filled so that for every item, the XOR of its cells equals f.

        ┌──────┐               ┌──► f  (b bits)
item ──►│ hash │──► h ─────────┤
        └──────┘               └──► i0, i1, i2

           i0          i1          i2
┌───┬───┬──▼──┬───┬───┬──▼──┬───┬──▼──┬───┐
│   │   │ F0  │   │   │ F1  │   │ F2  │   │   F0 ^ F1 ^ F2 == f
└───┴───┴─────┴───┴───┴─────┴───┴─────┴───┘

To check an item, you compute h, look up its three cells, and compare their XOR with f. For an item in the set, they always match. For any other item, the XOR is a random b-bit value, which matches f with probability 2^-b.

Each check reads three cells, so for large filters it's three cache misses, against one for a blocked Bloom filter. However, since the reads are independent, the CPU can do them concurrently, so the checks are about as fast as with a Bloom filter.

The filter uses the local wyhash3 implementation for hashing. It performs roughly the same as xxh34 but has a much simpler implementation, without SIMD or assembly.

Benchmarks

Here's an excerpt from the full benchmarks5, comparing unsure to xorfilter6 (binary fuse by the authors of the paper) and bloom (unsure's own Bloom filter) with 8-bit fingerprints (ns/op, lower is better):

Operation Items unsure xorfilter bloom
Build (per item) 10K 23 25 13
1M 30 31 12
Contains 10K 6.2 8.0 9.3
1M 7.0 9.3 10.2
50M 39 42 40

Memory, bits per item (lower is better):

Items Fingerprint unsure xorfilter bloom
100K 8-bit 9.50 9.50 12.45
10M 8-bit 9.02 9.02 12.10
10M 16-bit 18.04 18.04 27.99

Unsure is the same size as xorfilter (same layout) with up to 25% faster checks. Compared to the Bloom filter, it uses up to 36% less memory, with checks as fast or faster, but up to 2.5× slower builds.

  1. Bloom filter overview and how it works. ↩︎

  2. Binary Fuse Filters paper by Thomas Mueller Graf and Daniel Lemire, 2022. ↩︎

  3. Reference wyhash implementation by Wang Yi. ↩︎

  4. Reference xxHash implementation by Yann Collet. ↩︎

  5. Binary fuse filter benchmarks. ↩︎

  6. FastFilter/xorfilter by Daniel Lemire. ↩︎

UltraLogLog

UltraLogLog is a unique items counter that trades accuracy for space, like HyperLogLog7. It tells you approximately how many distinct items it has seen, no matter how many times each one appeared. UltraLogLog doesn't store the items, so it's much more compact than a regular set.

UltraLogLog is a newer design (Otmar Ertl, 2024) that uses the space more efficiently: for the same error, it needs about 43% less memory than HyperLogLog. For example, a HyperLogLog sketch with 0.81% standard error takes 16 KB, while an UltraLogLog sketch with 0.86% error takes 8 KB. However, adding, counting, and merging are slower than with HyperLogLog.

UltraLogLog is useful in the same places as HyperLogLog: counting unique visitors, unique search queries, or distinct values in a database column, possibly across many machines or segments.

// Standard error about 0.9% of the true count.
sketch := ull.New()

sketch.Add([]byte("alice"))
sketch.Add([]byte("bob"))
sketch.Add([]byte("alice"))
sketch.Add([]byte("carol"))

sketch.Count() // 3 (approximately)

You can merge sketches to get the total number of unique items from all of them, without counting shared items twice.

home := ull.New() // visitors to the home page
docs := ull.New() // visitors to the docs
// ...
home.Merge(docs)
home.Count() // visitors to either page

The sketch has one setting: the precision p, which gives a relative standard error of 0.782/√(2^p). The default is p=13 with 0.86% error in 8 KB, close to the common HyperLogLog default (0.81% in 16 KB).

You can add items to a sketch, get the estimated count, and merge sketches. You cannot check if a specific item was added, remove items, or list them.

How it works

HyperLogLog hashes each item and uses the first p bits of the hash to pick one of m = 2^p registers. It calculates the rank (the number of leading zeros in the rest of the hash, plus one) and keeps the highest rank it has seen in the register. Seeing a rank of k suggests there were about 2^k items in the register. The count is estimated from all the registers together.

                      p bits
        ┌──────┐   ┌──────────┬────────────────────────┐
item ──►│ hash │──►│ 01101001 │ 0001101...             │
        └──────┘   └────┬─────┴───────────┬────────────┘
                        │ register i      └ rank = 3 zeros + 1 = 4
          ┌───┬───┬───┬─▼─┬───┬───┬───┬───┬───┬───┐
registers │ 3 │ 0 │ 5 │ 2 │ 1 │ 0 │ 4 │ 2 │ 0 │ 1 │  2 → 4
          └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

A HyperLogLog register loses some information: it only keeps track of the highest value, not whether any slightly lower values were seen. These lower values show up at least as often as the highest one, so they can tell a lot about the count.

UltraLogLog8 uses the registers more efficiently. Each register is still one byte, but it stores the highest rank k in the upper 6 bits, and whether k−1 and k−2 were seen in the lower 2 bits:

              k = 5        k-1 k-2
          ┌───────────────┬───┬───┐
register  │ 0 0 0 1 0 1   │ 1 │ 0 │  saw 5 and 4, but not 3
          └───────────────┴───┴───┘
          ┌───────────────┬───┬───┐
add k=6:  │ 0 0 0 1 1 0   │ 1 │ 1 │  saw 6, 5, 4
          └───────────────┴───┴───┘

The count estimate uses the FGRA estimator from the UltraLogLog paper. Each register adds a weight based on its value, and the count is calculated as a power of the sum of the weights. Nearly empty and nearly full sketches get special handling, so the estimate stays accurate from zero to billions of items, without bias tables or a separate formula for small counts.

Unsure keeps a histogram of register values (256 four-byte counters, 1 KB) updated as the registers change. This way, Count reads the histogram instead of scanning all the registers. Merge checks 8 registers at a time using a few bitwise operations to find which ones the other sketch would change, and only updates those.

The item is hashed once with wyhash, and the 64-bit hash is split into the register index and the rank.

Benchmarks

Here's an excerpt from the full benchmarks9, comparing UltraLogLog to unsure's own HyperLogLog and axiom10 (HyperLogLog with LogLog-Beta estimator and sparse mode) (ns/op, lower is better):

Operation p Size ull hll axiom
Add 10 1 KB 8.1 5.5 7.6
14 16 KB 8.0 5.7 7.7
18 256 KB 9.4 8.3 8.0
Count 10 1 KB 165 68 17,700
14 16 KB 161 63 348,000
18 256 KB 173 57 4,650,000
Merge 10 1 KB 2,900 720 1,740
14 16 KB 51,200 20,200 58,500
18 256 KB 818,000 341,000 955,000

Accuracy and memory, relative RMSE over 1,000 sketches (lower is better):

Distinct items ull p=13 hll p=14 axiom p=14
1,000 0.66% 0.54% 0.01%
40,000 0.73% 0.68% 0.69%
1,000,000 0.86% 0.79% 0.82%
Memory 9.1 KB 16.3 KB 16.1 KB

UltraLogLog provides the same accuracy as HyperLogLog with almost half the memory. However, adding, counting, and merging are noticeably slower.

Log-linear histogram

A log-linear histogram is a summary of a stream of numbers that trades accuracy for space. It can give you an approximate median, 99th percentile, or any other quantile of the data. It can also estimate what fraction of the numbers are below a certain value (the CDF). The histogram doesn't store the numbers, so it's much more compact than a sorted list.

For example, to find the exact 99th percentile of 1,000,000 response times, you'd have to keep all of them. With 64-bit floats, that takes 8 MB. A log-linear histogram estimates the same percentile within 0.39% of its true value using about 14 KB — almost 600 times less.

The error is relative to the value: if the true 99th percentile is 200 ms, the histogram returns a value between 199.2 and 200.8 ms. This guarantee applies to every quantile, from the median to the most extreme outliers. The size of the histogram doesn't depend on the number of values, only on the accuracy you choose and on how wide the range of the values is.

A log-linear histogram is useful when you need percentiles for positive values that cover a wide range, like latencies, file sizes, or prices.

// Response times in milliseconds.
hist := loghist.New()

hist.Add(12.5)
hist.Add(8.1)
hist.Add(130.0)
// ...

hist.Quantile(0.5)  // median
hist.Quantile(0.99) // 99th percentile
hist.CDF(100)       // fraction of responses faster than 100 ms

You can merge histograms to gather data from multiple machines or segments (like by hour, endpoint, or region). Merging is exact: a merged histogram is the same as if it had received all the values directly.

east := loghist.New() // latencies on one server
west := loghist.New() // latencies on another
// ...
east.Merge(west)
east.Quantile(0.99) // 99th percentile across both servers

The histogram has two settings: relative error and value range. By default, the error is 0.0039 (0.39%) and the range is from 1e-9 to 1e18. Lowering the error or increasing the range uses more memory.

You can add numbers to a histogram, estimate quantiles and the CDF, and merge histograms. You cannot remove numbers or list them.

How it works

A histogram splits the range of values into buckets and counts how many values are in each one. To estimate a quantile, it adds up the counts starting from the lowest bucket until it reaches the requested rank, then returns a value from that bucket. The accuracy of the estimate depends on how wide the bucket is.

With buckets that have equal widths, like 0–10, 10–20, and so on, every estimate has the same absolute error of ±5 around the bucket's midpoint. So the relative error is very large for small values and unnecessarily small for large values:

0       10      20      30     970     980     990     1000
├───────┼───────┼───────┼─ ··· ─┼───────┼───────┼───────┤
    └ 5 ± 5: ±100%                   995 ± 5: ±0.5% ┘

A logarithmic histogram solves this by making each bucket's width proportional to its value. For example, if the bucket boundaries are powers of 1.02 (1, 1.02, 1.0404, ...), the end of each bucket is 2% larger than its start, so any value in the bucket is within about 1% of the bucket's midpoint. DDSketch11 uses this method. The downside is that finding the right bucket for a value means you have to calculate a logarithm, which is relatively slow.

A log-linear histogram gets almost the same result with cheaper math. First, it splits the values into ranges between powers of two: 1–2, 2–4, 4–8, and so on (these are called octaves). Then it splits every octave into the same number of equal-width buckets. For example, here are three octaves with 4 buckets each:

1       2               4                               8
├─┬─┬─┬─┼───┬───┬───┬───┼───────┬───────┬───────┬───────┤
4 buckets   4 buckets               4 buckets

Each octave is twice as long as the previous one, so its buckets are twice as wide, and the bucket width grows with the values, as in a logarithmic histogram. Finding the right bucket only takes a few bit operations instead of calculating a logarithm.

HdrHistogram12 is the best-known log-linear histogram. It records integers: the position of the highest 1 bit of a number determines its octave, and the next few bits determine the bucket within the octave.

Unsure works with float64 numbers and finds the bucket in a similar way to HdrHistogram.

IEEE 754 double-precision format

A float64 in Go (and most other languages) is made up of three parts:

  • a sign bit,
  • an 11-bit exponent e (stored as 1023 + e to avoid negative values),
  • and a 52-bit mantissa f.

The number's value is 1.f × 2^e, where 1.f is a binary fraction between 1 and 2.

The exponent determines the octave, from 2^e to 2^(e+1). The top m bits of the mantissa determine one of the 2^m equal buckets within the octave.

For example, here's the number 5.25 with m=3 (8 buckets per octave). In binary, 5.25 = 1.0101₂ × 2², so the exponent is 2 (stored as 1025), and the mantissa starts with 0101:

5.25 = 1.0101₂ × 2²

sign   exponent     top m   rest of the mantissa
┌───┬─────────────┬─────┬─────────────────────────┐
│ 0 │ 10000000001 │ 010 │ 1000000000 ... 00000000 │
└───┴──────┬──────┴──┬──┴──┬──────────────────────┘
           │         │     └── ignored
           │         └── bucket 2 of 8
           └── 1025 = 2 + 1023: octave [4, 8)

4                               8
├───┬───┬───┬───┬───┬───┬───┬───┤
  0   1   2   3   4   5   6   7
          └ 5.25 lands in bucket 2: [5, 5.5)

Add finds the bucket for the given number and increases the count. Merge adds the counts bucket by bucket. Quantile adds up the counts from the closer end (the leftmost bucket for q ≤ 0.5, the rightmost bucket otherwise) until it reaches the rank.

The number of mantissa bits m comes from the requested error: the constructor picks the smallest m for which the maximum error doesn't exceed the requested one. The default is m=7: 128 buckets per octave and an error of 0.39%.

Log-linear histogram vs. t-digest

A t-digest13 also estimates quantiles, but it limits the error in ranks: Quantile(0.99) returns a value whose rank is close to 99%. A log-linear histogram limits the error in values: Quantile(0.99) returns a value close to the true 99th percentile.

In the middle of the data, the two are pretty similar. But in a long tail, values at nearby ranks can be very different, so even a small error in rank can lead to a big difference in value. Here is the mean relative error of an 8.5 KB t-digest (δ=100) on 1M values from three distributions: lognormal (as in the benchmarks), Pareto with α=1.5 (a longer tail), and uniform between 1,000,000 and 2,000,000 (no tail):

Quantile Lognormal Pareto Uniform
0.5 0.12% 0.09% 0.009%
0.99 1.7% 5.6% 0.015%
0.999 8.7% 67% 0.009%
0.9999 83% 868% 0.004%

A log-linear histogram of about the same size (1% error, 8 KB) has an error below 0.78% for all these cases.

So a log-linear histogram is better for latencies, sizes, and other positive measurements with long tails. A t-digest is better when you need a fixed size no matter what the values are, or when the values can be arbitrarily close to zero.

Benchmarks

Here's an excerpt from the full benchmarks14, comparing unsure to hdr15 (log-linear, integers only, fixed range) and dd16 (DDSketch, logarithmic buckets) with a lognormal distribution (ns/op, lower is better):

Operation Error unsure hdr dd
Add 1% 4 4 19
0.4% 4 4 19
0.1% 4 4 19
Quantile 1% 48 283 1,750
0.4% 90 1,708 3,100
0.1% 337 1,712 11,967
Merge 1% 334 16,369 302
0.4% 657 115,052 808
0.1% 3,249 115,018 2,862

Mean relative error at the requested 0.1%, over 1M values (lower is better):

Quantile unsure hdr dd
0.5 0.033% 0.033% 0.050%
0.99 0.038% 0.037% 0.048%
0.999 0.027% 0.019% 0.039%
0.9999 0.016% 0.002% 0.025%

Memory after adding 1M values (lower is better):

Error unsure hdr dd
1% 8 KB 40 KB 6 KB
0.4% 14 KB 264 KB 13 KB
0.1% 56 KB 264 KB 40 KB

Unsure adds values as fast as hdr and 5× faster than dd, queries 5–19× faster than hdr and about 35× faster than dd, and merges about as fast as dd and 35–175× faster than hdr. It's slightly less accurate than hdr (using 5× less memory), and more accurate than dd (using 1.4× more memory).

  1. DDSketch paper by Charles Masson et al., 2019. ↩︎

  2. HdrHistogram by Gil Tene. ↩︎

  3. T-digest overview and how it works. ↩︎

  4. Log-linear histogram benchmarks. ↩︎

  5. HdrHistogram/hdrhistogram-go by Coda Hale. ↩︎

  6. DataDog/sketches-go by Datadog. ↩︎

MinHash

MinHash estimates how similar two sets are. It summarizes each set in a short fixed-size signature (for example, 256 numbers). Comparing two signatures gives the approximate Jaccard similarity of the sets: |A∩B| / |A∪B|, the proportion of unique items that both sets share.

The size of a signature doesn't depend on the size of the set, so you can compare two sets of a million items each just by comparing 256 pairs of numbers instead of checking every item. Plus, each set's signature is only calculated once, so comparing lots of sets to each other is relatively cheap.

MinHash is useful for finding near-duplicate documents, like web pages or essays (represented as sets of words or 3-word phrases). It's also useful for finding similar user profiles (as sets of liked items) or overlapping datasets (as sets of keys).

// Two documents as sets of words.
strA := "the quick brown fox jumps over the lazy dog"
docA := minhash.New(256)
for w := range strings.FieldsSeq(strA) {
    docA.Add([]byte(w))
}

strB := "the quick brown cat jumps over the lazy dog"
docB := minhash.New(256)
for w := range strings.FieldsSeq(strB) {
    docB.Add([]byte(w))
}

sigA, sigB := docA.Signature(), docB.Signature()
sigA.Similarity(sigB) // 0.75 (true value 7/9 = 0.78)

The MinHash sketch has one setting: the signature size k, which gives a standard error of √(J(1−J)/k) for true similarity J. For example, with k=256 and J=0.5:

  • 68% of estimates are within ±3.1 pp of J (0.47–0.53),
  • 95% within ±6.2 pp (2·stdErr),
  • 99.7% within ±9.4 pp (3·stdErr).

You can add items to a sketch, merge sketches, and get and compare signatures. You cannot check if a specific item was added, count the items, remove them, or list them.

How it works

Classic MinHash17 hashes every item with k different hash functions. Here are two sets, A = {fox, cat, dog, owl} and B = {fox, dog, emu}, and their item hashes for k=4:

item   h1     h2     h3     h4     in A   in B
fox    0.07   0.52   0.66   0.38    ✓      ✓
cat    0.21   0.15   0.80   0.91    ✓
dog    0.48   0.33   0.09   0.74    ✓      ✓
emu    0.63   0.27   0.44   0.12           ✓
owl    0.90   0.71   0.58   0.29    ✓

For each hash function, the set keeps only the smallest hash value among its items. These k minimums are the set's signature. To estimate the similarity of two sets, compare their signatures position by position, count the number of equal values, and divide by k:

             h1     h2     h3     h4
A signature  0.07   0.15   0.09   0.29
B signature  0.07   0.27   0.09   0.12
equal        ✓             ✓
             → 2 of 4 = 0.5

The estimated similarity (0.5) is different from the actual value (2 shared items / 5 distinct items = 0.4). To get a more accurate estimate, k is usually much larger than in this example.

One permutation hashing18 hashes every item once, with a single hash function, and splits the range of hash values into k equal buckets. Each bucket keeps the smallest hash value among its items. Here are the same sets with k=4, using h1 from above:

bucket       0            1            2            3
range        0.00–0.25    0.25–0.50    0.50–0.75    0.75–1.00

A items      fox 0.07     dog 0.48                  owl 0.90
             cat 0.21
B items      fox 0.07     dog 0.48     emu 0.63

A minimums   0.07         0.48         ·            0.90
B minimums   0.07         0.48         0.63         ·

Each bucket works like a separate MinHash over the items in its range. So the bucket minimums form a signature, and comparing two signatures works the same way. But there is a catch: when a set isn't much larger than k, some buckets end up empty (shown as · above), so there's nothing to compare in them.

Optimal densification19 solves this by filling each empty bucket with the value from another bucket in the same set. Each empty bucket tries other buckets in a pseudo-random order and copies the value of the first non-empty one:

bucket       0         1         2         3
A minimums   0.07      0.48      ·         0.90
B minimums   0.07      0.48      0.63      ·

A signature  0.07      0.48      0.90 (3)  0.90
B signature  0.07      0.48      0.63  │   0.07 (0)
equal        ✓         ✓               │         │
             → 2 of 4 = 0.5            │         │
                                       │         │
             which bucket the value was copied from

This order depends only on the empty bucket's position, so two similar sets tend to fill empty spots with the same values. This makes the estimate work for sets of any size, with about the same error as classic MinHash.

Unsure keeps the k bucket minimums in the sketch. Add and Merge use the original buckets. Densification only happens in Signature, and it makes a copy of the buckets without modifying the sketch.

Each item is hashed once with 64-bit wyhash. Multiplying the hash by k once gives both the bucket and the value to store:

┌─────────────────┬─────────────────┬─────────────────┐
│ high 64 bits:   │ next 32 bits:   │ rest:           │
│ bucket in [0,k) │ value           │ unused          │
└─────────────────┴─────────────────┴─────────────────┘
127              64                32                 0

Densification fills empty buckets in a coordinated way, spreading the copies evenly across the non-empty buckets. This keeps the error close to classic MinHash, and makes densification fast even for small sets.

Benchmarks

Here's an excerpt from the full benchmarks20, comparing unsure to dgryski21 (classic MinHash) (ns/op, lower is better):

Operation k unsure dgryski
Add 64 5 30
256 5 115
1024 5 358
Similarity 64 25 24
256 104 103
1024 378 376

RMSE of the similarity estimate at k=256 and J=0.5 (lower is better):

Distinct items unsure dgryski
256 2.89% 3.07%
1,024 2.84% 3.12%
4,096 2.99% 3.09%
16,384 3.11% 3.07%
Memory 1.0 KB 2.0 KB

Unsure adds items 6–70× faster than dgryski, compares signatures at the same speed, has roughly the same accuracy, and uses half the memory.

  1. Classic MinHash paper by Andrei Broder, 1997. ↩︎

  2. One permutation hashing by Ping Li et al., 2012. ↩︎

  3. Optimal densification paper by Anshumali Shrivastava, 2017. ↩︎

  4. MinHash benchmarks. ↩︎

  5. dgryski/go-minhash by Damian Gryski. ↩︎

Wrapping up

Bloom filter and HyperLogLog are everyone's favorites, but they're not the only useful probabilistic data structures out there. In some situations, you might find these helpful:

  • Binary fuse filter is a more compact alternative to a Bloom filter when you know all the items in advance.
  • UltraLogLog is a more compact (but slower) alternative to HyperLogLog.
  • Log-linear histogram is a much more accurate alternative to t-digest (with a variable size).
  • MinHash compares large sets for similarity using a tiny fixed-size signature.

To use them in Go, try the nalgeon/unsure package:

go get github.com/nalgeon/unsure
]]>
Probabilistic data structures in Gohttps://antonz.org/probabilistic-data-structures/Fri, 13 Nov 2026 15:00:00 +0000https://antonz.org/probabilistic-data-structures/Bloom filter, count-min sketch, HyperLogLog, t-digest, and top-k sketch.Probabilistic data structures give you approximate answers to questions about the data they handle. Does the set contain a certain item? How many unique items are in the collection? Which items appear most often? Unlike deterministic structures like sets and frequency tables, the answers might not be exact, but in return, you can drastically reduce memory usage.

In this post, we'll talk about what probabilistic structures are, how they work, and what kinds of guarantees they provide. I'll also introduce unsure — a package that implements these structures in Go. It's simple (the core logic for each data structure is 100–300 LOC), fast (usually several times faster than other implementations), and has no dependencies except for the standard library.

Bloom filter • Count-min sketch • HyperLogLog • T-digest • Top-k

Bloom filter

A Bloom filter is a set that trades certainty for space. It can tell you that an item is definitely not in the set, or that it probably is (which might be a false positive). The filter doesn't store the items, so it's much more compact than a regular set.

For example, a regular set with 1,000,000 distinct 8-byte strings takes about 64 MB. A Bloom filter for the same strings, with a 1% false positive rate, uses only 1.24 MB (about 10 bits per item) — that's 50 times smaller. The size of the filter doesn't depend on the item size, so the difference gets even bigger with longer strings.

A Bloom filter often resides in memory and helps minimize expensive I/O operations such as disk reads or network calls. You check if an item is in the filter, and if the answer is "no", you skip the costly lookup. If the answer is "yes", you still have to perform the lookup because it might be a false positive.

// A filter for 1000 items with a 1% false positive rate.
filter := bloom.New(1000, 0.01)

filter.Add([]byte("alice"))
filter.Add([]byte("bob"))

filter.Contains([]byte("alice")) // true
filter.Contains([]byte("carol")) // false (or, rarely, true)

The filter is sized for the given number of items with a given false positive rate. You can add more, but the false positive rate will go up.

You can add an item to a Bloom filter and check if an item is in the filter, but you cannot delete an item, count the number of items, or iterate over them.

How it works

Bloom filter1 is a large array of m bits, all set to zero at first. To add an item, you compute k hash values for it and set the k bits at those positions:

        ┌──────┐                       ┌───────┐
item ──►│ hash │──► h1, h2, ..., hk ──►│ mod m │──► i1, i2, ..., ik
        └──────┘                       └───────┘

          i1          i2                  ik
┌───┬───┬─▼─┬───┬───┬─▼─┬───┬───┬───┬───┬─▼─┬───┐
│ 0 │ 0 │ 1 │ 0 │ 0 │ 1 │ 0 │ 0 │ 0 │ 0 │ 1 │ 0 │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
  0   1   2                                  m-1

To check if an item is in the filter, you compute the same k hashes and check if all k bits are set:

  • If any of the bits is not set, the item definitely was never added.
  • If all the bits are set, the item was probably added, but it's not guaranteed (the bits could have been set by other items).
          i1          i2                  ik
┌───┬───┬─▼─┬───┬───┬─▼─┬───┬───┬───┬───┬─▼─┬───┐
│ 1 │ 0 │ 1 │ 0 │ 0 │ 1 │ 1 │ 0 │ 1 │ 0 │ 1 │ 0 │  all 1 → probably in the set
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ 1 │ 0 │ 1 │ 0 │ 0 │ 0 │ 1 │ 0 │ 1 │ 0 │ 1 │ 0 │  any 0 → definitely not
└───┴───┴───┴───┴───┴─▲─┴───┴───┴───┴───┴───┴───┘          in the set
                     (!)

The k bits are randomly distributed throughout the entire array. When the filter is larger than the CPU cache, each bit access could result in a cache miss, so a lookup may wait on memory k times.

Unsure uses a blocked Bloom filter2. The bit array is divided into 512-bit blocks, each matching the size of a CPU cache line. When you add or check an item, it is hashed once: part of the hash selects a block, and the rest selects k bits within that block. Each add or check only accesses one cache line, so the filter stays fast even when it's very large.

        ┌──────┐         ┌──► high 32 bits ──► block
item ──►│ hash │──► h ───┤                   ┌─────────┐
        └──────┘         └──► low 32 bits ──►│ × salts │──► i1, i2, ..., ik
                                             └─────────┘

          block
┌───────┬───▼───┬───────┬───────┬───────┬───────┐
│   0   │   1   │   2   │   3   │  ...  │  n-1  │
└───────┴───────┴───────┴───────┴───────┴───────┘
        │       │
┌───────┘       └───────────────────────────────┐
│         i1          i2                  ik    │
├───┬───┬─▼─┬───┬───┬─▼─┬───┬───┬───┬───┬─▼─┬───┤
│ 0 │ 0 │ 1 │ 0 │ 0 │ 1 │ 0 │ 0 │ 0 │ 0 │ 1 │ 0 │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
  0   1   2                                  511

In a blocked Bloom filter, some blocks end up with more items than others, which increases the false positive rate. To make up for this, the filter needs to be a bit larger. Compared to a standard Bloom filter, it uses about 3% more memory at a 1% false positive rate, 8% more at 0.1%, and 15% more at 0.01%.

The filter uses the local wyhash3 implementation for hashing. It performs roughly the same as xxh34 but has a much simpler implementation, without SIMD or assembly.

Benchmarks

Here's an excerpt from the full benchmarks5, comparing unsure to bits-and-blooms6 (a classic Bloom filter) and gloom7 (a blocked one) (ns/op, lower is better):

Operation Items unsure bits-and-blooms gloom
Add 10K 9 37 17
1M 10 36 19
50M 38 170 63
Contains, hit 10K 8 32 16
1M 9 32 18
50M 34 129 60
Contains, miss 10K 8 41 27
1M 9 48 33
50M 34 113 60

Memory, bits per item at 10M items (lower is better):

False positive rate unsure bits-and-blooms gloom
10% 4.84 4.80 5.39
1% 9.90 9.59 10.79
0.1% 15.49 14.38 16.18

Unsure is about 4× faster than bits-and-blooms and 2× faster than gloom, using 1–8% more memory than bits-and-blooms and 4–10% less than gloom.

Count-min sketch

A count-min sketch is a frequency table that trades accuracy for space. It tells you approximately how many times each item has appeared. The estimate is never less than the actual count, but it can be higher. The sketch doesn't store the items, so it's much more compact than a regular map of per-item counts.

For example, a regular map counting 1,000,000 distinct 8-byte strings takes about 64 MB. A count-min sketch for the same strings, with estimates within 0.01% of the total count (with 99% probability), uses only 0.55 MB — that's 116 times smaller. The size of the sketch doesn't depend on the number of distinct items or their size, only on the accuracy you choose. So the difference gets even bigger with more or longer strings.

A count-min sketch is useful when you want to track how many times an item shows up in a large stream of events. It's often used to check if something has happened a certain number of times, like rate-limiting an IP after X requests or sending an alert after an error happens Y times. A sketch can also help decide if a key is worth keeping in the cache given how often it was requested.

// Estimates within 0.1% of the total count, with 99% probability.
sketch := countmin.New(0.001, 0.01)

sketch.Add([]byte("alice"))
sketch.Add([]byte("bob"))
sketch.AddN([]byte("alice"), 2)

sketch.Count([]byte("alice")) // 3 (or, rarely, more)
sketch.Count([]byte("bob"))   // 1 (or, rarely, more)
sketch.Count([]byte("carol")) // 0 (or, rarely, more)
sketch.Total()                // 4

The sketch uses two settings: epsilon ε and delta δ. If the actual count for any given item is X and the total of all counts is N, then the estimated count for this item will usually be between X and X+ε·N. However, rarely (with a probability of δ) the estimate could be even higher.

For example, if ε is 0.001, δ is 0.01, and N is 1 million, then the estimate could be off by up to 1,000 (ε·N) with at least 99% probability (1−δ), and by more than 1,000 with at most 1% probability (δ).

The counting error in a sketch depends on the total of all counts, not on each individual item. Therefore, frequent items are estimated more or less accurately relative to their count, but rare items are not — the absolute error is too high for them.

You can increase the per-item counter in a sketch and get the estimated count for an item, but you cannot decrease a counter or iterate over the items.

How it works

Count-min sketch8 is a table of counters with d rows and w columns, all starting at zero. Each row uses its own hash function that maps an item to one of the w counters. To add an item, you increment its counter in each row:

        ┌──────┐                       ┌───────┐
item ──►│ hash │──► h1, h2, ..., hd ──►│ mod w │──► i1, i2, ..., id
        └──────┘                       └───────┘

       ┌───┬───┬─▼─┬───┬───┬───┬───┬───┬───┬───┐
row 1  │ 0 │ 2 │ 4 │ 0 │ 1 │ 0 │ 0 │ 3 │ 0 │ 1 │  4 → 5
       ├───┼───┼───┼───┼───┼───┼─▼─┼───┼───┼───┤
row 2  │ 1 │ 0 │ 0 │ 0 │ 2 │ 0 │ 3 │ 0 │ 1 │ 0 │  3 → 4
       ├───┼───┼───┼───┼───┼───┼───┼───┼─▼─┼───┤
row d  │ 0 │ 1 │ 0 │ 2 │ 0 │ 0 │ 1 │ 0 │ 5 │ 0 │  5 → 6
       └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
                 i1              i2      id

To estimate an item's count, you take the smallest value from its d counters:

  • Other items might hash to the same counter, so each counter value is ≥ true count.
  • The smallest counter is the one with the fewest collisions, so it's the best estimate.
       ┌───┬───┬─▼─┬───┬───┬───┬───┬───┬───┬───┐
row 1  │ 0 │ 2 │ 4 │ 0 │ 1 │ 0 │ 0 │ 3 │ 0 │ 1 │  4
       ├───┼───┼───┼───┼───┼───┼─▼─┼───┼───┼───┤
row 2  │ 1 │ 0 │ 0 │ 0 │ 2 │ 0 │ 3 │ 0 │ 1 │ 0 │  3
       ├───┼───┼───┼───┼───┼───┼───┼───┼─▼─┼───┤
row d  │ 0 │ 1 │ 0 │ 2 │ 0 │ 0 │ 1 │ 0 │ 5 │ 0 │  5   min = 3
       └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

With w = e/ε columns, each counter's error is at most ε·N, with probability at least 1 − 1/e. If you use d = ln(1/δ) rows, the chance that all d of the item's counters exceed its true count by more than ε·N is ≤ δ.

Unsure uses a conservative update. When you add n to an item, it first finds the current estimate E (the smallest counter), then increases only the counters that are below E+n, leaving the larger ones unchanged. This keeps the same accuracy guarantee, but the actual error is about 2× lower. The tradeoff is that counts can't be decreased.

       ┌───┬───┬─▼─┬───┬───┬───┬───┬───┬───┬───┐
row 1  │ 0 │ 2 │ 4 │ 0 │ 1 │ 0 │ 0 │ 3 │ 0 │ 1 │  4 → 4
       ├───┼───┼───┼───┼───┼───┼─▼─┼───┼───┼───┤
row 2  │ 1 │ 0 │ 0 │ 0 │ 2 │ 0 │ 3 │ 0 │ 1 │ 0 │  3 → 4
       ├───┼───┼───┼───┼───┼───┼───┼───┼─▼─┼───┤
row d  │ 0 │ 1 │ 0 │ 2 │ 0 │ 0 │ 1 │ 0 │ 5 │ 0 │  5 → 5
       └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

Counters are 32-bit instead of the usual 64-bit, so the sketch uses 2× less memory. The item is hashed once, and each row gets its own position from that hash by salting it (multiplying by a random per-row constant).

        ┌──────┐         ┌─────────┐
item ──►│ hash │──► h ──►│ × salts │──► i1, i2, ..., id
        └──────┘         └─────────┘

The sketch uses wyhash for hashing.

Benchmarks

Here's an excerpt from the full benchmarks9, comparing unsure to BoomFilters10 (a classic count-min sketch with 64-bit counters) (ns/op, lower is better):

Operation ε Size (unsure) unsure BoomFilters
Add 0.001 55 KB 13 19
0.00001 5.4 MB 17 32
0.000001 54 MB 81 98
Count 0.001 55 KB 9 51
0.00001 5.4 MB 14 64
0.000001 54 MB 52 139

Accuracy at ε=0.0001, N=10M additions over 1M distinct items, mean overestimate (lower is better):

Distribution unsure BoomFilters
Uniform 139 302
Zipf, s = 1.1 23 44
Zipf, s = 1.5 0.3 0.8
Size 536 KB 1080 KB

Unsure is about 1.5× faster for Add and 4× faster for Count, using 2× less memory with 2–2.7× lower error.

HyperLogLog

HyperLogLog is a unique items counter that trades accuracy for space. It tells you approximately how many distinct items it has seen, no matter how many times each one appeared. HyperLogLog (also called a sketch from here on) doesn't store the items, so it's much more compact than a regular set.

For example, a regular set of 1,000,000 distinct 8-byte strings takes about 64 MB. A HyperLogLog sketch counting the same strings with about 0.8% error uses only 16 KB — that's almost 4,000 times smaller. The size of the sketch doesn't depend on the number of items or their size, only on the accuracy you choose. A 16 KB sketch counts a billion items as accurately as a thousand.

HyperLogLog is useful when you need to count unique things in a large stream: unique visitors to a website, unique search queries per day, or distinct values in a database column.

// Standard error about 0.8% of the true count.
sketch := hll.New()

sketch.Add([]byte("alice"))
sketch.Add([]byte("bob"))
sketch.Add([]byte("alice"))
sketch.Add([]byte("carol"))

sketch.Count() // 3 (approximately)

You can merge sketches to gather data from multiple machines or segments (like by hour, page, or region). When you merge two sketches, you get the total number of unique items from both, without counting shared items twice.

home := hll.New() // visitors to the home page
docs := hll.New() // visitors to the docs
// ...
home.Merge(docs)
home.Count() // visitors to either page

The sketch has one setting: the precision p, which gives a relative standard error (stdErr) of 1.04/√(2^p). A common default is p=14, which gives 0.81% error.

With p=14 and 1 million distinct items:

  • 68% of the time the estimate is within 0.81% (8,100) of the true count,
  • 95% within 1.6% (2·stdErr),
  • 99.7% within 2.4% (3·stdErr).

The error is relative to the count, so the standard error is the same 0.81% for a thousand items or a billion.

You can add items to a sketch, get the estimated count, and merge sketches. You cannot check if a specific item was added, remove items, or list them.

How it works

HyperLogLog11 is based on a simple observation. If you hash items to random bit strings, about half of them start with 1, a quarter with 01, an eighth with 001, and so on. Seeing a hash with k leading zeros suggests there were about 2^(k+1) distinct items. Duplicates hash to the same value, so they don't affect the result.

A single observation is unreliable, so the sketch divides the items into m = 2^p groups, where p is the selected precision. The first p bits of the hash pick a group (a register), and the register keeps the highest rank (leading zeros plus one) it has seen in the rest of the hash:

        ┌──────┐   ┌──────────┬────────────────────────┐
item ──►│ hash │──►│ 01101001 │ 0001101...             │
        └──────┘   └────┬─────┴───────────┬────────────┘
                        │ register i      └ rank = 3 zeros + 1 = 4
          ┌───┬───┬───┬─▼─┬───┬───┬───┬───┬───┬───┐
registers │ 3 │ 0 │ 5 │ 2 │ 1 │ 0 │ 4 │ 2 │ 0 │ 1 │  2 → 4
          └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

The count is estimated from all the registers together, using a harmonic mean of 2^register. The standard error is about 1.04/√m. Merging two sketches is just taking the maximum value from each pair of registers.

The original estimator is biased when dealing with small counts (up to a few times m), so in these cases it uses a different formula called linear counting. This switch creates a sudden change in error, and some implementations (like HyperLogLog++12) address it by using large tables of bias corrections based on real data.

Unsure uses the improved estimator by Otmar Ertl13. Instead of a harmonic mean of the registers, it works from a histogram: how many registers have value 0, value 1, and so on. A formula applied to the histogram gives an accurate estimate for any number of items, from zero to billions, so there's no need for a separate formula for small counts or for correction tables.

The sketch updates the histogram whenever registers change. Most adds don't change any registers, so this is almost free. Counting always takes the same amount of time, no matter how big the sketch is. Other implementations scan all the registers on every count, which takes from microseconds to milliseconds.

Registers are one byte each, and the histogram has 64 four-byte counters (256 bytes). The item is hashed once with wyhash, and the 64-bit hash is split into the register index and the rank.

Benchmarks

Here's an excerpt from the full benchmarks14, comparing unsure to axiom15 (HyperLogLog with LogLog-Beta estimator and sparse mode) (ns/op, lower is better):

Operation p Size unsure axiom
Add 10 1 KB 5.5 7.6
14 16 KB 5.6 7.6
18 256 KB 8.1 7.9
Count 10 1 KB 68 18,300
14 16 KB 62 350,000
18 256 KB 57 4,710,000
Merge 10 1 KB 730 1,710
14 16 KB 20,100 58,600
18 256 KB 341,000 951,000

Accuracy at p=14 (0.81% standard error), relative RMSE over 100 sketches (lower is better):

Distinct items unsure axiom
1,000 0.63% 0.02%
40,000 0.64% 0.71%
1,000,000 0.79% 0.89%

Memory at p=14 after adding the given number of distinct items (lower is better):

Distinct items unsure axiom
100 16 KB 1.2 KB
1,000 16 KB 4.2 KB
10,000 16 KB 16 KB
1,000,000 16 KB 16 KB

Unsure adds about as fast as axiom, counts 270–83,000× faster, and merges 2.3–2.9× faster, with the same accuracy and memory for counts above the number of registers. When there are fewer items than registers, axiom's sparse mode makes it more accurate and compact.

T-digest

A t-digest is a summary of a stream of numbers that trades accuracy for space. It can give you an approximate median, 99th percentile, or any other quantile of the data. It can also estimate what fraction of the numbers are below a certain value (the CDF). The digest doesn't store the numbers, so it's much more compact than a sorted list.

For example, to find the exact 99th percentile of 1,000,000 numbers, you'd have to keep all of them. With 64-bit floats, that takes 8 MB. A t-digest estimates the same percentile within about 0.03% of the rank (between the 98.97th and the 99.03rd percentile) using only 8 KB — 1,000 times smaller. The size of the digest doesn't depend on the number of values, only on the accuracy you choose. An 8 KB digest summarizes a billion values as well as a million.

A t-digest is useful when you need quantiles over a large stream, like latency percentiles for a service, score distributions in an online game, or the outlier thresholds in sensor data.

// Response times in milliseconds.
digest := tdigest.New()

digest.Add(12.5)
digest.Add(8.1)
digest.Add(130.0)
// ...

digest.Quantile(0.5)  // median
digest.Quantile(0.99) // 99th percentile
digest.CDF(100)       // fraction of responses faster than 100 ms

You can merge digests to gather data from multiple machines or segments (like by hour, endpoint, or region). A merged digest estimates the percentiles of all values, but with less accuracy than individual digests do.

east := tdigest.New() // latencies on one server
west := tdigest.New() // latencies on another
// ...
east.Merge(west)
east.Quantile(0.99) // 99th percentile across both servers

The digest has one setting: the compression δ, which limits the number of centroids (see How it works below) to δ+2. A common default is δ=100, which takes 8 KB. Increasing δ uses more memory but reduces estimation error.

The error is measured in ranks: a rank error of 0.03% at quantile q=0.99 means the value returned by Quantile(0.99) is somewhere between the 98.97th and the 99.03rd percentile of the actual values. Tail estimates, such as q=0.99 or q=0.999, are more accurate than the median (q=0.5).

You can add numbers to a digest, estimate quantiles and the CDF, and merge digests. You cannot remove numbers or list them.

How it works

T-digest16 summarizes the numbers as a sorted list of centroids. Each centroid has a mean and a weight — the number of values it represents. To estimate a quantile, the digest finds the centroids around the requested rank and interpolates between their means.

The trick is in how big the centroids are allowed to grow. A scale function k(q) maps a quantile q to a number from -δ/4 to δ/4, and each centroid may only span 1 unit of k: if a centroid covers the quantiles from q₁ to q₂, then k(q₂) − k(q₁) ≤ 1.

The arcsine scale function, k(q) = δ/(2π)·asin(2q-1), is steep near q=0 and q=1 and flat near the median. This means the centroids it produces are larger in the center and smaller at the ends:

weight
  │                ┌──┐
  │             ┌──┤  ├──┐
  │          ┌──┤  │  │  ├──┐
  │       ┌──┤  │  │  │  │  ├──┐
  │  ┌─┬──┤  │  │  │  │  │  │  ├──┬─┐
  └──┴─┴──┴──┴──┴──┴──┴──┴──┴──┴──┴─┴──► value
    min      q=0.25   median  q=0.75     max

With 1M values and δ=100, the centroids around the median hold about 27,000 values each, those around the 99th percentile about 5,000, and the outermost ones about 500. This keeps the error near the tails small.

Unsure is the merging t-digest from the Dunning and Ertl paper. New values go to a buffer of 5·δ numbers. When the buffer is full, the digest sorts it and merges it with the centroids (already sorted) in a single pass, building new centroids from left to right as long as each one fits within its span of k. Every other pass goes right to left, so that neither tail ends up with fuller centroids. Quantile, CDF and Merge flush the buffer first.

The centroids are kept in two fixed arrays of δ+2 entries (the current list and the next one being built), along with the cumulative weights for a binary search in Quantile and CDF. With δ=100, that's 16·102·2 + 8·103 bytes for the centroids, and 8·500 bytes for the buffer, about 8 KB in total.

Centroids with weight 1 are treated as exact values rather than spread around their mean, and the exact minimum and maximum are used at the ends. So digests with few values give exact results, and Quantile(0) and Quantile(1) are always exact.

Benchmarks

Here's an excerpt from the full benchmarks17, comparing unsure to influxdata18 (merging t-digest with the same scale function) (ns/op, lower is better):

Operation δ unsure influx
Add 50 44 78
100 49 86
500 59 105
Quantile 50 11 13
100 13 13
500 15 16
Merge 50 296 2,060
100 630 4,330
500 2,720 23,950

Accuracy at δ=100, mean rank error over 1M normal values (lower is better):

Digest Quantile unsure influx
Single 0.5 0.007% 0.015%
0.99 0.018% 0.016%
0.999 0.011% 0.009%
Merged 0.5 0.055% 0.037%
0.99 0.023% 0.021%
0.999 0.006% 0.016%

Memory at δ=100 (lower is better): unsure 8.5 KB, influxdata 14.4 KB.

Unsure adds values about 1.8× faster than influxdata, queries at the same speed, merges 7–9× faster, and uses 40% less memory at about the same accuracy.

Top-k sketch

A Top-k sketch finds the k most frequent items in a stream (the "heavy hitters"), along with their approximate counts. It uses a fixed amount of memory based only on k, no matter how many different items are in the stream.

To find the exact top items, you'd have to count every unique item, for example with a map of per-item counts. With millions of distinct items, that takes tens or hundreds of megabytes. A Top-k sketch for the top 1000 items takes about 360 KB, and it usually finds all of them.

A Top-k sketch is useful when you want to identify the "hottest" data: the most requested URLs, the most active users, or the most common search queries. Unlike a count-min sketch, it keeps the actual items, so it can list them.

// Track the 2 most frequent items.
sketch := topk.New(2)

sketch.Add([]byte("alice"))
sketch.Add([]byte("bob"))
sketch.Add([]byte("carol"))
sketch.AddN([]byte("alice"), 4)
sketch.AddN([]byte("carol"), 2)

sketch.Top()                  // [{alice 5} {carol 3}]
sketch.Count([]byte("alice")) // 5
sketch.Count([]byte("bob"))   // 0 (not in the top 2)
sketch.Total()                // 9

Top returns up to k items, from the most frequent to the least frequent. Counts are estimates: they're usually exact for the most frequent items, but may be slightly lower than the actual count for less common items.

The sketch works best when the stream is skewed, meaning a few items appear much more often than the others. This is common in real situations. If all items are about equally frequent, there is no clear top k, and the results become less accurate.

You can add items to the sketch and get the top items with their counts, but you can't decrease counts or check items that aren't in the top k.

How it works

HeavyKeeper19 is a table of buckets that estimates item counts. It has d rows and w columns, and each item maps to one bucket in each row. Each bucket holds a fingerprint of the item and a count. To add an item, you update its bucket in each row:

  • If the bucket is empty or owned by the item, increase its count.
  • If the bucket is owned by another item, decay it: decrease its count by 1 with probability b^count (b < 1). When the count reaches 0, the new item takes over the bucket with a count of 1.
          ┌──────┐
add x ──► │ hash │──► h ──► high 32 bits ──► fingerprint = 7
          └──────┘    │
                      │ map to buckets
                   ┌──┴────────────┐
       ┌───────┬───▼───┬───────┬───│───┬───────┐
row 1  │       │ fp=7  │ fp=3  │   │   │ fp=5  │  column 2 is owned by x:
       │       │  41   │   2   │   │   │  980  │  41 → 42
       ├───────┼───────┼───────┼───▼───┼───────┤
row 2  │ fp=9  │       │       │ fp=2  │ fp=4  │  column 4 is owned by another:
       │  17   │       │       │   3   │   1   │  3 → 2 with probability b^3
       └───────┴───────┴───────┴───────┴───────┘
         col 1   col 2   col 3   col 4   col 5

The item's estimated count is the largest count among its buckets. Frequent items quickly reach counts that make decay very unlikely, so they keep their buckets. Rare items keep replacing each other without affecting the frequent ones. An item that becomes frequent later in the stream can still outnumber a less frequent owner and take over its bucket.

Next to the table, the sketch keeps a min-heap with the k items that have the largest estimates so far. After an item's buckets are updated, if its estimate is larger than the smallest count in the heap, the item is added to the heap, and the smallest item is removed. If the item is already in the heap, its count is increased.

                   ┌───────────┐
add x (15) ───────►│ bob    12 │  the root has the smallest count
                   └─────┬─────┘
              ┌──────────┴────────┐
        ┌─────┴─────┐       ┌─────┴─────┐
        │ alice  30 │       │ dave   14 │  15 > 12: x replaces bob at the root
        └─────┬─────┘       └───────────┘  15 > 14: x moves down, dave moves up
      ┌───────┴──────┐
┌─────┴─────┐  ┌─────┴─────┐
│ eve   980 │  │ fay    41 │
└───────────┘  └───────────┘

Unsure uses d = 2 rows of max(16k, 256) buckets, and a decay base of b = 0.8. The probabilities b^count are precomputed as 64-bit thresholds, so decay is cheap: the count c decreases if a random number is below the c-th threshold.

The original HeavyKeeper uses b = 1.08⁻¹ ≈ 0.93, and more rows. A smaller b lets frequent items lock their buckets faster, which makes the sketch more precise on flat streams. However, if b is too small (like 0.5), the first items to claim buckets keep them permanently, so items that become frequent later are never counted, even if they end up being the most frequent. Using b = 0.8 keeps most of the precision and still catches most late-arriving frequent items. As for the rows, two are enough to protect frequent items from collisions in a single row, and adding more rows only makes the sketch slower.

The item is hashed once. The hash is mapped to a position in each row by salting it (multiplying by a random per-row constant). The fingerprint is the top 32 bits of the hash. The heap uses the 64-bit hash to identify items, so it doesn't compare the actual item bytes.

Each bucket is 8 bytes (a 32-bit fingerprint and a 32-bit count), so the table takes 256·k bytes. The heap takes about 100 bytes per item plus the item itself.

The sketch uses wyhash for hashing and wyrand for random numbers.

Benchmarks

Here's an excerpt from the full benchmarks20, comparing unsure to keiler21 (HeavyKeeper with b = 0.9 and d = ln k) and dgryski22 (Filtered Space-Saving23) on the Zipf s=0.8 stream (time/op, lower is better):

Operation k unsure keiler dgryski
Add 10 24 ns 64 ns 59 ns
100 25 ns 84 ns 70 ns
1000 33 ns 130 ns 73 ns
Top 10 0.34 µs 0.64 µs 0.77 µs
100 3.7 µs 13 µs 14 µs
1000 75 µs 270 µs 292 µs

Precision is the fraction of the reported top k that is in the true top k (higher is better):

k Zipf s unsure keiler dgryski
100 0.6 0.90 0.38 0.19
0.8 1.00 0.78 0.85
1.0 0.99 1.00 1.00
Size 39 KB 27 KB 39 KB
1000 0.6 0.97 0.70 0.52
0.8 1.00 0.98 1.00
1.0 1.00 1.00 1.00
Size 364 KB 414 KB 453 KB

Count error is the mean of |estimate − true| / true over the reported items (lower is better):

k Zipf s unsure keiler dgryski
100 0.6 14% 94% 428×
0.8 0.10% 46% 230%
1.0 0.01% 0.12% 0.0%
1000 0.6 2.4% 62% 18×
0.8 0.23% 1.9% 0.31%
1.0 0.05% 0.24% 0.02%

Unsure is 2–4× faster than the others for Add and 1.8–4× faster for Top. On flat streams (s=0.6), it finds the true top k with 90–97% precision, while keiler drops to 38–70% precision with a count error of 62–94%, and dgryski to 19–52% with counts 18× or more too high. On skewed streams (s=1.0), all three are about equally accurate.

Wrapping up

As engineers, we usually want exact answers from our data. But sometimes, allowing a bit of uncertainty can cut memory usage by tens, hundreds, or even thousands of times. That's where probabilistic data structures come in:

  • Bloom filter checks if an item might be in a set.
  • Count-min sketch estimates how many times each item has occurred.
  • HyperLogLog estimates the number of distinct items.
  • T-digest estimates quantiles of a stream of numbers.
  • Top-k sketch identifies the most frequent items in a stream.

To use them in Go, try the nalgeon/unsure package:

go get github.com/nalgeon/unsure

P.S. If you liked this post, check out the second part!

]]>
Go concurrency distilledhttps://antonz.org/go-concurrency-distilled/Sat, 26 Sep 2026 11:30:00 +0000https://antonz.org/go-concurrency-distilled/Interactive mini-book on concurrent programming in Go.This mini-book provides a brief overview of many concurrency topics in Go. Each topic comes with interactive examples — feel free to experiment with them by changing the code and clicking Run. There's also a PDF version with static examples.

This is a quick refresher on Go concurrency, not a beginner's guide. If you want to learn concurrency from the ground up with practical exercises, check out my other book — Gist of Go: Concurrency.

The book is AI-free.

Goroutines • Channels • Select • Pipelines • Time • Context • Wait groups • Data races • Race conditions • Mutexes • Semaphores • Signaling • Run once • Object pool • Atomics • Testing • Scheduling • Diagnostics • Final thoughts

Goroutines

The foundation of concurrency in Go is goroutines – functions started with the go keyword:

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        fmt.Println("worker 1")
    }()
    go func() {
        defer wg.Done()
        fmt.Println("worker 2")
    }()
    wg.Wait()
}
worker 2
worker 1

The Go runtime juggles these goroutines and distributes them among operating system threads running on CPU cores. Compared to OS threads, goroutines are lightweight, so you can create hundreds or thousands of them.

Goroutines are completely independent. The main function is also a goroutine, but it starts implicitly when the program starts. When main ends, other goroutines also shut down.

We use a wait group (sync.WaitGroup) to wait for goroutines to finish in the example above. A wait group has a counter inside. Calling Add(n) increments it by n, while Done() decrements it by one. Wait() blocks the calling goroutine (in this case, main) until the counter reaches zero. This way, main waits for both workers to finish before it exits.

WaitGroup.Go automatically increments the wait group counter, runs a function in a goroutine, and decrements the counter when it's done:

func main() {
    var wg sync.WaitGroup
    wg.Go(func() {
        fmt.Println("worker 1")
    })
    wg.Go(func() {
        fmt.Println("worker 2")
    })
    wg.Wait()
}
worker 2
worker 1

Channels

Goroutines can pass values to each other through channels. A channel is like a window where one goroutine can throw something and another can catch it:

func main() {
    messages := make(chan string)

    go func() { messages <- "ping" }()

    msg := <-messages
    fmt.Println(msg)
}
ping

Sending a value through a channel is a synchronous operation. When the sending goroutine writes a value to the channel (ch <- val), it blocks and waits for someone to receive that value (<-ch). Only then does it continue.

Output channel

Returning an output channel from a function and filling it within an internal goroutine is a common pattern in Go. This allows the caller to receive values through the channel while the owning function retains control of it:

func generate(start, stop int) chan int {
    out := make(chan int)
    go func() {
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}

Closing a channel

To signal readers that all data has been sent, the writer goroutine closes the channel with close():

func generate(start, stop int) chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}

The reader checks the channel's status with a second value ("comma OK") when reading:

func main() {
    in := generate(5, 10)
    for {
        num, ok := <-in
        if !ok {
            break
        }
        fmt.Print(num, " ")
    }
}
5 6 7 8 9

While the channel is open, the reader receives the next value and a true status. If the channel is closed, the reader gets a zero value and a false status.

A channel can only be closed once. Closing it again or writing to a closed channel causes a panic.

The only reason to close a channel is to signal to its readers that all data has been sent. If this isn't important to the readers, then you don't need to close it. When a channel is no longer used, Go's garbage collector will free its resources, whether it's closed or not.

Channel iteration

range automatically reads the next value from the channel and checks if it's closed. If the channel is closed, it exits the loop:

func main() {
    nums := generate(5, 10)
    for n := range nums {
        fmt.Print(n, " ")
    }
}
5 6 7 8 9

Range over a channel returns a single value, not a pair, unlike range over a slice.

Directional channels

You can protect yourself from accidental write/close errors by setting the channel direction. Channels can be:

  • chan (bidirectional): for reading and writing (default);
  • chan<- (send-only): for writing only;
  • <-chan (receive-only): for reading only.

You can't read from a send-only channel or write to a receive-only channel (nor can you close it).

Channels are usually initialized for both reading and writing, and specified as directional in function parameters. Go automatically converts a regular channel to a directional one:

stream := make(chan int)

go func(in chan<- int) {
    in <- 42
}(stream)

func(out <-chan int) {
    fmt.Println(<-out)
}(stream)
42

Buffered channels

Buffered channels work like a FIFO queue with a fixed-size buffer for storing values.

As long as the buffer has free space, writing to the channel doesn't block the goroutine. Similarly, as long as the buffer contains values, reading from the channel doesn't block the goroutine:

stream := make(chan int, 3)
stream <- 11
stream <- 12
stream <- 13

fmt.Println(<-stream)
fmt.Println(<-stream)
11
13

By default, if you don't specify a buffer size, a channel is unbuffered (buffer size equals zero).

Buffered channels work with the built-in len() and cap() functions:

stream := make(chan int, 3)
stream <- 11
fmt.Println(cap(stream), len(stream))
3 1

Reading from a closed buffered channel returns values from the buffer and a true status. Once all values are taken, it returns a zero value and a false status, like a regular channel:

stream := make(chan int, 1)
stream <- 11
close(stream)

val, ok := <-stream
fmt.Println(val, ok)
// 11 true

val, ok = <-stream
fmt.Println(val, ok)
// 0 false
11 true
0 false

nil channel

Like any type in Go, channels have a zero value, which is nil.

Writing to or reading from a nil channel blocks the goroutine indefinitely:

var stream chan int

go func() {
    // blocks forever
    stream <- 1
}()

// blocks forever
<-stream

Closing a nil channel causes a panic:

var stream chan int
close(stream)
// panic: close of nil channel

Select

The select statement is somewhat like switch, but specifically designed for channels. Here's what it does:

  • Checks which cases are not blocked.
  • If multiple cases are ready, randomly selects one to execute.
  • If all cases are blocked and there is a default case, executes it.
  • If all cases are blocked and there is no default case, waits until one is ready.

Select is used to manage data flow in pipelines:

// merge sends values from in1 and in2 to the output channel.
func merge(in1, in2 <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for in1 != nil || in2 != nil {
            select {
            case val1, ok := <-in1:
                if ok { out <- val1 } else { in1 = nil }
            case val2, ok := <-in2:
                if ok { out <- val2 } else { in2 = nil }
            }
        }
    }()
    return out
}

// Suppose we send 10..12 to in1, 20..22 to in2,
// and call merge(in1, in2)
10 11 20 12 21 22

To cancel goroutines:

// process modifies values from in and send them to out
// until in is exhausted or cancel is closed.
func process(cancel chan struct{}, in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for val := range in {
            select {
            case out <- val*10:
            case <-cancel:
                fmt.Println("canceled")
                return
            }
        }
    }()
    return out
}

// Suppose we send values 11 and 12 to in
// and then call close(cancel)
110
120
canceled

For non-blocking operations:

// multiplier returns a function that multiplies
// the input by 10 and sends it to the channel
// or returns an error if the channel is busy.
func multiplier(ch chan<- int) func(n int) error {
    return func(n int) error {
        select {
        case ch <- n*10:
            return nil
        default:
            return errors.New("busy")
        }
    }
}

func main() {
    nums := make(chan int, 1)
    multiply := multiplier(nums)

    err := multiply(11)
    fmt.Println(<-nums, err)
    // 110 <nil>

    err = multiply(12)
    fmt.Println(<-nums, err)
    // 120 <nil>

    err = multiply(13)
    err = multiply(14)
    fmt.Println(err)
    // busy
}
110 <nil>
120 <nil>
busy

And for much more.

Pipelines

A pipeline is a sequence of operations where each step takes input data, processes it in a specific way, and outputs it. The input and output of each operation is a channel.

A typical pipeline looks like this:

  • Reader: Reads input data from a file, database, or network.
  • N processors: Transform, filter, aggregate, or enrich data using external sources.
  • Writer: Writes the processed data to a file, database, or network.
func read[T any]() <-chan T {
    out := make(chan T)
    go func() {
        defer close(out)
        for {
            // read data from somewere
            data := // ...
            out <- data
        }
    }()
    return out
}

func process[T any](in <-chan T) <-chan T {
    out := make(chan T)
    go func() {
        defer close(out)
        for inData := range in {
            // process the data
            outData = // ...
            out <- outData
        }
    }()
    return out
}

func write[T any](in <-chan T) <-chan struct{} {
    done := make(chan struct{})
    go func() {
        defer close(done)
        for data := range in {
            // write the data
        }
    }()
    return done
}

Output channel

A goroutine can signal other goroutines that it has finished its work using an output channel:

func generate(start, stop int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := start; i < stop; i++ {
            out <- i
        }
    }()
    return out
}

func main() {
    nums := generate(5, 10)
    for n := range nums {
        fmt.Print(n, " ")
    }
}
5 6 7 8 9

Done channel

If a goroutine doesn't need to return results, it can signal completion using a done channel:

func work() <-chan struct{} {
    done := make(chan struct{})
    go func() {
        defer close(done)
        fmt.Println("work done")
    }()
    return done
}

func main() {
    done := work()
    <-done
}
work done

Cancel channel

To terminate a goroutine early, a calling goroutine can use a cancel channel:

func generate(cancel chan struct{}, n int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)
        for i := 1; i <= n; i++ {
            select {
            case out <- i:
            case <-cancel:
                return
            }
        }
    }()
    return out
}

func main() {
    cancel := make(chan struct{})
    defer close(cancel)

    nums := generate(cancel, 10)
    fmt.Println(<-nums)
    fmt.Println(<-nums)
    fmt.Println(<-nums)
}
1
2
3

Error handling

There are three approaches to error handling in concurrent pipelines.

➊ Return on the first error:

// calculate produces answers for the given numbers.
func process(in <-chan int) (<-chan int, <-chan error) {
	out := make(chan Answer)
	errc := make(chan error, 1)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			if err != nil {
				errc <- err  // return with error
				return
			}
			out <- ans
		}
		errc <- nil          // return with nil
	}()
	return out, errc
}

➋ Use a result type:

// Result contains an answer or an error.
type Result struct {
	answer int
	err    error
}

// calculate produces answers for the given numbers.
func calculate(in <-chan int) <-chan Result {
	out := make(chan Result)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			out <- Result{ans, err}  // return answer + error
		}
	}()
	return out
}

➌ Collect errors separately:

// calculate produces answers for the given numbers.
func calculate(in <-chan int, errc chan<- error) <-chan int {
	out := make(chan Answer)
	go func() {
		defer close(out)
		for n := range in {
			ans, err := fetchAnswer(n)
			if err == nil {
				out <- ans   // send answer
			} else {
				errc <- err  // or error
			}
		}
	}()
	return out
}

Time

Besides handling date and time, the time package offers tools for managing time-sensitive operations in concurrent programs.

After

time.After() returns a channel that is initially empty, but receives a value after the timeout period. It's useful for timing out operations:

// withTimeout executes a function with a given timeout.
func withTimeout(timeout time.Duration, fn func()) error {
    done := make(chan struct{})
    go func() {
        defer close(done)
        fn()
    }()

    // blocks until fn completes or the timer expires,
    // whichever happens first
    select {
    case <-done:
        return nil
    case <-time.After(timeout):
        return errors.New("timeout")
    }
}

withTimeout() waits for fn() to complete, but thanks to time.After(), it won't wait longer than the timeout duration:

func main() {
    var err error

    // completes in time
    err = withTimeout(
        50*time.Millisecond,
        func() { fmt.Println("work done") },
    )
    fmt.Println("err =", err)

    // gets canceled on timeout
    err = withTimeout(
        50*time.Millisecond,
        func() {
            time.Sleep(100 * time.Millisecond)
            fmt.Println("work done")
        },
    )
    fmt.Println("err =", err)
}
work done
err = <nil>
err = timeout

Timer

A timer (time.Timer) is a structure with a C channel to which it sends the current time when it triggers (expires). Timers are useful for planning future executions:

done := make(chan struct{})

timer := time.NewTimer(50 * time.Millisecond)
go func() {
    eventTime := <-timer.C  // blocks for 50ms
    fmt.Println("work done at", eventTime)
    close(done)
}()

<-done
work done at 2009-11-10 23:00:00.05

Stop() stops the timer and returns true if it hasn't expired yet, and false otherwise:

// timer expires after 50ms
timer := time.NewTimer(50 * time.Millisecond)
go func() {
    eventTime := <-timer.C
    fmt.Println("work done at", eventTime)
}()

// after 10ms, the timer hasn't expired yet
time.Sleep(10 * time.Millisecond)

if timer.Stop() {
    fmt.Println("execution canceled")
} else {
    fmt.Println("too late to cancel")
}
execution canceled

It's often more convenient to use the time.AfterFunc() wrapper function. It waits for duration d and then executes function f:

done := make(chan struct{})
work := func() {
    fmt.Println("work done")
    close(done)
}

// executes work after 50ms
time.AfterFunc(50*time.Millisecond, work)
<-done
work done

time.AfterFunc() returns a timer that you can cancel before execution starts:

// executes the function after 50ms
timer := time.AfterFunc(50*time.Millisecond, func() {})

// after 10ms, the timer hasn't expired yet
time.Sleep(10 * time.Millisecond)

if timer.Stop() {
    fmt.Println("execution canceled")
}
execution canceled

If a timer is used in a loop, it's better to create a single timer and reset it instead of creating a new instance on each iteration:

// consumer reads tokens from the input channel and alerts
// if a value does not appear in a channel after an hour.
func consumer(in <-chan token) {
    const timeout = time.Hour
    timer := time.NewTimer(timeout)
    for {
        timer.Reset(timeout)
        select {
        case <-in:
            // do stuff
        case <-timer.C:
            // log warning
        }
    }
}

// Suppose we send 10,000 values to the in channel
// and measure memory usage.
Memory used: 4 KB, # allocations: 6

Ticker

A ticker is like a timer, but it keeps firing until you stop it. Tickers are useful for executing periodic tasks:

// fires every 50ms
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()

go func() {
    for {
        // waits for ticker to fire on each iteration
        at := <-ticker.C
        fmt.Println("work done at", at)
    }
}()

// enough time for the ticker to fire 3 times
time.Sleep(160*time.Millisecond)
ticker.Stop()
work done at 2009-11-10 23:00:00.05
work done at 2009-11-10 23:00:00.10
work done at 2009-11-10 23:00:00.15

NewTicker(d) creates a ticker that sends the current time to the channel C at interval d. You must stop the ticker eventually with Stop() to free up resources.

If the channel reader can't keep up with the ticker, the ticker will skip ticks.

Context

The main purpose of context is to cancel operations, either manually or by timeout/deadline.

The function accepts a context and uses its Done() channel to listen for cancellation:

// work performs a task for 50 ms unless canceled.
// Returns an error when canceled.
func work(ctx context.Context) error {
    done := make(chan struct{})

    go func() {
        time.Sleep(50 * time.Millisecond)
        fmt.Println("work done")
        close(done)
    }()

    select {
    case <-done:
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

Cancel manually (context.Canceled error):

func main() {
    // empty context
    ctx := context.Background()
    // manual canellation context
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // takes 50 ms unless canceled
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    // cancels after 10 ms
    time.Sleep(10 * time.Millisecond)
    cancel()
    <-done
}
err = context canceled

Cancel by timeout (context.DeadlineExceeded error):

func main() {
    ctx := context.Background()
    // cancels after 10 ms
    ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // takes 50 ms unless canceled
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    <-done
}
err = context deadline exceeded

Cancel by deadline (context.DeadlineExceeded error):

func main() {
    ctx := context.Background()
    // cancels at now + 10 ms
    deadline := time.Now().Add(10 * time.Millisecond)
    ctx, cancel := context.WithDeadline(ctx, deadline)
    defer cancel()

    done := make(chan struct{})
    go func() {
        // takes 50 ms unless canceled
        err := work(ctx)
        fmt.Println("err =", err)
        close(done)
    }()

    <-done
}
err = context deadline exceeded

Context is layered. A context object is immutable. To add new properties to a context, a new (child) context is created based on the old (parent) context. The shorter timeout between the parent and child contexts always wins. The child context can only shorten the parent's timeout, not extend it:

func main() {
    // parent context with a 100 ms timeout
    const dur100ms = 100 * time.Millisecond
    parentCtx, cancel := context.WithTimeout(context.Background(), dur100ms)
    defer cancel()

    // child context with a 10 ms timeout
    const dur10ms = 10 * time.Millisecond
    childCtx, cancel := context.WithTimeout(parentCtx, dur10ms)
    defer cancel()

    // now the work gets canceled
    err := work(childCtx)
    fmt.Println("err =", err)
}
err = context deadline exceeded

Multiple cancels are safe. You can call cancel() on the context as many times as you want. The first cancel will work, and the rest will be ignored.

You can specify a custom cancellation cause using context.WithCancelCause(), context.WithTimeoutCause() and context.WithDeadlineCause(). This cause is accessible through context.Cause():

ctx, cancel := context.WithCancelCause(context.Background())
cancel(errors.New("the night is dark"))
fmt.Println(context.Cause(ctx))
the night is dark

You can register a function to execute when the context is canceled with context.AfterFunc():

ctx, cancel := context.WithCancel(context.Background())
cleanup := func() { fmt.Println("cleanup") }
context.AfterFunc(ctx, cleanup)
cancel()
time.Sleep(10 * time.Millisecond)
cleanup

Context can pass additional information about a call using context.WithValue(), which creates a context with a value for a specific key. But it's generally better to avoid passing values in context. It's better to use explicit parameters or custom structs instead.

Wait groups

The sync.WaitGroup type lets you wait for one or more goroutines to finish:

const n = 10
var wg sync.WaitGroup
wg.Add(n)
for range n {
    go func() {
        defer wg.Done()
        fmt.Print(".")
    }()
}
wg.Wait()
..........

A WaitGroup doesn't know anything about the goroutines it manages. It works with an internal counter. Calling wg.Add(1) increments the counter by one, while wg.Done() decrements it. wg.Wait() blocks the calling goroutine until the counter reaches zero.

The Go method combines Add, starting a goroutine, and Done:

var wg sync.WaitGroup
for range 10 {
    wg.Go(func() {
        fmt.Print(".")
    })
}
wg.Wait()
..........

All methods are safe to use from multiple goroutines.

Normally, all Add calls happen before Wait. But technically, there's nothing stopping you from doing some of the Add calls before Wait and some after (from another goroutine).

You can call Wait from multiple goroutines. They will all block until the group's counter reaches zero.

Data races

A data race happens when multiple goroutines access shared data, and at least one of them modifies it. We need to protect the data from this kind of concurrent access.

A data race doesn't always cause a runtime panic. That's why Go provides a special tool called the race detector. You can turn it on with the race flag, which works with the test, run, build, and install commands.

var total int

// There's a data race on total.
var wg sync.WaitGroup
wg.Go(func() { total++ })
wg.Go(func() { total++ })
wg.Wait()

fmt.Println("total:", total)
total: 2
go run -race main.go
==================
WARNING: DATA RACE
...
2
Found 1 data race(s)

Channels are safe for concurrent reading and writing, and they don't cause data races.

Ways to prevent data races:

  • Avoid concurrent data modification (typically by using channels).
  • Synchronize access with mutexes.
  • Use only atomic operations.

Race conditions

A race condition happens when an unpredictable order of operations from multiple goroutines leads to an incorrect system state:

// There's a race condition when working with balance.
withdraw := func(amount int) {
    if getBalance() < amount {
        return
    }
    time.Sleep(time.Millisecond)
    setBalance(getBalance() - amount)
}

setBalance(50)

var wg sync.WaitGroup
wg.Go(func() { withdraw(40) })
wg.Go(func() { withdraw(40) })
wg.Wait()

fmt.Println("balance:", getBalance())
balance: -30

If individual operations are concurrent-safe, Go's race detector won't find any issues. Because of this, it doesn't catch race conditions:

go run -race main.go
balance: -30

You can't fully eliminate uncertainty in a concurrent environment. Events will happen in an unpredictable order — that's just how concurrency works. However, you can prevent a race condition — often by protecting a composite operation with a mutex:

var mu sync.Mutex
withdraw := func(amount int) {
    mu.Lock()
    defer mu.Unlock()

    if getBalance() < amount {
        return
    }
    time.Sleep(time.Millisecond)
    setBalance(getBalance() - amount)
}

setBalance(50)

var wg sync.WaitGroup
wg.Go(func() { withdraw(40) })
wg.Go(func() { withdraw(40) })
wg.Wait()

fmt.Println("balance:", getBalance())
balance: 10

Compare-and-set

Sometimes you can prevent a race condition without using mutexes by applying an atomic compare-and-set operation or one of its flavors:

// CompareAndSet changes the value to new if the current value equals old.
// Returns true if the value was changed.
CompareAndSet(old, new any) bool

// CompareAndSwap changes the value to new if the current value equals old.
// Returns the old value.
CompareAndSwap(old, new any) any

// CompareAndDelete deletes the value if the current value equals old.
// Returns true if the value was deleted.
CompareAndDelete(old any) bool

// etc

The idea is always the same:

  • Check if the assumed (old) state matches reality.
  • If it does, change the state to new.
  • If not, do nothing.

Mutexes

The sync.Mutex type protects shared data and parts of your code from being accessed concurrently:

var total int
var mu sync.Mutex

var wg sync.WaitGroup
for range 100 {
    wg.Go(func() {
        mu.Lock()
        time.Sleep(time.Millisecond)
        total++
        mu.Unlock()
    })
}
wg.Wait()
total: 100

The mutex guarantees that only one goroutine can run the code between Lock() and Unlock() at a time.

A mutex is used in these situations:

  • When multiple goroutines are modifying the same data.
  • When one goroutine is modifying the data and others are reading it.

If all goroutines are only reading the data, you don't need a mutex.

TryLock

The TryLock method tries to lock the mutex, just like a regular Lock. But if it can't, it returns false right away instead of blocking the goroutine:

var total int
var mu sync.Mutex

var wg sync.WaitGroup
for range 100 {
    wg.Go(func() {
        if !mu.TryLock() {
            return
        }
        defer mu.Unlock()
        time.Sleep(time.Millisecond)
        total++
    })
}
wg.Wait()
total: 1

RWMutex

The sync.RWMutex type distinguishes between readers and writers. It provides two sets of methods:

  • Lock / Unlock lock and unlock the mutex for both reading and writing.
  • RLock / RUnlock lock and unlock the mutex for reading only.
var total int
var mu sync.RWMutex
var wg sync.WaitGroup

// 10 writers.
for range 10 {
    wg.Go(func() {
        mu.Lock()
        defer mu.Unlock()
        time.Sleep(time.Millisecond)
        total++
    })
}

// 10 readers.
for range 10 {
    wg.Go(func() {
        // Try switching from RLock/RUnlock to Lock/Unlock
        //and see how it affects the elapsed time.
        mu.RLock()
        defer mu.RUnlock()
        time.Sleep(time.Millisecond)
        _ = total
    })
}

wg.Wait()
elapsed: 10ms

Here's how it works:

  • If a goroutine locks the mutex with Lock(), other goroutines will be blocked if they try to use Lock() or RLock().
  • If a goroutine locks the mutex with RLock(), other goroutines can also lock it with RLock() without being blocked.
  • If at least one goroutine has locked the mutex with RLock(), other goroutines will be blocked if they try to use Lock().

This creates a "single writer, multiple readers" setup.

Locker

Both sync.Mutex and sync.RWMutex implement the same sync.Locker interface:

type Locker interface {
    Lock()
    Unlock()
}

By using Locker instead of a specific mutex type, you can build components that don't depend on a specific lock implementation. This lets the client decide which lock to use.

Channel as mutex

You can use a channel instead of a mutex to protect shared data:

var total int
lock := make(chan struct{}, 1)

var wg sync.WaitGroup
wg.Go(func() {
    lock <- struct{}{}
    defer func() { <-lock }()
    total++
})
wg.Go(func() {
    lock <- struct{}{}
    defer func() { <-lock }()
    total++
})
wg.Wait()
total: 2

Semaphores

A semaphore is like a container with N available slots and two operations: acquire to take a slot and release to free a slot. Here are the semaphore rules:

  • Calling acquire takes a free slot.
  • If there are no free slots, acquire blocks the goroutine that called it.
  • Calling release frees up a previously taken slot.
  • If there are any goroutines blocked on acquire when release is called, one of them will immediately take the freed slot and unblock.

You can implement a simple semaphore with a buffered channel, where N is the channel's size. To acquire the semaphore, send a value into the channel. To release it, take a value from the channel:

// Try changing nConc and see how the elapsed time changes.
const nConc = 4
const nCalls = 100
sema := make(chan struct{}, nConc)

var wg sync.WaitGroup
for range nCalls {
    sema <- struct{}{} // acquire
    wg.Go(func() {
        defer func() { <-sema }() // release
        time.Sleep(time.Millisecond) // do some work
    })
}
wg.Wait()
elapsed: 25ms

For more complex situations, use the golang.org/x/sync/semaphore package.

Rendezvous

A rendezvous lets two goroutines wait for each other:

  • There are two goroutines — G1 and G2 — and each one can signal that it's ready.
  • If G1 signals but G2 hasn't yet, G1 blocks and waits.
  • If G2 signals but G1 hasn't yet, G2 blocks and waits.
  • When both have signaled, they both unblock and continue running.

You can implement a simple rendezvous with a wait group:

var rend sync.WaitGroup
rend.Add(2)

var wg sync.WaitGroup
wg.Go(func() {
    fmt.Println("before rendezvous")
    rend.Done()
    rend.Wait()
    fmt.Println("after rendezvous")
})
wg.Go(func() {
    fmt.Println("before rendezvous")
    rend.Done()
    rend.Wait()
    fmt.Println("after rendezvous")
})
wg.Wait()
before rendezvous
before rendezvous
after rendezvous
after rendezvous

Barrier

A barrier is a general case of a rendezvous. It lets N goroutines wait for each other:

  • The barrier has a counter (starting at 0) and a threshold N.
  • Each goroutine that reaches the barrier increases the counter by 1.
  • The barrier blocks any goroutine that reaches it.
  • Once the counter reaches N, the barrier unblocks all waiting goroutines.

You can implement a simple barrier with a wait group:

const n = 4
var bar sync.WaitGroup
bar.Add(n)

var wg sync.WaitGroup
for range n {
    wg.Go(func() {
        fmt.Println("before the barrier")
        bar.Done()
        bar.Wait()
        fmt.Println("after the barrier")
    })
}
wg.Wait()
before the barrier
before the barrier
before the barrier
before the barrier
after the barrier
after the barrier
after the barrier
after the barrier

Signaling

The sync.Cond (conditional variable) type lets one goroutine signal to another that it's ready, and lets the other goroutine wait for that signal.

A Cond includes a mutex and has two methods — Wait and Signal.

  • Wait unlocks the mutex and suspends the goroutine until it receives a signal.
  • Signal wakes the goroutine that is waiting on Wait.
  • When Wait wakes up, it locks the mutex again.
cond := sync.NewCond(&sync.Mutex{})
done := false

var wg sync.WaitGroup
wg.Go(func() {
    cond.L.Lock()
    fmt.Println("G1 is ready to signal")
    done = true
    cond.Signal()
    cond.L.Unlock()
})
wg.Go(func() {
    cond.L.Lock()
    for !done {
        cond.Wait()
    }
    fmt.Println("G2 received the signal")
    cond.L.Unlock()
})
wg.Wait()
G1 is ready to signal
G2 received the signal

If there are multiple waiting goroutines when Signal is called, only one of them will be resumed. If there are no waiting goroutines, Signal does nothing.

You can also use the Broadcast method. While Signal wakes up only one goroutine waiting on Cond.Wait, the Broadcast method wakes up all such goroutines.

You can signal with a channel:

signal := make(chan struct{}, 1)

go func() {
    // do something
    signal <- struct{}{}
}()

go func() {
    <-signal
    // do something
}()

And broadcast too:

broadcast := make(chan struct{})

go func() {
    // do something
    close(broadcast)
}()

go func() {
    <-broadcast
    // do something
}()

go func() {
    <-broadcast
    // do something
}()

Broadcasting with a condition variable is limited: it only sends a signal, not the actual data, and it only works once. With channels, you can build a publish/subscribe system that doesn't have these limitations:

type Publisher struct {
    sbox []chan int // subscription channels
    mu   sync.Mutex // protects the state
}

func (p *Publisher) Subscribe() <-chan int {
    p.mu.Lock()
    defer p.mu.Unlock()
    sub := make(chan int, 1)
    p.sbox = append(p.sbox, sub)
    return sub
}

func (p *Publisher) Broadcast(v int) {
    p.mu.Lock()
    defer p.mu.Unlock()
    for _, sub := range p.sbox {
        select {
        case sub <- v:
        default:
        }
    }
}

Run once

The sync.Once type makes sure that the given function runs only once. If multiple goroutines call Once.Do at the same time, only one will run the function, while the others will wait until it returns:

total := 0
initState := func() {
    total += 1
}

var once sync.Once

var wg sync.WaitGroup
wg.Go(func() {
    once.Do(initState)
    // do something
})
wg.Go(func() {
    once.Do(initState)
    // do something
})
wg.Wait()
total: 1

Once is perfect for one-time initialization or cleanup in a concurrent environment.

Besides the Once type, the sync package also includes three convenience once-functions:

// Calls f only once.
func (o *Once) Do(f func())

// Returns a function that calls f only once.
func OnceFunc(f func()) func()

// Returns a function that calls f only once
// and returns the value from that first call.
func OnceValue[T any](f func() T) func() T

// Returns a function that calls f only once
// and returns the pair of values from that first call.
func OnceValues[T1, T2 any](f func() (T1, T2)) func() (T1, T2)

Object pool

The sync.Pool type helps reuse memory instead of allocating it every time, which reduces the load on the garbage collector:

pool := sync.Pool{
    New: func() any {
        buf := make([]byte, 1024)
        return &buf
    },
}

// Only allocates 4*1024 B, despite 4000 loop iterations.
var wg sync.WaitGroup
for range 4 {
    wg.Go(func() {
        for range 1000 {
            buf := pool.Get().(*[]byte)
            sink = buf
            pool.Put(buf)
        }
    })
}
wg.Wait()
Memory allocated: 4 KB

Get takes an item from the pool. If there are no available items, it creates a new one using New (which we have to define ourselves, since the pool doesn't know anything about the items it creates). Put returns an item back to the pool.

Things to keep in mind:

  • New should return a pointer, not a value, to reduce memory copying and avoid extra allocations.
  • The pool has no size limit. If you start 1000 more goroutines that all call Get at the same time, 1000 more buffers will be allocated.
  • After an item is returned to the pool with Put, you shouldn't use it anymore (since another goroutine might already have taken and started using it).

Atomics

An operation without synchronization can only be truly atomic if it translates to a single processor instruction. Such operations don't need locks and won't cause issues when called concurrently (even the write operations).

There are only a few atomics, and they're all found in the sync/atomic package:

Int32     Bool
Int64     Value
Uint32    Pointer
Uint64

Each atomic type provides the following methods:

  • Load reads the value of a variable.
  • Store sets a new value.
  • Swap sets a new value (like Store) and returns the old one.
  • CompareAndSwap sets a new value only if the current value is still what you expect it to be.
var n atomic.Int32
n.Store(10)
swapped := n.CompareAndSwap(10, 42)
fmt.Println("CompareAndSwap 10 -> 42:", swapped)
fmt.Println("n =", n.Load())
CompareAndSwap 10 -> 42: true
n = 42

Numeric types also provide an Add method that increments the value by the specified amount.

All methods are either translated into a single CPU instruction or are otherwise guaranteed to be atomic, so they are safe to use from multiple goroutines.

The composition of atomics is always non-atomic:

var delta atomic.Int32
var counter atomic.Int32

func increment() {
    // Not atomic; causes a race condition.
    delta.Add(1)
    sleep(10)
    counter.Add(delta.Load())
}

// After 100 concurrent increments,
// the final value is NOT guaranteed.
counter = 9386

A bulletproof way to make a composite operation atomic and prevent race conditions is to use a mutex:

var delta int32
var counter int32
var mu sync.Mutex

func increment() {
    // Atomic; doesn't cause a race condition.
    mu.Lock()
    delta += 1
    sleep(10)
    counter += delta
    mu.Unlock()
}

// After 100 concurrent increments, the final value is guaranteed:
// counter = 1+2+...+100 = 5050
counter = 5050

Sometimes you can use an atomic type instead of a mutex to exit early:

type Gate struct {
    closed atomic.Bool
}

func (g *Gate) Close() {
    if !g.closed.CompareAndSwap(false, true) {
        return // ignore repeated calls
    }
    // The gate is closed.
    // We can free resources now.
}

Testing

If your concurrent program uses channels or custom types with synchronization methods like Wait, you can use those in your tests. This way, your tests won't be much more complicated than if the code were synchronous:

// Calc calculates something asynchronously.
func Calc() <-chan int {
    out := make(chan int, 1)
    go func() {
        out <- 42
    }()
    return out
}
func Test(t *testing.T) {
    // Wait for the Calc goroutine to finish.
    got := <-Calc()
    if got != 42 {
        t.Errorf("got: %v; want: 42", got)
    }
}
PASS

If there aren't any suitable synchronization "handles" in the code you're testing, you can use the synctest package. It exports two functions:

func Test(t *testing.T, f func(*testing.T))
func Wait()

synctest.Test runs an isolated bubble. The bubble uses a fake clock, and you can manually control goroutine synchronization with synctest.Wait.

synctest.Wait blocks until all goroutines in the bubble — except the one that called Wait — have either finished or are durably blocked. This lets you wait for a specific goroutine to finish or get blocked, so you can check the program's state:

// NewProc starts the calculation.
func NewProc() *Proc {
    p := &Proc{done: make(chan struct{})}
    go func() {
        p.res = 42
        <-p.done // (X)
        p.res = 0
    }()
    return p
}
func Test(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        p := NewProc()
        defer p.Stop()

        // Wait for the goroutine to block at point X.
        synctest.Wait()
        if got := p.Res(); got != 42 {
            t.Fatalf("got %v, want 42", got)
        }
    })
}
PASS

The fake clock in synctest.Test move forward only if: ➊ all goroutines in the bubble are durably blocked; ➋ there's a future moment when at least one goroutine will unblock; and ➌ synctest.Wait isn't running. Thanks to this, time-dependent tests run instantly:

// Calc processes a value from the input channel.
// Times out if no input is received after 3 seconds.
func Calc(in chan int) (int, error) {
    select {
    case v := <-in:
        return v * 2, nil
    case <-time.After(3 * time.Second):
        return 0, ErrTimeout
    }
}
func Test(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ch := make(chan int)
        got, err := Calc(ch) // runs instantly

        if err != ErrTimeout {
            t.Errorf("got: %v; want: %v", err, ErrTimeout)
        }
        if got != 0 {
            t.Errorf("got: %v; want: 0", got)
        }
    })
}
PASS

The following operations durably block a goroutine:

  • A blocking send or receive on a channel created within the bubble.
  • A blocking select statement where every case is a channel created within the bubble.
  • Calling Cond.Wait.
  • Calling WaitGroup.Wait if all WaitGroup.Add calls were made inside the bubble.
  • Calling time.Sleep.

Blocking on mutexes, I/O, or system calls is not considered durable, and the synctest bubble can't handle them.

Scheduling

At the hardware level, CPU cores are responsible for running parallel tasks.

At the operating system level, a thread is the basic unit of execution. There are usually many more threads than CPU cores, so the operating system's scheduler decides which threads to run and which ones to pause.

At the Go runtime level, a goroutine is the basic unit of execution. The runtime scheduler runs a fixed number of OS threads, often one per CPU core. There can be many more goroutines than threads, so the scheduler decides which goroutines to run on the available threads and which ones to pause. The scheduler keeps switching between goroutines to make sure each one gets a turn to run on a thread, instead of waiting in line forever.

  CPU                  OS                   Go runtime
┌──────────┐  run on ┌──────────┐  run on ┌────────────┐
│ Cores    │ <────── │ Threads  │ <────── │ Goroutines │
└──────────┘         └──────────┘         └────────────┘

This is how Go handles concurrency.

Goroutine scheduler

The goroutine scheduler's job is to run M goroutines on N operating system threads, where M can be much larger than N. Here's a very simplified version of it's algorithm:

  • If there's a free thread, assign it a goroutine from the queue.
  • If a running goroutine gets blocked (for example, while reading from a channel), put it back in the queue and assign a different goroutine to the thread.
  • If a running goroutine gets stuck in a syscall, start a new thread to run other goroutines until the blocked goroutine finishes the syscall.
  • Check the running goroutines every 10 ms. Preempt long-running goroutines and return them to the queue to prevent starvation.
┌─────┐┌─────┐┌─────┐┌─────┐
│ G17 ││ G18 ││ G19 ││ G20 │                        queue
└─────┘└─────┘└─────┘└─────┘

┌─────┐      ┌─────┐      ┌─────┐      ┌─────┐
│ G15 │      │ G16 │      │ G13 │      │ G14 │      running
└─────┘      └─────┘      └─────┘      └─────┘
  │            │            │            │
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Thread E │ │ Thread F │ │ Thread C │ │ Thread D │
└──────────┘ └──────────┘ └──────────┘ └──────────┘

┌─────┐      ┌─────┐
│ G11 │      │ G12 │                                syscalls
└─────┘      └─────┘
  │            │
┌──────────┐ ┌──────────┐
│ Thread A │ │ Thread B │
└──────────┘ └──────────┘

The number of threads running Go code is controlled by the GOMAXPROCS environment variable or the runtime.GOMAXPROCS function.

A goroutine is a structure that starts out using about 2 KB of memory, mostly for its stack. The stack can grow if needed. Since goroutines are so lightweight, you can run tens of thousands or even hundreds of thousands of them on a small machine.

Diagnostics

To troubleshoot concurrent programs in production, we use metrics, profiling, and tracing.

Metrics show how the Go runtime is performing, like how much heap memory it uses or how long garbage collection pauses take. Each metric has a unique name and a value, which can be a number or a histogram.

You can use the runtime/metrics package to get a complete list of metrics or check the values of specific ones:

samples := []metrics.Sample{
    {Name: "/sched/gomaxprocs:threads"},
    {Name: "/sched/goroutines:goroutines"},
}
metrics.Read(samples)

for _, s := range samples {
    fmt.Printf("%s: %v\n", s.Name, s.Value.Uint64())
}
/sched/gomaxprocs:threads: 8
/sched/goroutines:goroutines: 1

In practice, people rarely do this manually. Instead, all metrics are automatically exported using Prometheus or OpenTelemetry libraries.

Profiling helps you understand exactly what the program is doing, what resources it uses, and where in the code this happens. Go uses a sampling profiler that's suitable for production.

The most commonly used profiles are CPU, which shows how much processor time each function uses, and heap, which shows how much heap memory each function uses. Goroutine, block, and mutex profiles help identify problems related to concurrency.

The easiest way to add a profiler to your app is by using the net/http/pprof package. To collect a profile with the given name, call the /debug/pprof/{name} endpoint. To view the collected profile, use the go tool pprof utility:

go tool pprof -proto \
  "http://localhost:6060/debug/pprof/profile?seconds=N" > cpu.pprof
go tool pprof -http=localhost:8080 cpu.pprof

You can also profile manually:

// CPU profile.
file, _ := os.Create("cpu.prof")
defer file.Close()
pprof.StartCPUProfile(file)
defer pprof.StopCPUProfile()
// ...
// Any other profile.
file, _ := os.Create(name + ".prof")
defer file.Close()
pprof.Lookup(name).WriteTo(file, 0)

Tracing records certain types of events while the program is running, mainly those related to concurrency and memory. When the profiling server from the net/http/pprof package is running, call the /debug/pprof/trace endpoint to collect a trace. To view the results, use the go tool trace utility.

You can also collect a trace manually:

file, _ := os.Create("trace.out")
defer file.Close()
trace.Start(file)
defer trace.Stop()
// ...

You can set up automatic tracing with a sliding window that's limited by size or duration. This is called "flight recording". It lets you always keep a recent trace available in case something goes wrong:

cfg := trace.FlightRecorderConfig{
    MinAge:   5 * time.Second,
    MaxBytes: 3 << 20, // 3MB
}
rec := trace.NewFlightRecorder(cfg)
rec.Start()
defer rec.Stop()

Final thoughts

We've covered a number of Go tools for writing concurrent programs:

  • Goroutines for running concurrent tasks.
  • Channels and select as flexible communication tools.
  • Timers and tickers for working with time.
  • Context for canceling operations.
  • Wait groups for synchronizing goroutines.
  • Mutexes to prevent race conditions.
  • Condition variables for signaling events.
  • Once for safe one-time initialization.
  • Pools to reduce garbage collector load.
  • Atomic operations.

If you like the book, please recommend it to your friends or colleagues. If you're interested, check out my other books and projects.

I'm glad you finished the book. Thank you, and I'll see you next time!

]]>
Solod 0.4: Better C interophttps://antonz.org/solod-0.4/Sat, 12 Sep 2026 13:00:00 +0000https://antonz.org/solod-0.4/A strict subset of Go that translates to regular C.Solod is a subset of Go that translates to regular C — with zero runtime, manual memory management, and source-level interop. It's designed for two main audiences:

  • Go developers who want low-level control without having to learn another language.
  • C developers who like Go's style.

The new Solod release provides an easy way to call third-party C libraries, makes a large part of the standard library freestanding, and impoves the tooling.

Automatic bindings • Freestanding packages • Type assertions • C interop • Multi-package testing • Checks and targets • Windows • Wrapping up

Automatic binding generator

Sobind generates bindings — stubs for calling third-party C libraries from Solod. It parses .h files and emits a Solod source file with necessary structs, unions, constants, variables, function pointer typedefs, and function declarations.

You can then use the generated types and functions in regular Solod code:

package main

import (
    "solod.dev/raylib/libraylib"
    "solod.dev/so/c"
)

func main() {
    // Using Raylib bindings.
    libraylib.InitWindow(screenWidth, screenHeight, "☀️ Solod / Raylib")
    defer libraylib.CloseWindow()
    // ...
}

Usually, the generated bindings are good enough to use as they are, without any manual changes. I have also prepared bindings for popular C libraries like libuv, raylib, sodium, and sqlite.

Unlike Go, calling C from Solod has zero overhead — Solod code is just regular C in the end.

More freestanding packages

At some point I decided to make as many packages as possible freestanding — independent of any libc implementation or specific OS runtime. That went pretty well. Solod now has 37 standard library packages, and 31 of them work in freestanding mode.

These packages work in freestanding mode with no restrictions:

bufio  bytealg  bytes  c  cmp  encoding  encoding/binary
encoding/hex  encoding/json  errors  io  maps  math/bits
math/rand  mem  path  runtime  slices  strconv  strings
unicode  unicode/utf8  unsafe

These packages work in freestanding mode with certain limitations:

  • crypto/crand depends on a user-provided hook to read random bytes.
  • fmt depends on a user-provided hook to print formatted text.
  • math offers a working subset of features.
  • net/netip works fully, except it can't resolve an IPv6 zone name.
  • sync/atomic works on targets that support lock-free instructions.
  • testing depends on a user-provided hook to print test results.
  • time reads the clock using user-provided hooks.
  • uuid depends on hooks from both crypto/crand and time.

There's a separate post with more details if you're interested.

Type assertions

A comma-ok type assertion is now fully supported for non-empty interfaces:

var s1 Shape = &rect
r, ok := s1.(*Rect)   // r is &rect, ok is true

var s2 Shape = &circle
c, ok := s2.(*Rect)   // c is nil, ok is false

Which translates to the following C code:

main_Shape s1 = (main_Shape){.self = &rect, .Area = main_Rect_Area};
bool ok = (s1.Area == main_Rect_Area);
main_Rect* r = ok ? (main_Rect*)s1.self : NULL;
// ok == true, r == &rect

main_Shape s2 = (main_Shape){.self = &circle, .Area = main_Circle_Area};
ok = (s2.Area == main_Rect_Area);
main_Rect* c = ok ? (main_Rect*)s2.self : NULL;
// ok == false, c == NULL

Previously, the only two supported forms were a direct assertion like r := s.(*Rect) and a check-only form like _, ok := s.(*Rect).

C interop helpers

The c package now supports more common C types:

size_t      - c.Size
ssize_t     - c.SSize
ptrdiff_t   - c.Ptrdiff
intptr_t    - c.Intptr
long double - c.LongDouble

There's also a c.ConstVoid type, which maps to a C const void. You can use it where C expects a const void* pointer:

// in c
so_ssize_t find_first(const void* items, size_t count, size_t size,
                      bool (*match)(const void*));
// in solod
//so:extern
func find_first(items *c.ConstVoid, count c.Size, size c.Size,
    match func(item *c.ConstVoid) bool) c.SSize

Finally, there are some useful cast functions.

c.Bitcast reads the bits of a value as another type of the same size:

bits := c.Bitcast[uint64](1.0)   // 0x3ff0000000000000
f := c.Bitcast[float64](bits)    // 1.0

You can use c.Bitcast instead of a pointer conversion such as *(*float64)(unsafe.Pointer(&b)).

c.StringData and c.SliceData return a typed pointer to the string or slice data:

b := []byte{1, 2, 3}
p := c.SliceData[c.UChar](b)     // unsigned char*
q := c.StringData[c.UChar]("ab") // unsigned char*

They replace (*T)(unsafe.SliceData(b)) and (*T)(unsafe.StringData(s)).

Multi-package testing

so test can now run tests from multiple packages at once. If you use a pattern that ends with ..., it will select every package that has a test subdirectory under its base directory:

so test ./so/...      # the whole stdlib
so test ./so/net/...  # only the networking packages

The entire run only needs one translation, one compilation, and one execution, which is much faster than running it separately for each package.

The -pkg-file flag restricts the run to only the packages listed in a file:

# freestanding.txt
so/bytes
so/mem
so/time
so test -pkg-file=freestanding.txt ./so/...

Checks and targets

so build, so test, so bench and so run take two new flags: -target and -check.

-target specifies the target platform for cross-compilation. Use the same value that clang and zig cc accept after --target=:

export CC="zig cc"
so build -target=x86_64-windows-gnu -o app.exe .
so build -target=wasm32-freestanding -o main.wasm .

-check enables code analysis:

so test -check=warn .      # -Wall -Wextra -Werror -Wno-shadow -Wno-unused-label
so test -check=sanitize .  # warn + AddressSanitizer + UndefinedBehaviorSanitizer
so test -check=analyze .   # warn + GCC static analyzer

The default optimization level is -O2. You can use CFLAGS to change it.

Limited Windows support

The standard library now builds for windows/amd64 and windows/arm64. All packages in the freestanding set work. Packages that require POSIX (conc, flag, log/slog, net, os, sync) are not supported.

You can use zig cc to cross-compile for Windows:

export CC="zig cc"
export CFLAGS="--target=x86_64-windows-gnu"
export LDFLAGS="-lbcrypt -liphlpapi"
so build -o app.exe .

Not the first-class Windows support that Go offers, but it's better than nothing.

Wrapping up

With v0.4, Solod can work with almost any C library thanks to automatic bindings. The freestanding-aware standard library makes the language a viable option for bare metal programming. Extra interop helpers make C-calling code easy to read, and better tooling keeps tests fast.

There's still a lot to do, of course. In the next release, I plan to focus on the standard library and bring over some hashing and crypto packages from Go. More C library integrations are on the way too!

If you're interested, take a look at Solod's readme — it has everything you need to get started. Or try Solod online without installing anything.

]]>
Going freestandinghttps://antonz.org/going-freestanding/Thu, 20 Aug 2026 12:00:00 +0000https://antonz.org/going-freestanding/Porting Go's standard library to platform-agnostic C.Creating a subset of Go that translates to C (which I named Solod) was never my end goal. I liked writing C code with Go, but without the standard library it felt pretty limited. So the next logical step was to port Go's stdlib.

At some point I decided to make as many packages as possible freestanding — independent of any libc implementation or specific OS runtime. That went pretty well. Solod now has 37 standard library packages, and 31 of them work in freestanding mode.

This post describes the techniques I used to get there. There's nothing genuinely novel, and if you're experienced with C, you probably already know all of them. Still, I think it's useful to document the approach — both for me and for anyone interested.

Freestanding mode • Headers • Builtins • Memory • Atomics • Pure C • Allocation • Values • Hooks • Hosted-only • Testing • Final thoughts

Freestanding mode

C has two types of environments. In a hosted environment, you get the full standard library — either the one required by the C standard or, even better, POSIX. In a freestanding environment, you get almost nothing.

The compiler tells you which one you're in:

#if __STDC_HOSTED__
// libc is available
#else
// you're on your own
#endif

Pass -ffreestanding and link with -nostdlib, and that's it: you no longer have printf, or malloc, or even memcpy. There is no entropy source, no file system operations, and no clock. If libc itself is "hard mode", this is "impossible".

Despite its limitations, freestanding mode can be really useful for microcontrollers, WebAssembly sandboxes, kernels, and anything else without an operating system to rely on.

Freestanding headers

Freestanding does not mean "just the C language". The C standard guarantees some headers even without libc, because they define types and macros instead of functions:

float.h   stdalign.h  stdbool.h  stdint.h
limits.h  stdarg.h    stddef.h   ...

Everything that requires actual function implementations is gone:

assert.h  math.h   stdlib.h  time.h
errno.h   stdio.h  string.h  ...

To reflect the hosted/freestanding split, let's introduce builtin.h, a common header included in every standard library package:

#if __STDC_HOSTED__

#include <assert.h>
#include <inttypes.h>
#include <stdalign.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define so_build_hosted

#else

#include <stdbool.h>
#include <stdint.h>
#include <stdalign.h>
#include <stddef.h>

#endif  // __STDC_HOSTED__

Individual packages follow the same approach: branch on so_build_hosted to distinguish between the hosted and freestanding implementations.

Compiler builtins

GCC and Clang implement some C standard functions without relying on libc. These are known as compiler builtins.

__builtin_trap causes the program to terminate abnormally. You can use it to implement poor man's assertion and panic:

#ifdef so_build_hosted

#define so_panic(msg)                                     \
    do {                                                  \
        fprintf(stderr, "panic: %s\n  %s:%d (func %s)\n", \
                msg, __FILE__, __LINE__, __func__);       \
        exit(1);                                          \
    } while (0)

#else

#define assert(cond)                   \
    do {                               \
        if (!(cond)) __builtin_trap(); \
    } while (0)

#define so_panic(msg)     \
    do {                  \
        (void)msg;        \
        __builtin_trap(); \
    } while (0)

#endif // so_build_hosted

From now on, I'll mainly show the freestanding versions and omit the hosted versions to keep things simple.

The __builtin_alloca function allocates memory on the stack. Its bounded wrapper limits the size of each allocation:

#define alloca __builtin_alloca

// The maximum size that can be allocated
// with alloca (64 KB by default).
#ifndef SO_MAX_ALLOCA_SIZE
#define SO_MAX_ALLOCA_SIZE (64 << 10)  // in bytes
#endif

#define so_alloca(size) ({                                \
    size_t _size = (size_t)(size);                        \
    if (_size > SO_MAX_ALLOCA_SIZE)                       \
        so_panic("alloca: size exceeds maximum allowed"); \
    _size ? alloca(_size) : NULL;                         \
})

Memory operations

The memxxx functions from string.h have matching builtins too, so you might expect a freestanding build to provide them for you:

// int memcmp(const void* lhs, const void* rhs, size_t n);
#define memcmp __builtin_memcmp

// void* memcpy(void* dst, const void* src, size_t n);
#define memcpy __builtin_memcpy

// void* memmove(void* dst, const void* src, size_t n);
#define memmove __builtin_memmove

// void* memset(void* dst, int ch, size_t n);
#define memset __builtin_memset

Unfortunately, there's no free lunch here.

__builtin_memcpy is not a separate memcpy implementation. If n is small and known at compile time, the compiler expands it into a few load and store instructions. But if n is large or only known at runtime, it calls the actual memcpy from libc instead.

Even worse, you don't need to mention memcpy explicitly to use it. Suppose you copy a large struct like this:

typedef struct { char buf[4096]; } Big;

void copy(Big* a, const Big* b) {
    *a = *b;
}

When you compile the code for aarch64-freestanding, the object file contains an undefined reference to memcpy. Zero-initializing a local array produces the same issue with memset. Neither name appears in the source; both are introduced by the compiler.

So the freestanding environment must still provide memcpy, memmove, memset, and memcmp for memory operations to work in the general case.

WebAssembly covers three of the four: memcpy, memmove, and memset map to the memory.copy and memory.fill instructions. There is no instruction for comparison, so memcmp stays a real function call even there. On other targets, the toolchain often provides all four, as zig cc does (even with -nostdlib). If it doesn't, provide a plain C implementation:

#undef memcpy
void* memcpy(void* dst, const void* src, size_t n) {
    unsigned char* d = dst;
    const unsigned char* s = src;
    while (n--) *d++ = *s++;
    return dst;
}

#undef memset
void* memset(void* dst, int ch, size_t n) {
    unsigned char* d = dst;
    while (n--) *d++ = (unsigned char)ch;
    return dst;
}

#undef memmove
void* memmove(void* dst, const void* src, size_t n) {
    // omitted for brevity
}

#undef memcmp
int memcmp(const void* lhs, const void* rhs, size_t n) {
    const unsigned char* l = lhs;
    const unsigned char* r = rhs;
    for (; n--; l++, r++) {
        if (*l != *r) return *l - *r;
    }
    return 0;
}

The defines (#define memcpy __builtin_memcpy and others above) are still worth keeping, even if you implement the functions yourself. This way, the compiler can still use its own implementation when applicable.

Fun fact: at -O2 and above, GCC can fold your custom memcpy implementation back into a call to memcpy, which is infinite recursion. -ffreestanding prevents this because it implies -fno-builtin, but the guarantee is weak. You can use -fno-tree-loop-distribute-patterns to disable this behavior for good.

The rest of string.h is not covered. No compiler provides memchr or strlen, so those you always have to write yourself — more on that below.

Atomic operations

Another useful group of compiler builtins is __atomic_xxx, which provide atomic, thread-safe memory access. They operate on regular objects instead of _Atomic objects:

// so_atomic_load atomically loads the value at p.
#define so_atomic_load(p) \
    (__atomic_load_n((p), __ATOMIC_SEQ_CST))

// so_atomic_store atomically stores v at p.
#define so_atomic_store(p, v) \
    (__atomic_store_n((p), (v), __ATOMIC_SEQ_CST))

This makes porting Go's sync/atomic types straightforward. All types — atomic integers, unsigned integers, booleans, and pointers — use the same two load/store macros:

// Bool is an atomic boolean value. The zero value is false.
typedef struct atomic_Bool {
    bool v;
} atomic_Bool;

// Load atomically loads and returns the value stored in x.
bool atomic_Bool_Load(atomic_Bool* x) {
    return so_atomic_load(&x->v);
}

// Store atomically stores val into x.
void atomic_Bool_Store(atomic_Bool* x, bool val) {
    so_atomic_store(&x->v, val);
}

A separate atomic_Bool type isn't strictly required — atomic_Bool_Load and atomic_Bool_Store would work with a plain bool*. Still, it can be useful. With a plain pointer, *x = true creates a silent data race that looks like ordinary code, while the wrapper makes you explicitly write x->v = true.

No stdatomic.h include is needed. However, the CPU must natively support the integer width you use. For example, a 64-bit atomic on a 32-bit target becomes a call to libatomic instead of a single instruction. But that's a different story.

Pure C implementations

If the compiler doesn't provide an implementation, you have to write one yourself. Preferably, use the libc name so all call sites remain unchanged.

A good example is memchr, which is required by bytes.IndexByte. There is a __builtin_memchr, but it is not an implementation, so you need to provide your own:

#ifndef so_build_hosted
// memchr implementation for freestanding environments.
static inline void* memchr(const void* s, int c, size_t n) {
    const unsigned char* p = s;
    unsigned char target = (unsigned char)c;
    while (n--) {
        if (*p == target) return (void*)p;
        p++;
    }
    return NULL;
}
#endif

Some of these DIY implementations aren't trivial, of course. Fortunately, Go's standard library includes many standalone algorithms, such as the string-to-number conversion functions in strconv or integer math in math/bits. Porting them to C is almost mechanical:

// Go version.
const m3 = 0x00ff00ff00ff00ff

// ReverseBytes32 returns the value of x
// with its bytes in reversed order.
func ReverseBytes32(x uint32) uint32 {
    const m = 1<<32 - 1
    x = x>>8&(m3&m) | x&(m3&m)<<8
    return x>>16 | x<<16
}
// C version.
static const int64_t m3 = 0x00ff00ff00ff00ff;

uint32_t bits_ReverseBytes32(uint32_t x) {
    const int64_t m = ((int64_t)1 << 32) - 1;
    x = ((x >> 8) & (m3 & m)) | ((x & (m3 & m)) << 8);
    return (x >> 16) | (x << 16);
}

Memory allocation

Memory allocation calls for a different technique. A naive approach would be to implement a freestanding malloc that uses a static buffer:

extern char so_heap[SO_HEAP_SIZE];
extern size_t so_heap_offset;

static inline void* malloc(size_t size) {
    // Simplified version without alignment.
    if (size > SO_HEAP_SIZE - so_heap_offset) {
        return NULL;
    }
    void* ptr = &so_heap[so_heap_offset];
    so_heap_offset += size;
    return ptr;
}

It might be sufficient for testing, but I'd avoid using it in production.

Instead of reimplementing malloc, let's remove the need for it, and make the caller provide the memory. Start with an allocator interface, so callers don't depend on a specific implementation:

// Allocator defines the interface for memory allocators.
// Simplified version without Realloc and alignment.
typedef struct {
    void* self;
    so_R_ptr_err (*Alloc)(void* self, so_int size);
    void (*Free)(void* self, void* ptr, so_int size);
} mem_Allocator;

What's with the so-types?

so_int is an integer of the target width:

#if SIZE_MAX == 0xFFFFFFFFu
typedef int32_t so_int;
#else
typedef int64_t so_int;
#endif

so_String is a pointer to the underlying string bytes and their count:

typedef struct {
    const char* ptr;
    so_int len;
} so_String;

so_Error is an interface value that wraps the error data:

typedef struct {
    void* self;
    so_String (*Error)(void* self);
} so_Error;

so_R_ptr_err is a result-type implementation for a (pointer + error) pair:

typedef struct {
    void* val;
    so_Error err;
} so_R_ptr_err;

There are other similar types like so_R_int_err (int + error) or so_R_f32_bool (float32 + bool).

Then provide an arena allocator, which is freestanding by design:

// Arena is a memory allocator that bump-allocates
// linearly within a fixed buffer.
typedef struct {
    so_Slice buf;
    so_int offset;
} mem_Arena;

mem_Arena mem_NewArena(so_Slice buf) {
    return (mem_Arena){.buf = buf};
}

so_R_ptr_err mem_Arena_Alloc(void* self, so_int size) {
    // Simplified version without alignment.
    mem_Arena* a = self;
    assert(size > 0 && "mem: invalid allocation size");
    if (size > so_len(a->buf) - a->offset) {
        return (so_R_ptr_err){.val = NULL, .err = mem_ErrOutOfMemory};
    }
    void* ptr = &so_at(so_byte, a->buf, a->offset);
    a->offset += size;
    return (so_R_ptr_err){.val = ptr, .err = (so_Error){}};
}

void mem_Arena_Free(void* self, void* ptr, so_int size) {
    // Free in arena is a no-op.
    (void)self; (void)ptr; (void)size;
}

void mem_Arena_Reset(void* self) {
    mem_Arena* a = self;
    a->offset = 0;
}

Usage example:

typedef struct Point {
    so_int x;
    so_int y;
} Point;

// Prepare the arena.
so_byte data[1024];
so_Slice buf = {.ptr = data, .len = sizeof(data)};
mem_Arena arena = mem_NewArena(buf);
mem_Allocator alloc = {
    .self = &arena,
    .Alloc = mem_Arena_Alloc,
    .Free = mem_Arena_Free};

// Allocate a Point. mem_Alloc is a macro that calls
// the Alloc "method" and panics on failure.
Point* p = mem_Alloc(Point, alloc);
p->x = 11;
p->y = 22;

On a freestanding target, an arena is a better choice than a buffer-backed malloc, because the caller decides how much memory is available and when it's released.

Values, not pointers

Constructor functions in Go typically return a pointer:

// A string reader.
type Reader struct {
    s        string
    i        int64 // current reading index
    prevRune int   // index of previous rune; or < 0
}

// NewReader returns a new Reader reading from s.
func NewReader(s string) *Reader {
    return &Reader{s, 0, -1}
}

This roughly translates to the following code, using the memory allocator from the previous section:

// A string reader.
typedef struct {
    so_String s;
    int64_t i;
    so_int prevRune;
} strings_Reader;

// NewReader returns a new Reader reading from s.
// The returned reader is allocated; the caller owns it.
strings_Reader* strings_NewReader(mem_Allocator alloc, so_String s) {
    strings_Reader* r = mem_Alloc(strings_Reader, alloc);
    r->s = s;
    r->i = 0;
    r->prevRune = -1;
    return r;
}

Instead of blindly following Go idioms, it's better to get rid of allocations altogether and return a value:

// NewReader returns a new Reader reading from s.
strings_Reader strings_NewReader(so_String s) {
    return (strings_Reader){.s = s, .prevRune = -1};
}

This isn't a technique specific to writing freestanding code — it's helpful for almost any C library.

Target hooks

Some things you can't write in a target-agnostic way at all. Only the target knows how to print a byte, read the clock, or generate a random number; these all depend on the hardware.

What you can do is declare functions (hooks) and let the user's code define them:

Hook Description
so_write_out send some bytes to the output
so_crand_read read some random bytes
so_time_wall get the current wall clock time
so_time_mono get the current monotonic time
so_time_sleep pause for a given duration

Then the user can call specific APIs available on their hardware:

so_int so_write_out(const uint8_t* buf, so_int size) {
    return board_uart_write(buf, size);
}

int64_t so_time_mono(void) {
    return (int64_t)board_uptime_ms() * 1000000;
}

What happens if the user doesn't provide an implementation? You still want the standard library to compile and work unless someone calls the missing functions. To achieve that, use weak definitions:

// so_write_out drops the bytes and reports a full write,
// so panic and fmt print nothing and report no error.
__attribute__((weak)) so_int so_write_out(const uint8_t* buf, so_int size) {
    (void)buf;
    return size;
}

// so_crand_read reads no bytes. The interpretation is left to the caller.
__attribute__((weak)) so_int so_crand_read(uint8_t* buf, so_int size) {
    (void)buf;
    (void)size;
    return 0;
}

// so_time_wall panics, because no default date is correct.
__attribute__((weak)) so_R_i64_i32 so_time_wall(void) {
    so_panic("time: define so_time_wall for this target");
}

Now every hook gets a default, and a definition in the user code silently wins over the default one.

Note that the defaults above behave differently on purpose. Dropping output is fine because a board with no UART (serial interface) has nowhere to print. Inventing a date is not fine, because no date would be correct.

For the same reason, crypto/rand panics instead of falling back to a software generator. A "random" source that silently returns predictable bytes would be a terrible idea:

// crand_read fills buf with size cryptographically secure random bytes.
// Panics if the target does not define so_crand_read.
static inline void crand_read(uint8_t* buf, so_int size) {
    if (size <= 0) return;
    if (so_crand_read(buf, size) != size) {
        so_panic("crypto/rand: no entropy source");
    }
}

You can still use a fallback when cryptographic security isn't needed, such as for hashing map keys or math/rand:

// runtime_Seed returns a random 64-bit seed.
static inline uint64_t runtime_Seed(void) {
    uint64_t seed = 0;
    // Use cryptographically secure random if available.
    if (so_crand_read((uint8_t*)&seed, 8) == 8 && seed != 0) {
        return seed;
    }
    // Fallback to deterministic xorshift64 sequence.
    // ...
}

Hosted-only

Some things aren't worth solving with hooks, such as the os and net packages, which require a lot of target-specific code. In these cases, it's better to use a header-level guard that fails in freestanding mode:

// so/os/os.h
#include "so/builtin/builtin.h"

#ifndef so_build_hosted
#error "os: hosted environment required"
#endif

If user code imports os in a freestanding environment, the compiler reports an error at compile time instead of at link time or runtime.

Testing

The only way to know if the freestanding implementation actually works is to test it.

My approach in Solod is to run the freestanding packages' test suites with a WASI runtime and a small harness. The harness defines all five hooks from the Target hooks section as WASI imports:

// ciovec is the buffer descriptor that fd_write reads.
// The WASI ABI is 32-bit, so both fields are 32-bit.
typedef struct {
    const uint8_t* buf;
    uint32_t len;
} ciovec;

// wasi_fd_write writes the buffers to the file descriptor
// and stores the number of bytes written in nwritten.
__attribute__((import_module("wasi_snapshot_preview1"), import_name("fd_write")))
extern uint32_t wasi_fd_write(uint32_t fd, const ciovec* iovs,
                              uint32_t iovs_len, uint32_t* nwritten);

// so_write_out writes size bytes to the standard output of the WASI host.
so_int so_write_out(const uint8_t* buf, so_int size) {
    ciovec iov = {.buf = buf, .len = (uint32_t)size};
    uint32_t written = 0;
    if (wasi_fd_write(1, &iov, 1, &written) != 0) {
        return 0;
    }
    return (so_int)written;
}

The freestanding make task builds tests from stdlib packages into a single wasm32-freestanding binary and runs it with wasmtime. This uses the same tests for the freestanding logic as in hosted mode, so I don't need to write separate freestanding tests.

Final thoughts

Here's a summary of the approach I used write a freestanding stdlib in C:

  • Choose between hosted and freestanding at compile time.
  • Use the compiler builtins when possible.
  • Implement the missing parts and port the standalone code.
  • Use explicit allocators; prefer values to pointers.
  • Declare hooks for the hardware, with weak defaults.
  • Fail fast for packages that can't work in freestanding.
  • Test in a freestanding build, not just hosted.

I hope you find it useful too.

If you're interested in trying this in practice, take a look at Solod's readme — it has everything you need to get started. Or try it online without installing anything.

]]>
Relying on Gohttps://antonz.org/relying-on-go/Sun, 09 Aug 2026 12:00:00 +0000https://antonz.org/relying-on-go/Reusing Go's tooling and standard library for a systems language.Everyone is creating a new programming language these days, often one that's "like Go but with more features" or "like Rust but simpler".

Solod, a systems language for C and Go developers, might look like one of those languages, but it takes a different approach.

Go's tooling

Solod is not "Go-like" in the usual sense, nor is it an attempt to "fix Go's mistakes". At the language level, Solod is literally a subset of Go. Solod reuses much of Go's existing tooling, including syntax highlighting, LSP, linters, and the package management system.

Take this quick-start guide, for example:

Quick start

Install the Solod command line tool:

go install solod.dev/cmd/so@latest

Create a new Go project and add the dependency to use the Solod standard library:

go mod init example
go get solod.dev@latest

Write regular Go code, but use Solod packages instead of the standard Go packages:

package main

import "solod.dev/so/math"

func main() {
    ans := math.Sqrt(1764)
    println("Hello, world! The answer is", int(ans))
}

Run without saving the binary:

so run .

That's it!

There's nothing new here. It's mostly standard Go workflow, except for so run, which is a Go program that mimics go run.

Go's standard library

Solod also reuses a lot of Go's standard library code and tests. Some of it is taken verbatim from Go's source code, like these two string functions:

// CutPrefix returns s without the provided leading prefix string
// and reports whether it found the prefix.
func CutPrefix(s, prefix string) (string, bool) {
    if !HasPrefix(s, prefix) {
        return s, false
    }
    return s[len(prefix):], true
}

// HasPrefix reports whether the string s begins with prefix.
func HasPrefix(s, prefix string) bool {
    return len(s) >= len(prefix) && s[:len(prefix)] == prefix
}

Of course, Solod retains the Go authors' copyright.

Some code requires changes to support the manual memory management with explicit allocators used by Solod:

// Go version.
func Clone(s string) string {
    if len(s) == 0 {
        return ""
    }
    b := make([]byte, len(s))
    copy(b, s)
    return unsafe.String(&b[0], len(b))
}
// Solod version.
func Clone(a mem.Allocator, s string) string {
    if len(s) == 0 {
        return ""
    }
    b := mem.AllocSlice[byte](a, len(s), len(s))
    copy(b, s)
    return string(b)
}

You can probably see the resemblance.

A grain of salt

Go tools don't know that Solod is a subset of the full Go language, so they won't flag features Solod doesn't support, like function literals or iterators. These diagnostics come from the custom so tooling:

package main

func main() {
    f := func(n int) {
        println(n)
    }
    f(42)
}
main.go:4:7: function literals are not supported
    f := func(n int) {
         ^here

Also, although a substantial part of Go's standard library is ported verbatim or with minimal changes from the original source, that doesn't mean the code is automatically correct. Solod still needs its own tests, including ones that run under sanitizers and static analyzers.

It's all C in the end

All Solod code is translated to regular C11 and then compiled with GCC or Clang. Solod therefore relies on C tooling and decades of optimization work just as much as on Go's.

Solod code:

package main

import "solod.dev/so/math"

func main() {
    // What might it be?
    ans := math.Sqrt(1764)
    println("Hello, world! The answer is", int(ans))
}

Translated C code:

// -- main.h --
#pragma once
#include "so/builtin/builtin.h"
#include "so/math/math.h"

// -- main.c --
#include "main.h"

int main(void) {
    // What might it be?
    double ans = math_Sqrt(1764.0);
    so_println("%s %" PRIdINT, "Hello, world! The answer is", (so_int)(ans));
    return 0;
}

The C version is noisier, of course, especially for more complex programs than this one. But it remains readable.

And since there's no runtime, interoperability between Solod and C costs nothing.

Final thoughts

A new language doesn't necessarily need a new ecosystem.

Solod relies heavily on Go, and I see that as a strength, not a weakness. Reusing Go's proven tools and standard library makes Solod more reliable and easier to work with.

If you're interested, take a look at Solod's readme — it has everything you need to get started. Or try it online without installing anything.

]]>
Going Backward: Reinventing Go's iteratorhttps://antonz.org/going-backward/Mon, 03 Aug 2026 12:00:00 +0000https://antonz.org/going-backward/Building a generic iterator wheel from scratch.Go's standard library has a slices package with a function called Backward. It lets you iterate over the elements of a slice in reverse order:

// Backward returns an iterator over index-value pairs in the slice,
// traversing it backward with descending indices.
func Backward[Slice ~[]E, E any](s Slice) iter.Seq2[int, E]

If you're not deeply familiar with generics and iterators, the natural reaction to this signature (and to the others in the slices package) is: "couldn't this have been made simpler somehow?"

To answer that, let's run a thought experiment. Let's picture ourselves as a distant ancestor, living in the pre-iterator era, who decided to implement Backward from scratch.

Our imaginary ancestor doesn't work at Google, so don't project their decisions onto the Go development team. They had their own reasons — and no Jira.

1. A slice in reverse

A pleasant, sunny summer day, birds singing. You're at the keyboard as usual, and suddenly you decide to write a function for walking a slice in reverse order. Anything beats working on yet another Jira ticket.

// Backward returns the slice in reverse order.
func Backward[T any](s []T) []T {
    n := len(s)
    res := make([]T, n)
    for i := n - 1; i >= 0; i-- {
        res[n-1-i] = s[i]
    }
    return res
}

Usage example:

s := []int{11, 22, 33, 44, 55}
b := Backward(s)
fmt.Println(b)
// [55 44 33 22 11]

The implementation is simple and works reliably. There's one drawback, though: Backward creates a copy of the slice, which can be wasteful for large slices.

Besides, the sun has hidden behind a cloud, and it looks like rain is coming. You decide to work a bit more.

2. Gimme, gimme, gimme

To avoid copying the slice, you decide to return a closure that knows the current position in the original slice and returns the next element on each call:

// Backward returns a function that, on each call, returns the next
// element of the slice (in reverse order) and a flag indicating
// whether to continue iterating (false means done).
func Backward[T any](s []T) func() (T, bool) {
    i := len(s)
    return func() (T, bool) {
        if i == 0 {
            var zero T
            return zero, false
        }
        i--
        return s[i], true
    }
}

Usage example:

s := []int{11, 22, 33, 44, 55}
next := Backward(s)
for {
    v, ok := next()
    if !ok {
        break
    }
    fmt.Print(v, " ")
}
fmt.Println()
// 55 44 33 22 11

Now it allocates O(1) memory instead of O(n). That's better.

Before moving on, you glance out of the window. Yep, sure enough, the rain has started, and the sky is even cloudier than before. Excellent working weather!

3. A callback-based iterator

Something about the calling code keeps bothering you. It came out quite imperative. You'd like to hand the loop mechanics over to Backward and leave the caller with nothing but the application logic (whatever it is you do with the slice elements).

You decide to complicate Backward's signature a little. Now it will return an iterator function that takes a callback as an argument and applies it to each element of the slice:

// Backward returns a function that takes a yield callback.
// The callback is invoked for each element of the slice (in reverse order).
func Backward[T any](s []T) func(yield func(T) bool) {
    return func(yield func(T) bool) {
        for i := len(s) - 1; i >= 0; i-- {
            if !yield(s[i]) {
                return
            }
        }
    }
}

The yield function returns a bool — that's so the callback can signal when it wants to stop the traversal early.

Now you can turn the for loop body in the calling code into a callback, and you don't need the loop anymore:

work := func(x int) bool {
    if x < 30 {
        return false // early exit
    }
    fmt.Print(x, " ")
    return true
}

s := []int{11, 22, 33, 44, 55}
it := Backward(s)
it(work)
fmt.Println()
// 55 44 33

Mmm, very functional.

One small nuance: Backward's signature looks a bit heavy. You add a separate type for the return value:

// Seq is an iterator over sequences of individual values.
// When called as seq(yield), seq calls yield(v) for each value
// v in the sequence, stopping early if yield returns false.
type Seq[T any] func(yield func(T) bool)

The function looks much better now:

func Backward[T any](s []T) Seq[T] {
    // body unchanged
}

Praising yourself for inventing the iterator, you walk over to the window. It looks like the weather's gotten worse. The rain is coming down in buckets, and the sky is so overcast that it's grown as dark as evening.

4. Iterator 2: Return of the Iterator

It's all great, but then it hits you: an ordinary range over a slice returns both the index and the element's value. Your iterator returns only the value. You decide to fix this vexing oversight:

func Backward[T any](s []T) func(yield func(int, T) bool) {
    return func(yield func(int, T) bool) {
        for i := len(s) - 1; i >= 0; i-- {
            if !yield(i, s[i]) {
                return
            }
        }
    }
}

Usage example:

work := func(i int, x int) bool {
    fmt.Print(i, ":", x, " ")
    return true
}

s := []int{11, 22, 33, 44, 55}
it := Backward(s)
it(work)
fmt.Println()
// 4:55 3:44 2:33 1:22 0:11

Since the result's signature has changed, it no longer fits the Seq type. What can you do — you'll have to add a new type. After ten minutes of deliberation, you decide to call it Seq2:

// Seq2 is an iterator over sequences of key-value pairs.
// When called as seq(yield), seq calls yield(k, v) for each pair
// (k, v) in the sequence, stopping early if yield returns false.
type Seq2[K any, V any] func(yield func(K, V) bool)
func Backward[T any](s []T) Seq2[int, T] {
    // body unchanged
}

You get up to stretch your legs, and go to the window. The downpour is so heavy you can't make anything out. Lightning is flashing. Hail the size of your fist is falling — you've never seen anything like it in your life. Well, these things happen!

5. Not quite a slice

Have you thought of everything? Seems so. But you're not going back to Jira tickets just yet. Refreshing your memory of the Go spec, you realize that besides ordinary slices there are "user-defined" ones — types whose underlying type is a slice:

// IDs is a slice of identifiers.
type IDs []int

Backward works perfectly well with IDs — the compiler accepts a value of type IDs since its underlying type is []int:

ids := IDs{11, 22, 33, 44, 55}
it := Backward(ids)
it(work)
fmt.Println()
// 4:55 3:44 2:33 1:22 0:11

But what about this?

// backwardIDs builds an iterator over a slice of identifiers
// in reverse order.
var backwardIDs func(IDs) Seq2[int, int] = Backward[int]
// ERROR: cannot use Backward[int]
// (value of type func(s []int) Seq2[int, int])
// as func(IDs) Seq2[int, int] value in variable declaration

Here's where the difference between IDs and []int shows up.

When you assign the function itself, it's the signatures that get compared: func(IDs) Seq2[int, int] versus func([]int) Seq2[int, int]. Signatures match only if the parameter types are identical. But IDs and []int are different, even though one is based on the other. The signatures differ → you get an error.

Scratching your head, you turn to the spec once again and find a special generic syntax: ~T. It represents the set of all types whose underlying type is T. Just what you need!

Now you'll have to parameterize not only the element type (E) but the slice type (Slice) as well. E is needed for the returned values, while Slice lets the function accept not just []E, but any types based on it:

func Backward[Slice ~[]E, E any](s Slice) Seq2[int, E] {
    return func(yield func(int, E) bool) {
        for i := len(s) - 1; i >= 0; i-- {
            if !yield(i, s[i]) {
                return
            }
        }
    }
}

Now the example:

var backwardIDs func(IDs) Seq2[int, int] = Backward[IDs, int]

ids := IDs{11, 22, 33, 44, 55}
work := func(i int, x int) bool {
    fmt.Print(i, ":", x, " ")
    return true
}
it := backwardIDs(ids)
it(work)
fmt.Println()
// 4:55 3:44 2:33 1:22 0:11

It works! You've ended up with something similar to Backward from the slices package.

You exhale wearily and walk over to the window. The downpour and hail have given way to a hurricane. Trees and billboards go flying past. Toads, for some reason, are falling from the sky.

6. Iterator 3: Judgment Day

To take your mind off the strange events outside the window, you keep pondering.

An ordinary Backward is already great. But it would be even better if the traversal logic itself were configurable. On the other hand, if you end up with a lot of parameters, a strategy would suit better. And, by the way, it wouldn't hurt to add a factory that produces iterator factories according to given criteria...

Before you can finish the thought, the ground outside the window tears open with a deafening roar. An enormous black hand, streaming molten lava and flickering flames, bursts out of the fissure, seizes you, and drags you straight down to hell.

P.S. Despite the article's tongue-in-cheek tone, the "complicated" version in the standard library is justified (Backward just follows suite with other package functions). But if you're doing something similar in a project that solves a specific problem — it might make sense to stop at the simpler option.

]]>
Solod 0.3: Concurrency, JSON, more safetyhttps://antonz.org/solod-0.3/Sat, 25 Jul 2026 11:30:00 +0000https://antonz.org/solod-0.3/A strict subset of Go that translates to regular C.Solod is a subset of Go that translates to regular C — with zero runtime, manual memory management, and source-level interop. It's designed for two main audiences:

  • Go developers who want low-level control without having to learn another language.
  • C developers who like Go's style.

At the end of the v0.2 post, I said the obvious goal for the next release was concurrency, along with the stdlib packages that support it. That's what v0.3 is about. Solod now has threads, channels, worker pools, mutexes, and atomics — enough tools for parallel data processing or handling network connections.

This release also adds a streaming JSON package, a bunch of safety checks (escape analysis, leak checking, nil-pointer panics, stack traces), and proper so test and so bench commands.

Threads • Channels • Worker pools • Sharing state • JSON • Safety net • Tooling • Wrapping up

Threads

The new conc package is the foundation. It provides real OS threads, backed by pthreads. If you're familiar with Go's goroutines, the code will look similar — but there are some important differences.

// greet prints a label three times.
func greet(arg any) any {
    from := arg.(string)
    for i := range 3 {
        println(from, "->", i)
    }
    return nil
}

func main() {
    // Run greet on a separate OS thread, concurrently with main.
    name := "thread"
    th := conc.Go(greet, name)

    // Wait blocks until the thread finishes.
    th.Wait()
    println("done")
}
thread -> 0
thread -> 1
thread -> 2
done

Solod doesn't support closures, so conc.Go takes a function and an any argument, instead of just a func() like you'd expect in Go.

Other important differences: starting an OS thread isn't free, and you always have to Wait on it (or Detach it), or it will leak. That makes conc.Go a good fit for a small, fixed number of long-lived threads — but not for thousands of short-lived tasks. For those cases, it's better to use a pool (shown below).

Channels

Threads in Solod communicate with each other through channels, like goroutines in Go. A channel carries values of a specific type. By default, sending or receiving on a channel blocks until both sides are ready, so a channel also works as a synchronization point.

// ping sends a single message on the given channel.
func ping(arg any) any {
    messages := arg.(*conc.Chan[string])
    messages.Send("ping")
    return nil
}

func main() {
    // An unbuffered channel (buffer size 0): each send blocks
    // until a receiver is ready to take the value.
    messages := conc.NewChan[string](mem.System, 0)
    defer messages.Free()

    // Launch a thread that sends "ping" into the channel.
    th := conc.Go(ping, &messages)
    defer th.Wait()

    // Receive the message and print it.
    var msg string
    messages.Recv(&msg)
    println(msg)
}
ping

A couple of Solod-specific moments here. When you create a channel, you give it an allocator (mem.System in this case), and you call Free when you're done with it. Also, Recv writes to a pointer you pass in, instead of returning the value directly. It returns a bool, which is false when the channel is closed and empty. So, a typical for msg := range ch loop in Go becomes for ch.Recv(&msg) { ... } in Solod.

Allocators are a key concept in Solod. The language doesn't allow hidden heap allocations, so any function that needs to allocate memory must take an allocator (the mem.Allocator interface) as its first argument.

Buffered channels can hold a limited number of values without having a receiver ready — just pass a non-zero size with NewChan. If you don't want to block forever, use RecvTimeout or SendTimeout with a duration. They return conc.Ok or conc.Timeout instead of getting stuck.

Worker pools

Threads are expensive, so spawning one per task doesn't scale. For handling many short-lived tasks, use conc.Pool: it uses a fixed number of worker threads that take tasks from a queue.

// job holds input and the result.
type job struct {
    id     int
    result int
}

// process handles one job.
func process(arg any) {
    j := arg.(*job)
    time.Sleep(100*time.Millisecond)
    j.result = j.id * 2
}

func main() {
    // A pool of 4 worker threads. Each submitted job is handled
    // by the next available worker.
    pool := conc.NewPool(mem.System, conc.PoolOptions{NumThreads: 4})
    defer pool.Free()

    // Submit 8 jobs. Each writes into its own struct, so keep
    // the structs alive in a slice until the jobs finish.
    start := time.Now()
    jobs := make([]job, 8)
    for i := range jobs {
        jobs[i].id = i + 1
        pool.Go(process, &jobs[i])
    }

    // Wait until all submitted jobs have finished.
    pool.Wait()

    for i := range jobs {
        println("job", jobs[i].id, "->", jobs[i].result)
    }
    elapsed := time.Since(start) / 1_000_000
    println("took", elapsed, "ms")
}
job 1 -> 2
job 2 -> 4
job 3 -> 6
job 4 -> 8
job 5 -> 10
job 6 -> 12
job 7 -> 14
job 8 -> 16
took 200 ms

pool.Wait() works similar to Go's WaitGroup.Wait — it blocks until all submitted jobs are finished. This program takes about 200 ms to run (even though there's 800 ms of total work), because 4 workers run concurrently.

You might think OS threads are much slower than Go's goroutines, but for pools, that's not the case. On realistic workloads, conc.Pool is usually only about 10% slower than Go, whether the tasks are CPU-bound or waiting on I/O. Channels are a different story: handing off work between threads requires a kernel wakeup, while Go does this in user space, so it can be several times slower. Check out Go-flavored concurrency in C for more details.

Sharing state

One way to share state in Solod is by using channels to communicate it. However, sometimes you just need a shared counter or a lock. For that, the new release introduces the sync and sync/atomic packages.

Here's an example of an atomic counter being updated by 50 tasks running on 4 threads:

// increment atomically increases the shared counter 1000 times.
func increment(arg any) {
    ops := arg.(*atomic.Uint64)
    for range 1000 {
        ops.Add(1)
    }
}

func main() {
    // An atomic value is safe for concurrent reads and writes.
    var ops atomic.Uint64

    pool := conc.NewPool(mem.System, conc.PoolOptions{NumThreads: 4})
    defer pool.Free()

    // 50 tasks, each incrementing the counter 1000 times.
    for range 50 {
        pool.Go(increment, &ops)
    }
    pool.Wait()

    println("ops:", ops.Load())
}
ops: 50000

A regular int incremented with ops++ would cause a data race and give a different result each time. Here, the result is exactly 50,000 on every run, thanks to the atomic Uint64 counter. The atomic package provides Int64, Uint64, Bool, and Pointer[T] types, all of which are lock-free and safe for concurrent use.

For anything more complex than a counter, use sync, which provides Mutex, Cond (a condition variable), and Once (runs a function exactly once). One thing to watch out for: unlike Go, a Solod mutex's zero value isn't ready to use — you need to Init it before locking and Free it when done.

var mu sync.Mutex
mu.Init()
defer mu.Free()

mu.Lock()
defer mu.Unlock()
// ... critical section ...

JSON

Go's encoding/json relies on reflection to marshal arbitrary structs. Solod has no reflection, and uses a different approach: a token-level API. You read and write one JSON token at a time, and the Encoder and Decoder types take care of the syntax — adding commas and colons, checking UTF-8, and rejecting bad input.

Encoding is done through a series of calls that match the structure of your document:

out := make([]byte, 256)
sb := strings.FixedBuilder(out)
enc := json.NewEncoder(&sb)

enc.BeginObject()
enc.Str("name")
enc.Str("Alice")
enc.Str("age")
enc.Int(25)
enc.EndObject()
enc.Flush()

println(sb.String())
{"name":"Alice","age":25}

Decoding pulls one validated token at a time with Next. You can check each token with Kind and read its value using typed getters like Str, Int, or Bool:

src := `{"name":"Alice","age":25}`
dec := json.NewDecoder(mem.System, []byte(src))
defer dec.Free()

var name string
var age int64

dec.Next() // the opening {
for dec.Next() && dec.Kind() == json.KindString {
    switch dec.Str() {
    case "name":
        dec.Next()
        name = dec.Str()
    case "age":
        dec.Next()
        age = dec.Int()
    default:
        dec.Next()
        dec.Skip()
    }
}

println(name, age)
Alice 25

This is a simplified example that works only because the decoder doesn't allocate any memory. In a real-world situation, you'd need to use an allocator.

The decoder works the same way whether you're using an in-memory document (NewDecoder) or reading from a stream with an io.Reader (NewReader). This means you can decode data directly from a source without having to buffer the entire message first. Both the encoder and decoder use minimal memory and will reject invalid JSON or non-UTF-8 strings.

As you can see, API is low-level and not nearly as ergonomic as it is in Go, especially when it comes to decoding. But on the bright side, it's 10 times faster and almost doesn't allocate, unlike in Go.

Safety net

Solod compiles to plain C, which is fast but not very forgiving: if you use an out-of-bounds index, dereference nil, or divide by zero, you get undefined behavior that could crash the program or silently give wrong results. The new release addresses some of these issues.

Escape analysis. Returning a pointer to a stack-allocated value is a classic C footgun. Solod now catches the common cases at compile time:

type Point struct{ x, y int }

func newPoint(x, y int) *Point {
    return &Point{x: x, y: y}
    //     ^ compile-time error: stack-allocated
    //       value escapes function frame
}

func main() {
    p := newPoint(3, 4)
    println(p.x, p.y)
}
so run: /tmp/sandbox/main.go:26:12: stack-allocated value escapes function frame
    return &Point{x: x, y: y}
           ^here (exit status 1)

While the escape analyzer doesn't catch every case, it's still quite useful in practice. I actually found a couple of dangling pointers in the standard library code with it, even though I was sure there weren't any.

Leak detection. Solod has no garbage collector, so a forgotten Free is a real memory leak. mem.Tracker helps catch these leaks: it wraps an allocator and keeps track of every allocation and free that goes through it. This way, you can monitor the program's memory usage in real time instead of guessing.

Wrap mem.System once, allocate memory through the tracker, and have a background thread log the stats at regular intervals:

// monitor periodically logs live allocation stats.
func monitor(arg any) any {
    t := arg.(*mem.Tracker)
    for {
        time.Sleep(100 * time.Millisecond)
        s := t.Stats()
        println("live:", s.Mallocs-s.Frees, "allocations,", s.Alloc, "bytes")
    }
    return nil
}

func main() {
    // Wrap the system allocator to count every allocation and free.
    heap := &mem.Tracker{Allocator: mem.System}

    // Watch memory from a background thread.
    conc.Go(monitor, heap).Detach()

    // Allocate through heap so the monitor sees it.
    for i := range 10 {
        v := mem.Alloc[int](heap) // intentionally not freeing it
        *v = i
        time.Sleep(50*time.Millisecond)
    }
    // ...
}
live: 2 allocations, 16 bytes
live: 4 allocations, 32 bytes
live: 6 allocations, 48 bytes
live: 8 allocations, 64 bytes
live: 10 allocations, 80 bytes

The tracker is lock-free and only uses a few atomic operations for each allocation, so it's cheap enough to keep enabled in production.

Nil-pointer panics. If you try to dereference a nil pointer, it will cause a panic at runtime instead of a raw segmentation fault:

type Rect struct{ width, height int }

func (r *Rect) area() int {
    return r.width * r.height
    //     ^ runtime error: nil pointer dereference
}

func main() {
    var r *Rect
    println(r.area())
}
panic: nil pointer dereference

Stack traces. When a program panics, the -panic flag controls what happens next:

so run -panic=trace .  # print a stack trace, then exit(1) - the default
so run -panic=exit  .  # just exit(1) after the message
so run -panic=abort .  # raise SIGABRT for a debugger or core dump

Stack trace frames represent each function in the call chain:

func main() {
    Work()
}

func Work() {
    res := Calc(42)
    println(res)
}

func Calc(x int) int {
    if x == 42 {
        panic("can't handle 42")
    }
    return x * 2
}
panic: can't handle 42
/tmp/solod_build764532392/main.c:27 (func main_Calc)
/tmp/solod_run1106942066(main_Calc+0x51)
/tmp/solod_run1106942066(main_Work+0x12)
/tmp/solod_run1106942066(main+0x9)

The same system handles assertions like slice bounds, index-out-of-range, c.Assert, and similar checks. Instead of calling C's assert, they panic in a way that respects the -panic flag.

There's also a new -sanitize flag that enables C sanitizers (address and undefined by default) to help you catch more issues during development:

so run -sanitize -panic=abort example/play

Tooling

'so test' and 'so bench'. Solod now has built-in test and benchmark runners. so test finds TestXxx(t *testing.T) functions in a package's test subdirectory, creates a runner, transpiles it, and runs it. so bench does the same for BenchmarkXxx(b *testing.B).

A typical package layout with tests and benchmarks looks like this:

so/uuid
├── bench
│   ├── main.go
│   └── uuid.go
├── test
│   ├── main.go
│   └── uuid.go
└── uuid.go

There's also a quick check for memory leaks: t.Allocator() gives you a tracking allocator (described in the 'Safety net' section above), and the test will fail if anything allocated with it isn't freed by the end of the test.

=== RUN   TestAlloc
    memory leak: 1 unfreed allocation(s), 16 byte(s)
--- FAIL: TestAlloc

Fuzzing. Since Solod is a strict subset of Go, any Solod package is also a valid Go package. This means you get Go's built-in fuzzer for free, making fuzz testing pretty easy. Solod's encoding/json package takes advantage of this by using Go's own encoding/json as an oracle, making sure that every JSON document accepted by Solod is also accepted by Go.

Automatic linking. The new so:link directive lets a package specify which C library it needs, and so build gathers these libraries and passes them to the C compiler. The standard packages already use the new directive, so importing so/math links with -lm, and so/sync or so/conc links with -lpthread — you no longer have to set LDFLAGS manually.

Wrapping up

With v0.3, Solod reaches an important milestone: a program can now do multiple things at once. The JSON package gives programs a standard way to communicate, and the safety checks help prevent silent failures — both during development and in production.

There's still a lot to do, of course. In the next release, the standard library will keep growing, and the language and tooling will get better to make programming in Solod more convenient and safe.

If you're interested, take a look at Solod's readme — it has everything you need to get started. Or try Solod online without installing anything.

]]>
On interactive Go tourshttps://antonz.org/on-go-tours/Sat, 11 Jul 2026 12:30:00 +0000https://antonz.org/on-go-tours/Wrapping up the series.Over the past two years, I've published interactive tours for five Go releases, from 1.22 to 1.26.

I know some of you have read them, and I've received a lot of kind words from you (even some core Go team members reached out) — thank you so much for that!

Tour history: Go 1.22 • 1.23 • 1.24 • 1.25 • 1.26 + Go features by version

Unfortunately, at some point, writing these tours stopped being fun and started to feel like a part-time job. I'm not really excited about that, so I've decided to stop.

I still like Go (well, most of it). I read and write Go code. I'm still pretty close to the language and will probably continue to write about it.

But the interactive tours story is over.

]]>