go-redis/redis · error
redis: invalid database number: %q
Error message
redis: invalid database number: %q
What it means
Returned by setupTCPConn when the single path segment of a redis:// URL is not a base-10 integer. The path (e.g. /3) selects the logical database; if strconv.Atoi fails on it, this error names the offending segment.
Source
Thrown at options.go:700
func setupTCPConn(u *url.URL) (*Options, error) {
o := &Options{Network: "tcp"}
o.Username, o.Password = getUserPassword(u)
h, p := getHostPortWithDefaults(u)
o.Addr = net.JoinHostPort(h, p)
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)
}
if u.Scheme == "rediss" {
o.TLSConfig = &tls.Config{
ServerName: h,
MinVersion: tls.VersionTLS12,
}
}
return setupConnParams(u, o)
}
// getHostPortWithDefaults is a helper function that splits the url into
// a host and a port. If the host is missing, it defaults to localhost
// and if the port is missing, it defaults to 6379.View on GitHub (pinned to 36d97525cd)
Solutions
- Use a plain integer for the DB: redis://host:6379/3.
- Omit the path entirely to select DB 0, or set Options.DB after ParseURL.
- Prefer the ?db=N query parameter if you want to keep the path empty.
Example fix
// before
opt, err := redis.ParseURL("redis://localhost:6379/db0")
// after
opt, err := redis.ParseURL("redis://localhost:6379/0") Defensive patterns
Strategy: validation
Validate before calling
func validDBPathSegment(seg string) bool { _, err := strconv.Atoi(seg); return err == nil } Type guard
func parseDBPath(u *url.URL) (int, bool) {
segs := strings.FieldsFunc(u.Path, func(r rune) bool { return r == '/' })
if len(segs) != 1 { return 0, false }
db, err := strconv.Atoi(segs[0]); return db, err == nil
} Prevention
- Use a bare integer for the DB path segment.
- Omit the path entirely to default to DB 0.
- Prefer ?db=N over the path form for clarity.
When it happens
Trigger: A URL like redis://host:6379/db0, redis://host:6379/abc, or redis://host:6379/3x where the path component after the first slash is non-numeric.
Common situations: Confusing the DB selector with a path label (putting 'db0' in the URL), trailing slashes or stray characters in the path, or copy-pasting a URL that worked with another convention.
Related errors
- redis: invalid URL scheme: %s
- redis: invalid URL path: %s
- redis: invalid %s number: %s
- redis: invalid %s duration: %w
- redis: invalid %s boolean: expected true/false/1/0 or an emp
AI-assisted analysis of go-redis/redis@36d97525cd (2026-08-06).
Data as JSON: /data/errors/c4bdb129ae7c27ed.json.
Report an issue: GitHub.