redis/go-redis · error

redis: invalid database number: %q

Error message

redis: invalid database number: %q

What it means

ParseFailoverURL's path component must be a single integer naming the Redis database index. When the path is non-empty but cannot be parsed as an integer (strconv.Atoi fails), setupFailoverConn returns this error wrapping the offending segment.

Source

Thrown at sentinel.go:453

	switch u.Scheme {
	case "rediss":
		o.TLSConfig = &tls.Config{ServerName: h, MinVersion: tls.VersionTLS12}
	case "redis":
		o.TLSConfig = nil
	default:
		return nil, fmt.Errorf("redis: invalid URL scheme: %s", u.Scheme)
	}

	f := strings.FieldsFunc(u.Path, func(r rune) bool {
		return r == '/'
	})
	switch len(f) {
	case 0:
		o.DB = 0
	case 1:
		var err error
		if o.DB, err = strconv.Atoi(f[0]); err != nil {
			return nil, fmt.Errorf("redis: invalid database number: %q", f[0])
		}
	default:
		return nil, fmt.Errorf("redis: invalid URL path: %s", u.Path)
	}

	return setupFailoverConnParams(u, o)
}

func setupFailoverConnParams(u *url.URL, o *FailoverOptions) (*FailoverOptions, error) {
	q := queryOptions{q: u.Query()}

	o.MasterName = q.string("master_name")
	o.ClientName = q.string("client_name")
	o.RouteByLatency = q.bool("route_by_latency")
	o.RouteByLatencyTolerance = q.duration("route_by_latency_tolerance")
	o.RouteRandomly = q.bool("route_randomly")
	o.ReplicaOnly = q.bool("replica_only")
	o.UseDisconnectedReplicas = q.bool("use_disconnected_replicas")

View on GitHub (pinned to c5cad058c7)

Solutions

  1. Use a numeric database in the path: redis://host:26379/2
  2. Remove the path entirely if DB 0 is fine (empty path defaults to DB 0)
  3. Move the master name to FailoverOptions.MasterName instead of the URL path

Example fix

// before
opt, err := redis.ParseFailoverURL("redis://myapp-db")
// after
opt, err := redis.ParseFailoverURL("redis://myapp-db/0")
Defensive patterns

Strategy: validation

Validate before calling

u, err := url.Parse(raw)
if err != nil { return err }
p := strings.TrimPrefix(u.Path, "/")
if p != "" {
    if _, err := strconv.Atoi(p); err != nil { return fmt.Errorf("path must be numeric DB index, got %q", p) }
}

Try / catch

opt, err := redis.ParseFailoverURL(raw)
if err != nil {
    if strings.Contains(err.Error(), "invalid database number") { /* fix URL path */ }
    return err
}

Prevention

When it happens

Trigger: Calling ParseFailoverURL with a path like "/mydb", "/0/master", or "/01a" — anything that is present but not a pure integer.

Common situations: Putting the master name in the path (it belongs in the masterName option or as a query/other field), or pasting a URL where the path holds a database *name* rather than a numeric index.

Related errors


AI-assisted analysis of redis/go-redis@c5cad058c7 (2026-09-01). Data as JSON: /api/errors/c30d7edf35c7f2cb. Report an issue: GitHub.