Skip to content
Written with Claude
IMPORTANT

As you may notice, this page and pretty much the entire website were obviously created with the help of AI. I wonder how you could tell? Was it a big "Written With Claude" badge on every page? I moved it to the top now (with the help of AI of course) to make it even more obvious. There are a few blogposts that were written by me manually, the old-fashioned way, I hope there will be more in the future, and those have a similar "Human Written" badge. This project (not the website), on the other hand, is a very, very different story. It took me more than two years of painstaking and unpaid work in my own free time. A story that, hopefully, I will tell someday. But meanwhile, what would you like me to do? To create a complex documentation website with a bunch of highly technical articles with the help of AI and fake it, to give you an illusion that I also did that manually? Like the half of itnernet is doing at this point? How does that makes any sense? Is that even fair to you? Or maybe to create this website manually, the old-fashioned way, just for you? While working a paid job for a salary, most of you wouldn't even get up in the morning. Would you like me to sing you a song while we're at it? For your personal entertainment? Seriously, get a grip. Do you find this information less valuable because of the way this website was created? I give my best to fix it to keep the information as accurate as possible, and I think it is very accurate at this point. If you find some mistakes, inaccurancies or problems, there is a comment section at the bottom of every page, which I also made with the help of the AI. And I woould very much appreciate if you leave your feedback there. Look, I'm just a guy who likes SQL, that's all. If you don't approve of how this website was constructed and the use of AI tools, I suggest closing this page and never wever coming back. And good riddance. And I would ban your access if I could know how. Thank you for your attention to this matter.

Connection Settings

This page covers all database connection configuration in NpgsqlRest, including connection strings, connection behavior settings, and NpgsqlRest-specific connection options.

Connection Strings

The ConnectionStrings section defines named database connections. The first available connection is used automatically when no specific connection is specified.

json
{
  "ConnectionStrings": {
    "Default": "Host=localhost;Port=5432;Database=mydb;Username=myuser;Password=mypassword"
  }
}

Multiple Connections

You can define multiple named connections for different purposes (e.g., read replicas, different databases):

json
{
  "ConnectionStrings": {
    "Default": "Host=primary.example.com;Database=mydb;Username=app;Password=secret",
    "ReadReplica": "Host=replica.example.com;Database=mydb;Username=app;Password=secret",
    "Analytics": "Host=analytics.example.com;Database=analytics;Username=report;Password=secret"
  }
}

Using Environment Variables

Connection strings support environment variable placeholders when ParseEnvironmentVariables is enabled (default):

json
{
  "ConnectionStrings": {
    "Default": "Host={PGHOST};Port={PGPORT};Database={PGDATABASE};Username={PGUSER};Password={PGPASSWORD}"
  }
}

This is the recommended approach for production deployments to keep credentials out of configuration files.

Connection String Parameters

Common PostgreSQL connection string parameters:

ParameterDescriptionExample
HostServer hostname or IPlocalhost, db.example.com
PortServer port5432
DatabaseDatabase namemydb
UsernameLogin usernamemyuser
PasswordLogin passwordmypassword
SSL ModeSSL connection modeRequire, Prefer, Disable
PoolingEnable connection poolingtrue, false
Minimum Pool SizeMinimum connections in pool0
Maximum Pool SizeMaximum connections in pool100
Connection Idle LifetimeSeconds before idle connection is closed300
Connection LifetimeMaximum connection lifetime in seconds0 (unlimited)
TimeoutConnection timeout in seconds15

For a complete list, see the Npgsql Connection String Parameters.

Connection Settings

The ConnectionSettings section controls connection behavior, testing, and retry logic.

json
{
  "ConnectionSettings": {
    "SetApplicationNameInConnection": true,
    "UseJsonApplicationName": false,
    "TestConnectionStrings": true,
    "RetryOptions": {
      "Enabled": true,
      "RetrySequenceSeconds": [1, 3, 6, 12],
      "ErrorCodes": ["08000", "08003", "08006", "08001", "08004", "55P03", "55006", "53300", "57P03", "40001"]
    },
    "MetadataQueryConnectionName": null,
    "MetadataQuerySchema": null,
    "MultiHostConnectionTargets": {
      "Default": "Any",
      "ByConnectionName": {}
    }
  }
}

Settings Reference

SettingTypeDefaultDescription
SetApplicationNameInConnectionbooltrueSets the ApplicationName connection property to the configured application name.
UseJsonApplicationNameboolfalseDynamically sets a JSON-formatted application name per request (see below). Note: Limited to 64 characters.
TestConnectionStringsbooltrueValidates each connection by opening and closing it during startup.
MetadataQueryConnectionNamestringnullConnection name used for metadata queries. Uses default connection if null.
MetadataQuerySchemastringnullSet the search path to this schema before executing the metadata query function. When null (default), no search path is set and the server's default search path is used. Useful when using non-superuser roles with limited schema access.
MultiHostConnectionTargetsobject(see below)Configuration for multi-host connection failover and load balancing.

Application Name in Connection

When SetApplicationNameInConnection is true, the configured ApplicationName is included in the database connection. This helps identify connections in PostgreSQL monitoring tools like pg_stat_activity.

JSON Application Name

When UseJsonApplicationName is true, the ApplicationName connection property is set dynamically on every request in the following JSON format:

json
{"app": "MyApi", "uid": "user123", "id": "abc-123"}
FieldDescription
appApplication name from configuration
uidUser ID for authenticated users, or null for anonymous requests
idValue of the execution request header, or null if not provided

The execution request header name can be configured in the NpgsqlRest section underExecutionIdHeaderName (default is X-NpgsqlRest-ID). See NpgsqlRest Request Headers for details.

This provides detailed per-request tracking in PostgreSQL's pg_stat_activity.

WARNING

The ApplicationName connection property is limited to 64 characters. Longer values will be truncated.

Connection Testing

When TestConnectionStrings is true (default), NpgsqlRest validates all configured connections at startup by opening and closing each one. This ensures:

  • Connection strings are valid
  • Database servers are reachable
  • Credentials are correct

If any connection fails, the application will not start.

Retry Options

The RetryOptions section configures automatic retry behavior for transient connection failures.

json
{
  "ConnectionSettings": {
    "RetryOptions": {
      "Enabled": true,
      "RetrySequenceSeconds": [1, 3, 6, 12],
      "ErrorCodes": ["08000", "08003", "08006", "08001", "08004", "55P03", "55006", "53300", "57P03", "40001"]
    }
  }
}

Retry Settings Reference

SettingTypeDefaultDescription
EnabledbooltrueEnable automatic retry for connection failures.
RetrySequenceSecondsnumber[][1, 3, 6, 12]Wait intervals (in seconds) between retry attempts. Supports decimals like 0.25.
ErrorCodesstring[](see below)PostgreSQL error codes that trigger automatic retries.

Default Error Codes

The default error codes cover common transient failures:

CodeClassDescription
08000Connection ExceptionGeneral connection error
08001SQL Client Unable to Establish ConnectionClient cannot connect
08003Connection Does Not ExistConnection lost
08004SQL Server Rejected ConnectionServer rejected connection
08006Connection FailureConnection failed
55006Object In UseDatabase object is in use
55P03Lock Not AvailableCannot acquire lock
53300Too Many ConnectionsConnection limit reached
57P03Cannot Connect NowServer starting up
40001Serialization FailureTransaction serialization conflict

Custom Retry Configuration

For high-availability scenarios, you might want more aggressive retries:

json
{
  "ConnectionSettings": {
    "RetryOptions": {
      "Enabled": true,
      "RetrySequenceSeconds": [0.5, 1, 2, 4, 8, 16, 32],
      "ErrorCodes": ["08000", "08003", "08006", "57P03"]
    }
  }
}

Multi-Host Connection Support

NpgsqlRest supports PostgreSQL multi-host connections with failover and load balancing capabilities using Npgsql's NpgsqlMultiHostDataSource.

Multi-Host Connection Strings

Connection strings with comma-separated hosts are automatically detected as multi-host connections:

json
{
  "ConnectionStrings": {
    "Default": "Host=primary.db.com,replica1.db.com,replica2.db.com;Database=mydb;Username=app;Password=secret"
  }
}

Target Session Attributes

Configure which server type to target for each connection:

json
{
  "ConnectionSettings": {
    "MultiHostConnectionTargets": {
      "Default": "Any",
      "ByConnectionName": {
        "readonly": "Standby",
        "primary": "Primary"
      }
    }
  }
}
ValueDescription
AnyAny successful connection is acceptable (default)
PrimaryServer must not be in hot standby mode
StandbyServer must be in hot standby mode
PreferPrimaryTry primary first, fall back to any
PreferStandbyTry standby first, fall back to any
ReadWriteSession must accept read-write transactions
ReadOnlySession must not accept read-write transactions

See Npgsql Failover and Load Balancing for more details.

Multi-Host Example

Complete configuration for a primary-replica setup:

json
{
  "ConnectionStrings": {
    "Default": "Host=primary.db.com,replica1.db.com,replica2.db.com;Database=mydb;Username=app;Password=secret",
    "ReadOnly": "Host=replica1.db.com,replica2.db.com,primary.db.com;Database=mydb;Username=app;Password=secret"
  },
  "ConnectionSettings": {
    "MultiHostConnectionTargets": {
      "Default": "PreferPrimary",
      "ByConnectionName": {
        "ReadOnly": "PreferStandby"
      }
    }
  }
}

NpgsqlRest Connection Options

The NpgsqlRest section contains additional connection-related settings that control how routines interact with database connections.

json
{
  "NpgsqlRest": {
    "ConnectionName": null,
    "UseMultipleConnections": false
  }
}

NpgsqlRest Connection Settings Reference

SettingTypeDefaultDescription
ConnectionNamestringnullConnection name from ConnectionStrings to use. Uses first available if null.
UseMultipleConnectionsboolfalseAllow individual routines to specify alternative connections.

Using Multiple Connections

When UseMultipleConnections is true, individual PostgreSQL routines can specify which connection to use via comments. This is useful for:

  • Read replicas: Route read-only queries to replicas
  • Sharding: Route queries to different database shards
  • Resource isolation: Separate heavy analytics queries from transactional workloads

Example PostgreSQL function using a specific connection:

sql
create function get_report_data()
returns table(...)
language sql
as $$
  select * from large_table;
$$;

comment on function get_report_data() is '
HTTP GET /reports/data
@connection ReadReplica
';

Complete Example

Here's a complete connection configuration for a production environment:

json
{
  "ConnectionStrings": {
    "Default": "Host={PGHOST};Port={PGPORT};Database={PGDATABASE};Username={PGUSER};Password={PGPASSWORD};SSL Mode=Require;Pooling=true;Maximum Pool Size=100",
    "ReadReplica": "Host={PGHOST_REPLICA};Port={PGPORT};Database={PGDATABASE};Username={PGUSER};Password={PGPASSWORD};SSL Mode=Require;Pooling=true;Maximum Pool Size=50"
  },
  "ConnectionSettings": {
    "SetApplicationNameInConnection": true,
    "UseJsonApplicationName": false,
    "TestConnectionStrings": true,
    "RetryOptions": {
      "Enabled": true,
      "RetrySequenceSeconds": [0.5, 1, 2, 5, 10],
      "ErrorCodes": ["08000", "08003", "08006", "08001", "08004", "55P03", "55006", "53300", "57P03", "40001"]
    }
  },
  "NpgsqlRest": {
    "ConnectionName": null,
    "UseMultipleConnections": true
  }
}

Next Steps

Comments

Released under the MIT License.