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. 1.Update PostgreSQL connection string with encoded password:
  2. 2.`
  3. 3.postgresql://app_user:MyP%40ss%23w0rd%262024@db.example.com:5432/production
  4. 4.`
  5. 5.For MySQL, use the same encoding in the DSN:
  6. 6.`
  7. 7.mysql://app_user:MyP%40ss%23w0rd%262024@db.example.com:3306/production?sslmode=required
  8. 8.`
  9. 9.For MongoDB connection strings, encode the full URI:
  10. 10.`
  11. 11.mongodb+srv://app_user:MyP%40ss%23w0rd%262024@cluster0.example.com/production?retryWrites=true
  12. 12.`
  13. 13.For Redis, either encode or use separate parameters in code:
  14. 14.```python
  15. 15.import redis
  16. 16.# Instead of from_url, pass components separately
  17. 17.client = redis.Redis(
  18. 18.host="redis.example.com",
  19. 19.port=6379,
  20. 20.password="MyP@ss#w0rd&2024", # Raw password, no encoding needed
  21. 21.db=0
  22. 22.)
  23. 23.`
  24. 24.In Kubernetes secrets, store the raw password and construct the connection string in the application:
  25. 25.```yaml
  26. 26.apiVersion: v1
  27. 27.kind: Secret
  28. 28.metadata:
  29. 29.name: db-credentials
  30. 30.type: Opaque
  31. 31.data:
  32. 32.password: TXlQQHNzI3cwcmQmMjAyNA==
  33. 33.`

Prevention - Enforce password policies that exclude URL-special characters (`@`, `#`, `&`, `/`, `?`, `=`, `%`) - Use connection pooling libraries (PgBouncer, ProxySQL) that accept password as a separate parameter - Store connection strings in environment variables with a build step that URL-encodes passwords - Test connection strings in CI/CD pipelines before deploying to production - Use AWS Secrets Manager or HashiCorp Vault to inject credentials at runtime without manual string construction