This sample demonstrates how to build a Node.js application using Sequelize with Amazon Aurora DSQL.
- Sequelize models with UUID primary keys for Aurora DSQL's distributed architecture
- Database-enforced referential integrity using Aurora DSQL foreign key constraints (a capability that became generally available in August 2026), with UUID relationship columns and Sequelize associations for eager loading — modeling relationships at the application level with UUID columns remains a valid alternative
- IAM authentication via the Aurora DSQL Connector for node-postgres (
@aws/aurora-dsql-node-postgres-connector), which automatically generates and refreshes IAM tokens — no static passwords, for both admin and non-admin users - Individual DDL execution (Aurora DSQL does not support multiple DDL statements per transaction)
- Optimistic concurrency control (OCC) retry logic with exponential backoff and jitter
- Schema isolation for a least-privilege, non-admin application user
- Running this code might result in charges to your AWS account.
- We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see Grant least privilege.
- This code is not tested in every AWS Region. For more information, see AWS Regional Services.
- Node.js 20 or later (required by the Aurora DSQL connector)
- AWS CLI v2 configured with credentials
- An Aurora DSQL cluster (single-Region is sufficient)
- IAM permissions:
dsql:DbConnectAdminanddsql:DbConnecton your cluster
Install dependencies:
npm installSet the following environment variables:
export CLUSTER_ENDPOINT="your-cluster.dsql.your-region.on.aws"
export CLUSTER_USER="admin" # required — see below for recommended non-admin setup
# CLUSTER_REGION is optional — the connector auto-detects the Region from the endpointAdmin access is needed only for one-time schema and role creation. After setup, use the non-admin app user (recommended below).
# Test connectivity first
npm run test:connection
# Run the full demo. This creates the schema and tables if needed, then CLEARS
# any existing rows in these tables before seeding fresh demo data, so the run
# is repeatable. Point it at a database/schema that only holds this sample's data.
npm start
# After reviewing the data in your database, clean up
npm run cleanupWhen you run the demo, the application creates the schema, registers guests, sets up rooms, processes reservations end to end (create, check-in, check-out, payment), queries guest history and room availability, prints a revenue report, and demonstrates the OCC retry pattern with a retry-safe loyalty-tier update.
Unit tests are pure logic — they require no AWS credentials, no network, and no live cluster:
npm testIntegration tests exercise the full workflow against a live Aurora DSQL cluster (schema creation, foreign-key enforcement, eager loading, OCC retry, and cleanup). They are skipped automatically unless CLUSTER_ENDPOINT and CLUSTER_USER are set, so npm test stays green offline:
export CLUSTER_ENDPOINT="your-cluster.dsql.your-region.on.aws"
export CLUSTER_USER="admin" # or your non-admin app role (with CLUSTER_SCHEMA)
npm run test:integrationFor production workloads, use a least-privilege app user instead of admin. This is the recommended path after initial setup.
In Aurora DSQL, every non-admin database user maps 1:1 to an IAM identity — you link a database role to an IAM ARN with the AWS IAM GRANT command.
Note: This step requires an IAM user with permissions to create IAM policies and modify Aurora DSQL cluster access. If your current user lacks these permissions, ask your AWS account administrator.
Your IAM policy should include both actions:
{
"Sid": "DatabaseAccess",
"Effect": "Allow",
"Action": [
"dsql:DbConnectAdmin",
"dsql:DbConnect"
],
"Resource": "arn:aws:dsql:<region>:<account-id>:cluster/<cluster-id>"
}Edit src/setup_app_user.sql — replace <AWS_ACCOUNT_ID> and <IAM_USERNAME> with your values, then run:
# The AWS CLI token command below needs an explicit --region (unlike the app,
# which auto-detects the Region from CLUSTER_ENDPOINT). Set it to your cluster's
# Region for these one-time admin setup commands:
export CLUSTER_REGION="us-east-1" # replace with your cluster's Region
# Generate an admin auth token
TOKEN=$(aws dsql generate-db-connect-admin-auth-token \
--hostname $CLUSTER_ENDPOINT \
--region $CLUSTER_REGION \
--expires-in 3600)
# Run the SQL file to create the role, schema, and permissions
psql "host=$CLUSTER_ENDPOINT port=5432 dbname=postgres user=admin sslmode=require password=${TOKEN}" \
-f src/setup_app_user.sqlexport CLUSTER_USER="hotel_app"
export CLUSTER_SCHEMA="hotel"For example, if your AWS account ID is 111222333444 and your IAM user is jdoe, the AWS IAM GRANT line in setup_app_user.sql would read:
AWS IAM GRANT hotel_app TO 'arn:aws:iam::111222333444:user/jdoe';# Test connectivity with the app user
npm run test:connection
# Run the full demo (clears existing rows in these tables, then seeds demo data)
npm start
# After reviewing the data, clean up
npm run cleanupThe Aurora DSQL connector automatically selects the correct authentication token based on the username:
admin→ an admin authentication token (requires IAMdsql:DbConnectAdmin)- Any other user → a standard authentication token (requires IAM
dsql:DbConnect)
No sts:AssumeRole is required — the same IAM credentials that authenticate the AWS API call are linked to the database role via AWS IAM GRANT.
sequelize/
├── package.json # Project metadata, scripts, dependencies
├── package-lock.json # Pinned dependency versions
├── .gitignore
├── README.md
├── src/
│ ├── models.js # Sequelize model definitions (Guest, Room, Reservation, Payment)
│ ├── db.js # Aurora DSQL connection setup (connector integration), schema creation
│ ├── retry.js # OCC retry utility with exponential backoff and jitter
│ ├── app.js # Main hotel reservation demonstration application
│ ├── cleanup.js # Remove demo data (run separately after reviewing)
│ ├── test_connection.js # Quick connectivity verification
│ └── setup_app_user.sql # SQL commands to create a non-admin app user
└── test/
├── test_example.test.js # Unit tests — config, models, retry (no credentials required)
└── integration.test.js # Live end-to-end tests (skipped unless a cluster is configured)
- UUID primary keys:
DataTypes.UUIDwithDataTypes.UUIDV4— no coordination across the distributed system. - Foreign key constraints: Aurora DSQL added support for foreign key constraints (generally available August 2026), so this sample enforces referential integrity at the database level.
reservationreferencesguestandroom;paymentreferencesreservationandguest. Referenced tables are created before referencing tables. We use the defaultON DELETE NO ACTIONbehavior — following AWS guidance to preferNO ACTION/RESTRICToverCASCADEwhen child-row cardinality is unbounded (guests accumulate reservations and payments). Cascading actions run in a single transaction and count against the Aurora DSQL 3,000-row transaction limit, so they can fail unexpectedly at scale. Note also that FK checks add extra reads, and concurrent conflicts on referenced keys surface as retryable serialization errors (OC000/SQLSTATE 40001) rather than lock waits — so writes that can conflict should be wrapped in the OCC retry helper (seeretry.js, demonstrated here on the loyalty-tier update inapp.js). If you prefer, you can instead model relationships purely at the application level with UUID columns (settingconstraints: falseon the Sequelize associations); both approaches work well on Aurora DSQL. - Individual DDL execution: Each
CREATE TABLEruns as its own statement viasequelize.query(ddl, { raw: true }). Table names andREFERENCEStargets are schema-qualified (for example"hotel"."guest"), because each statement can run on a different pooled connection. - OCC retry: Catches
SQLSTATE 40001(error codesOC000/OC001) and retries with exponential backoff and jitter. Because Sequelize runs in autocommit mode by default, single-statement operations are safe to retry; do not wrap a retried operation in a baresequelize.transaction(). - Connector integration + connection compatibility: The Aurora DSQL connector plugs into Sequelize via
dialectModule: { ...pg, Client: AuroraDSQLClient }, so Sequelize usesnode-postgresbut with the connector's IAM-authenticating client (it also auto-detects the AWS Region from the cluster endpoint). The connection also setsclientMinMessages: 'ignore',standardConformingStrings: false, andkeepDefaultTimezone: trueto avoid unsupported sessionSETcommands. Note that the connector's own built-in OCC retry only applies to work run through itstransaction()method; when the connector is used via Sequelize'sdialectModule, queries go through Sequelize's own.query()/model methods and never calltransaction(), so that built-in retry is not engaged — which is why this sample provides its own query-level OCC retry inretry.js.
A few Aurora DSQL specifics shaped how this script is written:
- Idempotent role creation.
setup_app_user.sqluses a plainCREATE ROLE(re-running errors harmlessly with "role already exists"; the remaining statements are idempotent), rather than wrapping it in aplpgsqlDO $$ ... $$block. - Schema owned by admin. The schema is created owned by admin, and the app role is granted
USAGE, CREATEplus CRUD, rather than usingCREATE SCHEMA ... AUTHORIZATION <iam-role>. ALTER DEFAULT PRIVILEGESis required so the app role can access tables the application creates at runtime —GRANT ... ON ALL TABLESonly covers tables that exist at grant time.- Schema-qualify your models for a non-admin user. A non-admin role's default
search_path("$user", public) resolves unqualified table names to thepublicschema. If a same-named table exists inpublic(owned by another role), unqualified queries hit it and fail withpermission denied. This sample setsschema: SCHEMAon every model so all queries are schema-qualified (for example"hotel"."payment") regardless ofsearch_path.
After creating the schema, you can confirm the foreign keys landed and are enforced. Connect as admin and run:
-- List each foreign key, its parent, and referential actions.
-- No schema filter, so this works whether the tables are in "public" (admin path)
-- or "hotel" (recommended non-admin path); the schema is shown in the output.
SELECT tc.table_schema AS schema,
tc.table_name AS child_table,
kcu.column_name AS fk_column,
ccu.table_name AS parent_table,
ccu.column_name AS parent_column,
rc.delete_rule AS on_delete,
rc.update_rule AS on_update
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage ccu
ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema
JOIN information_schema.referential_constraints rc
ON tc.constraint_name = rc.constraint_name AND tc.table_schema = rc.constraint_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
ORDER BY schema, child_table, fk_column;Expect four foreign keys (reservation → guest/room, payment → reservation/guest), each with on_delete/on_update = NO ACTION, listed under whichever schema holds the tables (public for the admin path, hotel for the recommended non-admin path). You can also confirm each constraint is validated and enforcing with SELECT conname, convalidated, confdeltype FROM pg_constraint WHERE contype = 'f'; (convalidated = t, confdeltype = a).
- No static passwords — IAM tokens are generated and refreshed at runtime by the Aurora DSQL connector (
@aws/aurora-dsql-node-postgres-connector) - TLS is required for all connections to Aurora DSQL; the connector negotiates TLS automatically
- Tokens are short-lived; the connector generates a fresh token for each new connection
- Use a least-privilege non-admin app user for runtime; reserve admin for schema setup and migrations
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0