cannot execute in a read-only transaction
This error occurs when you try to write data while connected to a read replica or in a read-only transaction.
The cannot execute in a read-only transaction error means you can't write in the current context.
Understanding the Error
ERROR: cannot execute INSERT in a read-only transaction
You're trying to INSERT, UPDATE, DELETE, or DDL in a read-only context.
Common Causes
1. Connected to Read Replica
# Connection string points to replica
postgresql://user:pass@replica-host:5432/mydb
2. Read-Only Transaction Mode
SQL
3. default_transaction_read_only Setting
SQL
4. Hot Standby Server
Connected to a streaming replica that's in recovery mode.
How to Fix It
Solution 1: Connect to Primary Server
JAVASCRIPT
Solution 2: Use Read-Write Transaction
SQL
Solution 3: Check/Change Session Setting
SQL
Solution 4: Check Server Mode
SQL
Solution 5: Configure Connection Pool
JAVASCRIPT
Solution 6: Handle in Application
JAVASCRIPT
Best Practices
- Separate read/write connections in your application
- Document which server to use for each operation
- Use connection pooling with proper routing
- Handle failover gracefully when replica promoted
- Monitor replication lag to avoid stale reads