AlgoViz

Inside a key-value store

medium 24 min

A distributed key-value store keeps simple pairs on many machines.

A small replicated store

Read it, run it, change a line and run it again.

Loading editor…

One process plays all nodes. It shows the ring, N = 3 copies, W and R, versions, and read repair.

The same in Go
package mainimport (	"crypto/sha256"	"encoding/binary"	"fmt"	"sort"	"sync")type ConsistentHash struct {	ring     []uint64          // sorted hash values	nodes    map[uint64]string // hash -> node	replicas int               // virtual nodes per machine	mu       sync.RWMutex}func NewConsistentHash(replicas int) *ConsistentHash {	return &ConsistentHash{nodes: map[uint64]string{}, replicas: replicas}}func hash(key string) uint64 {	h := sha256.Sum256([]byte(key))	return binary.BigEndian.Uint64(h[:8])}func (c *ConsistentHash) AddNode(id string) {	c.mu.Lock()	defer c.mu.Unlock()	for i := 0; i < c.replicas; i++ {		h := hash(fmt.Sprintf("%s#%d", id, i))		c.ring = append(c.ring, h)		c.nodes[h] = id	}	sort.Slice(c.ring, func(i, j int) bool { return c.ring[i] < c.ring[j] })}// GetNodes returns up to n different machines, clockwise from the key.func (c *ConsistentHash) GetNodes(key string, n int) []string {	c.mu.RLock()	defer c.mu.RUnlock()	h := hash(key)	start := sort.Search(len(c.ring), func(i int) bool { return c.ring[i] >= h })	seen := map[string]bool{}	out := []string{}	for s := 0; s < len(c.ring) && len(out) < n; s++ {		id := c.nodes[c.ring[(start+s)%len(c.ring)]]		if !seen[id] {			seen[id] = true			out = append(out, id)		}	}	return out}// GetNode returns the first owner, or "" for an empty ring.func (c *ConsistentHash) GetNode(key string) string {	if got := c.GetNodes(key, 1); len(got) == 1 {		return got[0]	}	return ""}func main() {	c := NewConsistentHash(64)	for _, n := range []string{"A", "B", "C", "D"} {		c.AddNode(n)	}	fmt.Println(c.GetNode("user:123"), c.GetNodes("user:123", 3))}