FNV Hashing For Shard Keys

Hash keys with hash/fnv for deterministic shard assignment, and reuse one hasher via Reset to avoid allocating on every call.

GoResilience

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"hash/fnv"
)

func shardFor(key string, shards uint32) uint32 {
	// FNV hashing: New32a gives a deterministic 32-bit digest
	h := fnv.New32a()
	_, _ = h.Write([]byte(key))
	return h.Sum32() % shards
}

func main() {
	keys := []string{"user:1", "user:2", "session:9", "job:42", "job:43"}
	for _, key := range keys {
		fmt.Printf("%-10s -> shard %d\n", key, shardFor(key, 4))
	}

	// 复用同一个 hasher:Reset 清空状态但不重新分配
	h := fnv.New64a()
	_, _ = h.Write([]byte("alpha"))
	first := h.Sum64()
	h.Reset()
	_, _ = h.Write([]byte("alpha"))
	second := h.Sum64()
	fmt.Println("stable after reset:", first == second)
}

How the snippet works

The compressed view: all the work sits in the functions shardFor and main, doing all the work.

The file repeats itself only inside for _, key := range keys.

Applying it

Entry signature: func shardFor(key string, shards uint32) uint32

The demo output is labeled (stable after reset:), so the printed output reads as a trace of the operations performed.

main is the driver: it invokes shardFor before returning.

Statements that matter most here

func shardFor(key string, shards uint32) uint32 {
	// FNV hashing: New32a gives a deterministic 32-bit digest
	h := fnv.New32a()
	_, _ = h.Write([]byte(key))
	return h.Sum32() % shards
}
for _, key := range keys {
	fmt.Printf("%-10s -> shard %d\n", key, shardFor(key, 4))
}

Interactive Tools for This Topic

FAQ

What does FNV Hashing For Shard Keys print when run?
Execute the whole file; each printed line is prefixed with a label like `stable after reset:`.