distcache: a groupcache-style distributed cache in Go, built to learn

A learning project in Go: a read-through distributed cache with consistent hashing, singleflight, an LRU and a hot cache, standard library only.

Abdeldjalil Chougui (Open-Source)7 min read0 kali dilihat
distcache: a groupcache-style distributed cache in Go, built to learn

Putting a cache in front of a database is simple on one server. On several servers, three problems appear together. If every node caches on its own, the same value is loaded and stored many times. If a popular key is missing, hundreds of requests may ask the database for it at the same moment. And when you add or remove a node, you do not want every key to change place.

groupcache is a well-known Go design that answers all three, and I wanted to understand it by writing my own version. distcache is a groupcache-style distributed read-through cache in Go, using only the standard library. Every key has exactly one owner node, and other nodes ask the owner over HTTP instead of hitting your database.

What it does

The project is four small packages:

  • consistenthash: a hash ring with virtual nodes that picks a key's owner.
  • singleflight: collapses concurrent loads of the same key into one.
  • lru: a size-bounded least-recently-used cache.
  • distcache: ties them together. A Pool is one node (peers, ring, HTTP handler). A Group is a cache namespace with a Getter, a main cache for the keys this node owns, and a small hot cache for popular keys owned by others.

A read goes through these steps:

Group.Get(key)
  main cache / hot cache hit?            → return
  singleflight(key):
    owner = ring.Get(key)
    owner is another node?  GET owner/_distcache/<group>/<key>
        ok         → maybe keep a copy in the hot cache → return
        not found  → return ErrNotFound (no second load)
        unreachable→ fall through and load locally
    Getter(key) → main cache → return
  after each insert: evict LRU entries until main+hot ≤ cacheBytes
  (from the hot cache while it is over 1/8 of main)

On the owner's side, a request to /_distcache/<group>/<key> is answered from its cache or by a singleflight call to the Getter. It is never forwarded again, so nodes with different peer lists cannot send a request around in a loop.

What I built from scratch, and what it teaches

Consistent hashing. The obvious way to choose a node is hash(key) % N. The problem appears when N changes: almost every key gets a new owner, and the whole cache is cold at once. A hash ring moves only about 1/N of the keys. But a ring with one point per node spreads keys unevenly, which is why each node gets many virtual nodes on the ring. The tests check this with numbers: balance across 4 nodes with 200 virtual nodes, and adding a 5th node moves about 1/5 of 40,000 keys, and only to the new node.

Thundering herds. A cold popular key can trigger hundreds of identical backend queries at once. singleflight turns them into one: the first caller does the work, and the others wait for its result. It runs in two places, on the requesting node and on the owner. One test sends 90 concurrent requests for one key, spread over all nodes, and checks that they cause one backend load and at most one peer request per node.

Hot keys. If a key is very popular, its owner becomes a bottleneck, because every other node keeps asking it. So the requesting node keeps a copy of some values in its hot cache. The policy is the one groupcache uses: 1 in 10 fetches is kept, so mostly the frequently requested keys stay. The hot cache is capped at about 1/8 of the cache.

Fill-only caches. There is no Set and no Delete. That sounds like a missing feature, and it is a design choice: if values never change under a key, they never go stale between nodes, and no invalidation protocol is needed. It only works for data that does not change under a key. For data that changes, you put the version in the key, for example user:42:v7.

How to use it

Add the library to your module:

go get github.com/AbdeldjalilChougui/distcache@latest

Or install the demo binary:

go install github.com/AbdeldjalilChougui/distcache/cmd/distcache@latest

The demo runs three nodes in front of a fake backend that takes 300 ms per load:

go build -o distcache ./cmd/distcache
P=http://127.0.0.1:8001,http://127.0.0.1:8002,http://127.0.0.1:8003
./distcache -addr 127.0.0.1:8001 -peers $P &
./distcache -addr 127.0.0.1:8002 -peers $P &
./distcache -addr 127.0.0.1:8003 -peers $P &

curl -i 127.0.0.1:8001/get/user:42   # X-Owner shows which node loaded it
curl -i 127.0.0.1:8003/get/user:42   # fast: fetched from the owner's cache
curl 127.0.0.1:8001/stats

The first request pays the 300 ms. The second one goes to a different node and is still fast, because that node fetches the value from the owner's cache.

As a library, you create a pool, tell it the peers, mount its HTTP handler and define a group with the function that loads from your real data source:

pool := distcache.NewPool("http://10.0.0.1:8000", distcache.PoolOptions{})
pool.Set("http://10.0.0.1:8000", "http://10.0.0.2:8000", "http://10.0.0.3:8000")
http.Handle(distcache.DefaultBasePath, pool)

users := pool.NewGroup("users", 64<<20, distcache.GetterFunc(
	func(ctx context.Context, key string) ([]byte, error) {
		return loadUserFromDB(ctx, key)
	}), distcache.Options{})

v, err := users.Get(ctx, "user:42")

The 64<<20 is the group's byte budget: 64 MiB for the main and hot caches together.

How it is tested

go test -race ./...

The small packages have their own tests: LRU eviction order and byte accounting, a hand-computable hash ring with exact owners, and a singleflight test where 50 concurrent callers run the function once, and errors and panics do not wedge the group.

The main tests run a 3-node in-process cluster over real HTTP on 127.0.0.1. They check that:

  • every key is loaded from the backend exactly once, by its owner, no matter which node is asked;
  • the hot cache serves repeated requests locally when enabled, and every request goes to the owner when it is not;
  • when the owner is down, the node falls back to a local load;
  • not-found is passed through and not retried;
  • LRU eviction keeps the cache under its byte budget and drops the oldest keys;
  • keys with /, spaces, ?, # and % survive the URL round trip.

Things to know

This is a learning project. The README lists these limits:

  • No expiry, no Set, no Delete, by design. Data that changes needs versioned keys.
  • Peer membership is a static list passed to Pool.Set. There is no discovery and no health checking. A dead owner is detected per request, with the HTTP client timeout, and the key is loaded locally.
  • When the peer list changes, keys move to new owners and are loaded again there. The old copies just age out.
  • The hot-cache policy is random sampling, not a real frequency counter.
  • A load's context is the first caller's context. If that caller gives up, the callers waiting on the same flight get its error.
  • Plain HTTP with no authentication between nodes.

What I learned

The first lesson is that these three pieces are each small, and the design is in how they fit. The ring answers "who owns this key". singleflight answers "who is already loading it". The LRU answers "what do we drop". None of them knows about the others.

The second is the value of removing a feature. Without Set and Delete, there is nothing to invalidate, nothing to replicate and no ordering problem between nodes. Versioned keys move the hard part to the caller, where it is often easy.

The third came from a limitation: sharing one load between many callers also shares its fate. If the first caller's context is cancelled, everyone waiting gets that error. The README lists it as a limitation.

Get the code

The source, the demo and the tests are on GitHub: https://github.com/AbdeldjalilChougui/distcache. It is MIT licensed. The consistenthash and singleflight packages are short and can be read on their own.


Originally published at abdeldjalilchougui.biz.


Sumber artikel open-source oleh Abdeldjalil Chougui di DEV Community — Baca artikel asli. Topik: #opensource #go #backend

Sukai & bagikan artikel ini

Komentar