Skip to main content
This guide covers common database-related issues that may arise when working with the Definable backend.

Connection Issues

Symptoms:
  • Error: Could not connect to server: Connection refused
  • Error: OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed
Solutions:
  1. Verify PostgreSQL is running:
  2. Check connection parameters:
    • Verify hostname, port, username, password, and database name
    • Make sure database exists: psql -U postgres -c "SELECT datname FROM pg_database;"
  3. Test connection with psql:
  4. Check PostgreSQL logs:
Symptoms:
  • Error: asyncpg.exceptions.PostgresConnectionError: connection to server was closed
  • Error: asyncpg.exceptions.InvalidAuthorizationSpecificationError: password authentication failed
Solutions:
  1. Check your connection string format:
  2. URL encode special characters in password:
  3. Check PostgreSQL authentication settings (pg_hba.conf):
    • Ensure it allows password authentication (md5 or scram-sha-256)
    • For development, temporarily set local connections to โ€˜trustโ€™
  4. Test with a minimal example:
Symptoms:
  • Error: ssl_error_want_read or ssl_error_want_write
  • Error: SSL SYSCALL error: EOF detected
Solutions:
  1. Disable SSL for local development (if needed):
  2. For production, configure SSL properly:
  3. For Supabase with SSL issues:
    • Use the connection pooler URL instead of direct connection
    • Go to Supabase dashboard > Project Settings > Database > Connection Pooling

Migration Issues

Symptoms:
  • Error: FAILED: Multiple head revisions are present
  • Error: Can't locate revision identified by '...'
Solutions:
  1. For multiple heads:
  2. For missing revisions:
  3. Check alembic configuration:
    • Verify alembic.ini has correct database URL
    • Check env.py imports your SQLAlchemy models correctly
Symptoms:
  • Error: Error: Target database is not up to date.
  • Error: Can't locate revision identified by '...'
Solutions:
  1. Synchronize with the team:
  2. For development, reset migration state:
  3. Fix revision chain manually:
    • Edit the down_revision in migration files to fix the chain
    • Use alembic history to understand the current chain
Symptoms:
  • alembic revision --autogenerate doesnโ€™t detect model changes
  • Generated migration has unexpected changes
Solutions:
  1. Ensure models are imported in env.py:
  2. Check model metadata:
  3. Run with verbose output:
  4. Check for unsupported model features:
    • Some SQLAlchemy constructs arenโ€™t detected by Alembic
    • Add manual migrations for: Constraints, Indexes, some Column types
Symptoms:
  • Error like: ProgrammingError: column X does not exist
  • Error when executing migrationโ€™s upgrade() function
Solutions:
  1. Edit the migration file:
    • Fix the SQL or Alembic operations causing errors
  2. For data corruption, clean approach (development only):
  3. For schema issues where tables already exist:

SQLAlchemy Issues

Symptoms:
  • Error: TimeoutError: Connection attempt timed out
  • Application hangs when connecting to database
Solutions:
  1. Configure connection pooling correctly:
  2. Implement retry logic for transient failures:
  3. Check for database resource limitations:
    • Maximum connections (max_connections in postgresql.conf)
    • Check current connections: SELECT count(*) FROM pg_stat_activity;
Symptoms:
  • Error: AssertionError: A sync operation occurred within an async transaction.
  • Error: InterfaceError: connection is closed
Solutions:
  1. Ensure youโ€™re using async operations throughout:
  2. Check for instances of sync operations:
    • Replace .all() with await session.execute(query).all()
    • Replace .first() with await session.execute(query).first()
    • Use await session.commit() instead of session.commit()
  3. Fix connection closing issues:
Symptoms:
  • Unexpected query results
  • Error: AttributeError: 'Query' object has no attribute 'xxx'
Solutions:
  1. Debug queries by logging SQL:
  2. Review SQLAlchemy 2.0-style execution:
  3. Check for ORM vs. Core confusion:
    • Result objects differ between ORM queries and Core queries
    • For ORM: Use .scalars() to get model instances
    • For Core: Use .mappings() to get dictionaries

PostgreSQL Issues

Symptoms:
  • Error: permission denied for schema public
  • Error: permission denied for relation your_table
Solutions:
  1. Grant permissions to your database user:
  2. Check current user and permissions:
  3. For hosted databases with restricted permissions:
    • Use the admin/owner account instead of a restricted role
    • Contact your database provider for assistance
Symptoms:
  • Poor search results
  • Performance issues with text search
Solutions:
  1. Create proper indexes:
  2. Optimize your search queries:
  3. Consider using a vector database for semantic search:
    • Use pgvector for embedding-based search
    • Create appropriate indexes for vector columns

Performance Issues

Symptoms:
  • Database operations taking too long
  • API response times deteriorating
Solutions:
  1. Identify slow queries:
  2. Use EXPLAIN ANALYZE to understand query plans:
  3. Add appropriate indexes:
  4. Optimize your queries:
    • Use LIMIT to restrict result size
    • Only select needed columns
    • Avoid multiple joins when possible
    • Consider pagination for large result sets
Symptoms:
  • Error: FATAL: too many connections
  • Applications waiting for database connections
Solutions:
  1. Configure connection pooling properly:
  2. Check current connections and limits:
  3. For production, consider external connection poolers:
    • PgBouncer
    • AWS RDS Proxy
    • Supabase Connection Pooler
Symptoms:
  • Out of memory errors
  • Slow API responses when retrieving many records
Solutions:
  1. Implement pagination:
  2. Use cursor-based pagination for large datasets:
  3. Stream results for large exports:

Data Integrity Issues

Symptoms:
  • Error: invalid input syntax for type uuid
  • Missing UUID values in records
Solutions:
  1. Ensure UUIDs are used consistently:
  2. For migrations involving UUID columns:
  3. Check database and python type consistency:
Symptoms:
  • Error: violates foreign key constraint
  • Error: insert or update on table violates foreign key constraint
Solutions:
  1. Check referential integrity:
  2. Fix application logic:
    • Ensure parent records exist before creating child records
    • Implement proper cascading deletes in models
  3. For migration or data fixing:
Symptoms:
  • Error: duplicate key value violates unique constraint
  • Insert or update operations failing
Solutions:
  1. Check existing data:
  2. Implement upsert logic:
  3. For batch operations, find and filter duplicates before insert:

Advanced Issues

Symptoms:
  • Error: Unexpected JSON type
  • Problems querying or updating JSON fields
Solutions:
  1. Use appropriate column type:
  2. Query JSON data efficiently:
  3. Update JSON fields:
Symptoms:
  • Deadlocks
  • Error: current transaction is aborted, commands ignored until end of transaction block
Solutions:
  1. Use proper transaction patterns:
  2. Handle nested transactions:
  3. For deadlocks, implement retry logic:
Symptoms:
  • Slow vector similarity searches
  • High CPU usage during vector operations
Solutions:
  1. Create appropriate indexes:
  2. Tune search parameters:
  3. Optimize embedding dimension and storage:
    • Use the smallest embedding size that maintains accuracy
    • Consider dimensionality reduction techniques
    • For very large collections, implement clustering or partitioning

Supabase Connection Issues

Symptoms:
  • Error: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "db.abcdefghijkl.supabase.co" and accepting TCP/IP connections on port 5432?
  • Connection works from one network but not another
  • Intermittent connection issues
Solutions:
  1. Force IPv4 connections:
  2. Disable IPv6 on your local machine (temporary test):
  3. Use Supabase connection pooler instead of direct connection:
    • Go to Supabase Dashboard > Project Settings > Database > Connection Pooling
    • Use the provided connection string which may bypass IP version issues
  4. Test connection using domain instead of IP address:
Symptoms:
  • Connections time out after exactly 30-60 seconds
  • Error: OperationalError: could not connect to server: Connection refused
  • Error: ssl_error_syscall with Supabase connection
Solutions:
  1. Check if your network allows outbound connections to port 5432:
  2. Check if your IP is allowlisted in Supabase:
    • Go to Supabase Dashboard > Project Settings > Database > Network Restrictions
    • Add your current IP address to the allowed list
    • If using dynamic IPs, you may need to keep this updated
  3. Use Supabaseโ€™s HTTPS connection pooler for restrictive networks:
  4. VPN or proxy solutions:
    • If your network has strict firewall rules, consider using a VPN
    • Configure a proxy that allows PostgreSQL connections
Symptoms:
  • Error: remaining connection slots are reserved for non-replication superuser connections
  • Connections work initially but fail under load
  • Error: sorry, too many clients already when multiple services connect
Solutions:
  1. Configure proper connection pooling in application:
  2. Use Supabaseโ€™s connection pooler:
  3. Implement aggressive connection clean-up:
  4. Monitor and adjust connection limits in dashboard:
    • Go to Supabase Dashboard > Project Settings > Database > Connection Pooling
    • Adjust pool mode and connection limits based on your tier
    • For Free and Pro tiers, be especially careful with connection counts
Symptoms:
  • High latency on database operations
  • Intermittent timeouts despite successful connections
  • Connection issues during specific times of day
Solutions:
  1. Select appropriate Supabase region:
    • When creating a new project, choose the region closest to your users/servers
    • For existing projects, consider migrating to a closer region if latency is critical
  2. Configure longer timeouts for high-latency connections:
  3. Implement connection caching for read-heavy workloads:
  4. Consider Supabase Edge Functions for latency-sensitive operations:
    • Deploy Edge Functions closer to the database
    • Reduce round-trip time for critical operations
Symptoms:
  • Error: SSL SYSCALL error: EOF detected
  • Error: ssl_error_want_read or ssl_error_want_write
  • Error: SSL error: certificate verify failed
Solutions:
  1. Configure SSL properly:
  2. For development/testing, disable strict certificate verification (not recommended for production):
  3. Update CA certificates:
  4. Use Supabase connection string with SSL parameters:
Symptoms:
  • Hitting connection limits unexpectedly
  • Database operations becoming slower at certain times
  • Error: sorry, too many clients already despite proper connection pooling
Solutions:
  1. Be aware of tier limitations:
    • Free tier: Limited connections, compute, and may pause after inactivity
    • Pro tier: Higher limits but still restricted compared to enterprise
    • Check current tier limits at Supabase dashboard
  2. Implement application-level connection management:
  3. Add monitoring to track connection usage:
  4. Consider upgrading tier or optimizing application:
    • For production workloads, higher tiers provide better guarantees
    • Implement aggressive connection pooling
    • Add read replicas for read-heavy workloads if available in your tier

Next Steps

If youโ€™ve resolved your database issues, consider reviewing these related guides: If youโ€™re still experiencing database problems, check PostgreSQL and SQLAlchemy official documentation or contact the development team for assistance.