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.
Code
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
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.