Skip to content

Fix MOVED errors by not randomly selecting another node #1001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,31 @@ func (c *ClusterClient) slotMasterNode(slot int) (*clusterNode, error) {
return c.nodes.Random()
}

func (c *ClusterClient) tryAnotherNode(cmd Cmder) *clusterNode {
cmdInfo := c.cmdInfo(cmd.Name())
slot := c.cmdSlot(cmd)

state, err := c.state.Get()
if err != nil {
return nil
}

// Read only can be retried on another slave.
if c.opt.ReadOnly && cmdInfo != nil && cmdInfo.ReadOnly {
node, err := state.slotSlaveNode(slot)
if err != nil {
return nil
}

return node
}

// Cannot try any other node for writes as the prevAddr is the only
// acceptable node. Choosing another node will just result in MOVED errors
// being produced and wasting round-trip requests.
return nil
}

func (c *ClusterClient) Watch(fn func(*Tx) error, keys ...string) error {
if len(keys) == 0 {
return fmt.Errorf("redis: Watch requires at least one key")
Expand Down Expand Up @@ -971,11 +996,23 @@ func (c *ClusterClient) defaultProcess(cmd Cmder) error {
continue
}

// Second try random node.
node, err = c.nodes.Random()
if err != nil {
break
// Further attempts try another node, if possible.
//
// For writes this won't be possible
// as any other node will either be the wrong master (for another slot) or a slave that
// can't serve writes.
//
// For reads this may be possible if `ReadOnly` is set to true. A potentially
// random slave can be chosen for the next attempt.
//
// If another node cannot be selected, the current node will be kept for the next
// attempts.
if otherNode := c.tryAnotherNode(cmd); otherNode == nil {
continue
} else {
node = otherNode
}

continue
}

Expand Down