Skip to content

New serverless pattern: apigw-lambda-dsql #2749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions apigw-lambda-dsql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Amazon API Gateway, AWS Lambda and Amazon Aurora DSQL

Amazon Aurora DSQL is the fastest serverless, distributed SQL database with active-active high availability and multi-Region strong consistency. Aurora DSQL enables you to build always available applications with virtually unlimited scalability, the highest availability, and zero infrastructure management. It is designed to make scaling and resilience effortless for your applications and offers the fastest distributed SQL reads and writes.

This pattern deploys a API Gateway REST API, Lambda function and an Aurora DSQL PostgreSQL cluster.

Learn more about this pattern at [Serverless Land Patterns](https://serverlessland.com/patterns/apigw-lambda-dsql)

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
1. Change directory to the pattern directory:
```
cd apigw-lambda-dsql
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam build
sam deploy --guided
```
1. During the prompts:
* Enter a stack name
* Enter the desired AWS Region (verify which [regions Aurora DSQL is available in](https://aws.amazon.com/rds/aurora/dsql/faqs/))
* Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.

1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

## How it works

This sample project demonstrates how to use a Lambda function (invoked by API Gateway), that stores and retrieves data from an Amazon Aurora DSQL PostgreSQL cluster.

## Testing

Use the `Value` from `UsersApi` URL output from the above `sam deploy` command to invoke the API Gateway API, e.g:
`curl https://abc123.execute-api.eu-west-1.amazonaws.com/Prod/users/`
which should return with
`{"id": "e3ce23b5-c6a1-4289-bb02-2f34a2f7b956", "name": "John", "city": "LA", "telephone": "555-555-0150"}`

## Cleanup

1. Delete the stack
```bash
sam delete
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```
----
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
90 changes: 90 additions & 0 deletions apigw-lambda-dsql/apigw-lambda-dsql
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
{
"title": "Amazon API Gateway, AWS Lambda and Amazon Aurora DSQL",
"description": "Creates an API Gateway REST API integrated with an AWS Lambda function that connects to an Amazon Aurora DSQL PostgreSQL cluster",
"language": "Python",
"level": "200",
"framework": "AWS SAM",
"introBox": {
"headline": "How it works",
"text": [
"This sample project demonstrates how to use a Lambda function (invoked by API Gateway), that stores and retrieves data from an Amazon Aurora DSQL PostgreSQL cluster.",
"Aurora DSQL enables you to build always available applications with virtually unlimited scalability, the highest availability, and zero infrastructure management.",
"This pattern deploys a API Gateway REST API, Lambda function and an Aurora DSQL PostgreSQL cluster."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-dsql",
"templateURL": "serverless-patterns/apigw-lambda-dsql",
"projectFolder": "apigw-lambda-dsql",
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "Amazon Aurora DSQL, the fastest serverless distributed SQL database is now generally available",
"link": "https://aws.amazon.com/blogs/aws/amazon-aurora-dsql-is-now-generally-available/"
},
{
"text": "DSQL Vignette: Aurora DSQL, and A Personal Story",
"link": "https://brooker.co.za/blog/2024/12/03/aurora-dsql.html/"
},
{
"text": "Amazon Aurora DSQL samples",
"link": "https://github.com/aws-samples/aurora-dsql-samples/tree/main/python"
}
]
},
"deploy": {
"text": [
"sam deploy"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"sam delete"
]
},
"authors": [
{
"name": "Yusuf Mayet",
"image": "https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2021/11/24/Yusuf-mayet-aws.jpg",
"bio": "I am a Solutions Architect at AWS, where I help customers realise that true transformation lies at the intersection of Cloud, DevOps cultural practices, Agile principles, modular and scalable architectures, and efficient team structures.",
"linkedin": "yusufmayet"
}
],
"patternArch": {
"icon1": {
"x": 20,
"y": 50,
"service": "apigw",
"label": "API Gateway REST API"
},
"icon2": {
"x": 50,
"y": 50,
"service": "lambda",
"label": "AWS Lambda"
},
"icon3": {
"x": 80,
"y": 50,
"service": "aurora",
"label": "Amazon Aurora DSQL"
},
"line1": {
"from": "icon1",
"to": "icon2"
},
"line2": {
"from": "icon2",
"to": "icon3"
}
}
}
62 changes: 62 additions & 0 deletions apigw-lambda-dsql/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"title": "Amazon API Gateway, AWS Lambda and Amazon Aurora DSQL",
"description": "Creates an API Gateway REST API integrated with an AWS Lambda function that connects to an Amazon Aurora DSQL PostgreSQL cluster",
"language": "Python",
"level": "200",
"framework": "AWS SAM",
"introBox": {
"headline": "How it works",
"text": [
"This sample project demonstrates how to use a Lambda function (invoked by API Gateway), that stores and retrieves data from an Amazon Aurora DSQL PostgreSQL cluster.",
"Aurora DSQL enables you to build always available applications with virtually unlimited scalability, the highest availability, and zero infrastructure management.",
"This pattern deploys a API Gateway REST API, Lambda function and an Aurora DSQL PostgreSQL cluster."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-dsql",
"templateURL": "serverless-patterns/apigw-lambda-dsql",
"projectFolder": "apigw-lambda-dsql",
"templateFile": "template.yaml"
}
},
"resources": {
"bullets": [
{
"text": "Amazon Aurora DSQL, the fastest serverless distributed SQL database is now generally available",
"link": "https://aws.amazon.com/blogs/aws/amazon-aurora-dsql-is-now-generally-available/"
},
{
"text": "DSQL Vignette: Aurora DSQL, and A Personal Story",
"link": "https://brooker.co.za/blog/2024/12/03/aurora-dsql.html/"
},
{
"text": "Amazon Aurora DSQL samples",
"link": "https://github.com/aws-samples/aurora-dsql-samples/tree/main/python"
}
]
},
"deploy": {
"text": [
"sam deploy"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"sam delete"
]
},
"authors": [
{
"name": "Yusuf Mayet",
"image": "https://d2908q01vomqb2.cloudfront.net/9e6a55b6b4563e652a23be9d623ca5055c356940/2021/11/24/Yusuf-mayet-aws.jpg",
"bio": "I am a Solutions Architect at AWS, where I help customers realise that true transformation lies at the intersection of Cloud, DevOps cultural practices, Agile principles, modular and scalable architectures, and efficient team structures.",
"linkedin": "yusufmayet"
}
]
}
74 changes: 74 additions & 0 deletions apigw-lambda-dsql/src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#SPDX-License-Identifier: MIT-0

import json
import boto3
import psycopg2
import psycopg2.extensions
import os

cluster_endpoint = os.environ['cluster_endpoint']
region = os.environ['AWS_REGION']

client = boto3.client("dsql", region_name=region)

def lambda_handler(event, context):
# Generate a fresh password token for each connection, to ensure the token is not expired when the connection is established
password_token = client.generate_db_connect_admin_auth_token(cluster_endpoint, region)

conn_params = {
"dbname": "postgres",
"user": "admin",
"host": cluster_endpoint,
"port": "5432",
"sslmode": "require",
"password": password_token
}

# Use the more efficient connection method if it's supported.
if psycopg2.extensions.libpq_version() >= 170000:
conn_params["sslnegotiation"] = "direct"

# Make a connection to the cluster
conn = psycopg2.connect(**conn_params)

try:
with conn.cursor() as cur:
conn.commit()
except Exception as e:
conn.close()
raise e

conn.set_session(autocommit=True)

cur = conn.cursor()

cur.execute("DROP TABLE IF EXISTS users")

cur.execute(b"""
CREATE TABLE IF NOT EXISTS users(
id uuid NOT NULL DEFAULT gen_random_uuid(),
name varchar(30) NOT NULL,
city varchar(80) NOT NULL,
telephone varchar(20) DEFAULT NULL,
PRIMARY KEY (id))"""
)

# Insert some rows
cur.execute("INSERT INTO users(name, city, telephone) VALUES('John', 'LA', '555-555-0150')")

# Read back what we have inserted
cur.execute("SELECT * FROM users")
row = cur.fetchone()
print(row)

# return JSON back to API Gateway
return {
'statusCode': 200,
'body': json.dumps({
'id': str(row[0]),
'name': row[1],
'city': row[2],
'telephone': row[3]
})
}
3 changes: 3 additions & 0 deletions apigw-lambda-dsql/src/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
psycopg2-binary>=2.9
botocore>=1.35.74
boto3>=1.35.74
58 changes: 58 additions & 0 deletions apigw-lambda-dsql/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless patterns - Amazon API Gateway, AWS Lambda and Amazon Aurora DSQL

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
# Global values that are applied to all applicable resources in this template
Globals:
Function:
CodeUri: ./src
Runtime: python3.13
MemorySize: 128
Timeout: 3
LoggingConfig:
LogGroup: !Sub /aws/lambda/${AWS::StackName}
LogFormat: JSON
Architectures:
- arm64
Tags:
project: "apigw-lambda-dsql"

Resources:
UsersFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
Handler: app.lambda_handler
Policies: # Creates an IAM Role that defines the services the function can access and which actions the function can perform
- Statement:
- Effect: Allow
Action:
- dsql:DbConnectAdmin
Resource:
- !Sub arn:${AWS::Partition}:dsql:${AWS::Region}:${AWS::AccountId}:cluster/${DSQL}
Environment: # Function environment variables
Variables:
REGION: !Sub ${AWS::Region}
cluster_endpoint: !Sub ${DSQL}.dsql.${AWS::Region}.on.aws
Events:
Users:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /users
Method: get

DSQL:
Type: AWS::DSQL::Cluster
Properties:
DeletionProtectionEnabled: false
Tags:
- Key: project
Value: "apigw-lambda-dsql"

Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
UsersApi:
Description: API Gateway endpoint URL for Prod stage for Users function
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/users/"