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.
Code
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
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.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.