consistent: Index | Examples | Files

package consistent

import ""

Package consistent provides a consistent hashing function.

Consistent hashing is often used to distribute requests to a changing set of servers. For example, say you have some cache servers cacheA, cacheB, and cacheC. You want to decide which cache server to use to look up information on a user.

You could use a typical hash table and hash the user id to one of cacheA, cacheB, or cacheC. But with a typical hash table, if you add or remove a server, almost all keys will get remapped to different results, which basically could bring your service to a grinding halt while the caches get rebuilt.

With a consistent hash, adding or removing a server drastically reduces the number of keys that get remapped.

Read more about consistent hashing on wikipedia:



Package Files



var ErrEmptyCircle = errors.New("empty circle")

ErrEmptyCircle is the error returned when trying to get an element when nothing has been added to hash.

type Consistent Uses

type Consistent struct {
    NumberOfReplicas int

    UseFnv bool
    // contains filtered or unexported fields

Consistent holds the information about the members of the consistent hash circle.

func New Uses

func New() *Consistent

New creates a new Consistent object with a default setting of 20 replicas for each entry.

To change the number of replicas, set NumberOfReplicas before adding entries.


c := consistent.New()
users := []string{"user_mcnulty", "user_bunk", "user_omar", "user_bunny", "user_stringer"}
for _, u := range users {
    server, err := c.Get(u)
    if err != nil {
    fmt.Printf("%s => %s\n", u, server)


user_mcnulty => cacheA
user_bunk => cacheA
user_omar => cacheA
user_bunny => cacheC
user_stringer => cacheC

func (*Consistent) Add Uses

func (c *Consistent) Add(elt string)

Add inserts a string element in the consistent hash.

func (*Consistent) Get Uses

func (c *Consistent) Get(name string) (string, error)

Get returns an element close to where name hashes to in the circle.

func (*Consistent) GetN Uses

func (c *Consistent) GetN(name string, n int) ([]string, error)

GetN returns the N closest distinct elements to the name input in the circle.

func (*Consistent) GetTwo Uses

func (c *Consistent) GetTwo(name string) (string, string, error)

GetTwo returns the two closest distinct elements to the name input in the circle.

func (*Consistent) Members Uses

func (c *Consistent) Members() []string

func (*Consistent) Remove Uses

func (c *Consistent) Remove(elt string)

Remove removes an element from the hash.

func (*Consistent) Set Uses

func (c *Consistent) Set(elts []string)

Set sets all the elements in the hash. If there are existing elements not present in elts, they will be removed.

Package consistent imports 6 packages (graph) and is imported by 30 packages. Updated 2019-10-01. Refresh now. Tools for package owners.