Aurora DSQL SQLx Connector for Rust
Overview
A Rust connector for Amazon Aurora DSQL that wraps SQLx with automatic IAM authentication. The connector handles token generation, SSL configuration, and connection management so you can focus on your application logic.
Features
- Automatic IAM token generation
- Connection pooling with background token refresh (opt-in
poolfeature) - Single connection support for simpler use cases
- Connection string parsing support
- OCC retry helpers with exponential backoff and jitter
Prerequisites
- Rust 1.94 or later
- AWS credentials configured (see Credentials Resolution below)
- An Aurora DSQL cluster
For information about creating an Aurora DSQL cluster, see the Getting started with Aurora DSQL guide.
Credentials Resolution
By default, the connector uses the AWS SDK for Rust default credential chain, which resolves credentials in the following order:
- Environment variables (
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY, and optionallyAWS_SESSION_TOKEN) - Shared credentials file (
~/.aws/credentials) with optional profile viaAWS_PROFILEorprofileconfig option - Shared config file (
~/.aws/config) - IAM role for Amazon EC2/ECS/Lambda (instance metadata or task role)
The first source that provides valid credentials is used. You can override this by:
- Specifying
profilein the connection string for a specific AWS profile - Passing a custom
SharedCredentialsProvidervia the builder for programmatic credential control (e.g., assumed IAM roles in Lambda)
Installation
Add to your Cargo.toml:
[]
= "0.2.1"
Feature Flags
| Feature | Default | Description |
|---|---|---|
occ |
No | OCC retry helpers (retry_on_occ, is_occ_error, OCCType, OCCRetryExt trait for PgConnection) |
pool |
No | sqlx pool helper with background token refresh |
Note: To use OCCRetryExt on PgPool, enable both occ and pool features.
For most applications, enable both features:
[]
= { = "0.2.1", = ["pool", "occ"] }
Configuration Options
These options are parsed from the connection string or set via the builder:
| Field | Type | Default | Description |
|---|---|---|---|
host |
string |
(required) | Cluster endpoint or cluster ID |
region |
Option |
(auto-detected) | AWS region; required if host is a cluster ID |
user |
string |
"admin" |
Database user |
database |
string |
"postgres" |
Database name |
port |
u16 |
5432 |
Database port |
profile |
Option<String> |
None |
AWS profile name for credentials |
credentials_provider |
Option<SharedCredentialsProvider> |
None |
Custom credentials provider (builder only) |
tokenDurationSecs |
u64 |
900 (15 minutes) |
Token validity duration in seconds |
ormPrefix |
Option<String> |
None |
ORM prefix for application_name (e.g. "diesel" → "diesel:aurora-dsql-rust-sqlx/{version}") |
Quick Start
Enable the pool feature, then:
use Row;
async
Connection String Format
The connector supports PostgreSQL connection string format:
postgres://[user@]host[:port]/[database][?param=value&...]
Both postgres:// and postgresql:// schemes are supported.
Supported query parameters:
region— AWS regionprofile— AWS profile nametokenDurationSecs— Token validity duration in secondsormPrefix— ORM prefix for application_name
Region Resolution Priority:
- Parse from hostname (e.g.,
cluster.dsql.us-east-1.on.aws) - Explicit
?region=...in connection string - AWS SDK default region (
AWS_REGIONenv var or~/.aws/config)
Examples:
# Full endpoint (region auto-detected from hostname)
# With explicit region
postgres://admin@cluster.dsql.us-east-1.on.aws/postgres?region=us-east-1
# With AWS profile
postgres://admin@cluster.dsql.us-east-1.on.aws/postgres?profile=dev
# Cluster ID (region required)
postgres://admin@foo0bar1baz2quux3quuux4/postgres?region=us-east-1
Advanced Usage
Host Configuration
The connector supports two host formats:
Full endpoint (region auto-detected):
let opts = from_connection_string?;
Cluster ID (region required):
let opts = from_connection_string?;
Single Connection Usage
For simple scripts or when connection pooling is not needed:
use Row;
async
Each call to connection::connect() generates a fresh IAM token. For operations longer than the token duration, create a new connection.
Pool Configuration
The pool feature provides pool::connect() helpers that return a standard sqlx::PgPool with a background token refresh task that rotates the IAM auth token at 80% of the token duration. This feature requires a tokio runtime. Call pool.close().await to stop the background refresh task and release pool resources.
For custom pool settings, pass PgPoolOptions to connect_with() to get both pool tuning and the background token refresh task:
use DsqlConnectOptions;
use PgPoolOptions;
let config = from_connection_string?;
let pool = connect_with.await?;
Or use connect() for defaults:
let pool = connect.await?;
Programmatic Configuration
Use DsqlConnectOptionsBuilder for programmatic configuration:
use ;
use PgConnectOptions;
let pg = new
.host
.username
.database;
let opts = default
.pg_connect_options
.region
.build?;
let mut conn = connect_with.await?;
Custom Credentials Provider
For environments where the default credential chain doesn't apply (e.g., Lambda with assumed roles), pass a custom SharedCredentialsProvider:
use ;
use Credentials;
use ;
let creds = new;
let config = default
.pg_connect_options
.credentials_provider
.build?;
let pool = connect_with.await?;
Token Generation
The connector automatically generates IAM authentication tokens:
- Connection pools: A background task refreshes the token at 80% of the token duration via
pool.set_connect_options(). Callpool.close().awaitto stop the refresh task. - Single connections: A fresh token is generated at connection time.
- Token generation is a local SigV4 presigning operation with negligible cost.
For the admin user, the connector generates admin tokens using db_connect_admin_auth_token. For other users, it generates standard tokens using db_connect_auth_token.
Token duration defaults to 900 seconds. This can be customized via tokenDurationSecs in the connection string.
OCC Retry
Aurora DSQL uses optimistic concurrency control (OCC). Transactions may fail with OCC errors when concurrent modifications conflict. The connector provides helpers to automatically detect and retry these operations (enable the occ feature).
Using the Extension Trait (Recommended)
Import OCCRetryExt to add retry methods to PgPool or PgConnection:
use OCCRetryExt;
// With connection pool
let mut pool = connect.await?;
pool.transaction_with_retry.await?;
// With single connection
let mut conn = connect.await?;
conn.transaction_with_retry.await?;
// With custom config
use OCCRetryConfigBuilder;
let config = default
.max_attempts
.base_delay_ms
.max_delay_ms
.build?;
pool.transaction_with_retry.await?;
Simplifying with txn! macro: Hide Box::pin boilerplate:
use ;
pool.transaction_with_retry.await?;
Opting Out: For operations that don't need retry, use sqlx directly:
// Direct pool usage - no OCC retry
let mut tx = pool.begin.await?;
query.execute.await?;
tx.commit.await?;
Manual Retry (Advanced)
For custom retry logic or operations that need explicit transaction control:
use retry_on_occ;
let config = default;
retry_on_occ.await?;
Configuration
Customize retry behavior with OCCRetryConfigBuilder:
use OCCRetryConfigBuilder;
let config = default
.max_attempts // Default: 3
.base_delay_ms // Default: 1ms
.max_delay_ms // Default: 100ms
.jitter_factor // Default: 0.25 (25%)
.build?;
Backoff Strategy:
- Exponential:
delay = base_delay * 2^(attempt-1) - Additive jitter:
jitter = delay * random(0..1) * jitter_factor - Capped at
max_delay_ms
Retry Logging
The connector uses the log crate for retry logging. If your application uses any log implementation (e.g., env_logger, tracing-subscriber), the connector's logs will be captured automatically.
OCC Error Types
The connector classifies OCC errors by type for better observability:
| SQLSTATE | OCCType | Description |
|---|---|---|
OC000 |
Data |
Data conflict - concurrent modification of same rows |
OC001 |
Schema |
Schema conflict - DDL changes during transaction |
40001 |
Unknown |
Generic serialization failure (parsed for embedded OC000/OC001) |
Use is_occ_error() to detect and classify errors, or check logs for conflict types. Error codes are included in all retry log messages for better observability.
Examples
The example/ directory contains runnable examples with a standalone Cargo project:
| Example | Description |
|---|---|
| example_preferred | Recommended: Pool with concurrent queries and transactional writes |
| example_no_connection_pool | Single connection without pooling |
Running Examples
# Run the preferred example (pool-based)
# Run the no-pool example
Additional Resources
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0