Discord's Read States service spiked in latency and CPU every 2 minutes. The cause was Go garbage collection: in the Go versions Discord ran, if no collection had happened for 2 minutes, Go forced one anyway, and each collection scanned a cache of tens of millions of read states.

What does the Read States service do?

In its February 2020 post, Discord described Read States as the service tracking which channels and messages each user had read. It sat in the hot path: every connect, every message sent, every message read. Each server held a Least Recently Used (LRU) cache in memory with millions of users and tens of millions of read states, and hundreds of thousands of cache updates per second.

Why the scan cost so much

The team suspected garbage collection, but the code made very few allocations. The answer was in the Go source: in the versions they ran, if garbage collection had not run for 2 minutes, Go forced one anyway, whatever the heap growth.

Go's collector is a tracing collector: it finds live memory by starting from roots and following every pointer it finds. Its cost follows the live data it has to scan. Discord described its case as the collector scanning the entire LRU cache, tens of millions of read states, to decide what was still referenced.

Why a smaller cache did not fix it

Less to scan should mean shorter scans, so Discord added a cache size setting and split each server's cache into many smaller partitioned caches. The spikes did get smaller, but a smaller cache meant more misses, and a miss meant a database load. The post says this raised 99th percentile latency: a large cache meant big spikes every 2 minutes, while a small cache meant smaller spikes but higher p99.

What the Rust rewrite changed

Discord already used Rust elsewhere and this service was small and self-contained, so they ported it. Rust manages memory through ownership and drop rules, without a mandatory garbage collector, and a read state evicted from the LRU cache is freed at once. In their load test, the Rust version's latency was as good as Go's with no latency spikes, and after more tuning it beat Go on latency, CPU and memory. Discord later raised the cache capacity to 8 million read states.

How to check your own service

Look for long-lived, pointer-heavy objects in memory, plus latency spikes that repeat on a fixed interval. Plot p99 latency and CPU over an hour, and run with GODEBUG=gctrace=1 to line the cycles up with the graphs. Before shrinking a cache, measure the miss rate and the database load it will add.

Our take

In Go, a large live cache containing pointers can add tracing work even when allocation profiles show little new allocation. Before you shrink the cache or change language, measure GC work and cache misses, then decide which cost you would rather pay.

Read the full article: https://systemdesignsimple.com/discord-go-garbage-collection-latency-spikes/