Introduction Database connection strings that contain special characters in passwords (like `@`, `#`, `&`, `/`, `%`) can cause connection failures when the characters are not properly URL-encoded. This issue commonly appears during credential rotation when new passwords contain special characters.
Symptoms - Application throws "could not connect to server" or "connection refused" errors after password change - Connection string parser interprets `@` in password as the host delimiter boundary - `pq: password authentication failed` errors despite correct credentials - Redis clients report `ERR invalid URL` or `Malformed connection string`
Common Causes - The `@` character in a password terminates the userinfo section prematurely in `://user:password@host` format - Ampersand `&` characters in query parameters are treated as parameter separators - Percent `%` characters not followed by valid hex digits cause URL decoding failures - Forward slash `/` in passwords conflicts with the database name path separator
Step-by-Step Fix 1. **URL-encode the password before embedding in the connection string**: ```bash # Use Python to encode the password python3 -c "import urllib.parse; print(urllib.parse.quote('MyP@ss#w0rd&2024'))" # Output: MyP%40ss%23w0rd%262024 ```
- 1.Update PostgreSQL connection string with encoded password:
- 2.
` - 3.postgresql://app_user:MyP%40ss%23w0rd%262024@db.example.com:5432/production
- 4.
` - 5.For MySQL, use the same encoding in the DSN:
- 6.
` - 7.mysql://app_user:MyP%40ss%23w0rd%262024@db.example.com:3306/production?sslmode=required
- 8.
` - 9.For MongoDB connection strings, encode the full URI:
- 10.
` - 11.mongodb+srv://app_user:MyP%40ss%23w0rd%262024@cluster0.example.com/production?retryWrites=true
- 12.
` - 13.For Redis, either encode or use separate parameters in code:
- 14.```python
- 15.import redis
- 16.# Instead of from_url, pass components separately
- 17.client = redis.Redis(
- 18.host="redis.example.com",
- 19.port=6379,
- 20.password="MyP@ss#w0rd&2024", # Raw password, no encoding needed
- 21.db=0
- 22.)
- 23.
` - 24.In Kubernetes secrets, store the raw password and construct the connection string in the application:
- 25.```yaml
- 26.apiVersion: v1
- 27.kind: Secret
- 28.metadata:
- 29.name: db-credentials
- 30.type: Opaque
- 31.data:
- 32.password: TXlQQHNzI3cwcmQmMjAyNA==
- 33.
`