Skip to content

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 Default 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
  }
}

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.
MetadataQuerySchemastringnullSchema name for metadata queries.

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 X-Execution-Id request header, or null if not provided

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"]
    }
  }
}

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 Default 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

Released under the MIT License.