Maphash In-Process Sharding Seeds

Route string keys to shards with maphash: fast per-process hashing whose seed differs every run, so hashes are never persisted or shared across processes.

GoData Integrity

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"hash/maphash"
)

func main() {
	// seed 每次进程启动都不同:maphash 快,但哈希值不持久化、不跨进程复现
	seed := maphash.MakeSeed()

	keys := []string{"orders", "billing", "auth", "search"}
	shards := make([]int, 4)
	for _, k := range keys {
		h := maphash.String(seed, k)
		shards[h%4]++
		fmt.Printf("%-8s -> shard %d\n", k, h%4)
	}
	fmt.Println("shard loads:", shards)

	// 同一进程内同一 seed:相同输入得到相同哈希,可做分片路由
	fmt.Println("stable in-process:",
		maphash.String(seed, "orders") == maphash.String(seed, "orders"))
}

How control moves

Maphash In-Process Sharding Seeds comes down to the function main.

Iteration happens inside for _, k := range keys — everything outside it runs once.

Applying it

Running the file prints labeled results such as shard loads:, stable in-process: — each operation’s effect is visible in the output.

Statements that matter

for _, k := range keys {
h := maphash.String(seed, k)
shards[h%4]++
fmt.Printf("%-8s -> shard %d\n", k, h%4)
}
shards := make([]int, 4)

Interactive Tools for This Topic

FAQ

What does Maphash In-Process Sharding Seeds print when run?
The script runs standalone; its 2 labeled outputs include `shard loads:`, `stable in-process:`.