
I Deployed a Django Runtime Environment (Lambda, Aurora) in Just Over 100 Seconds with cdkd
This page has been translated by machine translation. View original
Introduction
Django is an open-source web application framework written in Python.
In this article, I used Lambda Web Functions, which recently added Python support, as the runtime and Aurora PostgreSQL in express configuration as the DB, and measured how long it takes to build the initial environment. I'll share the results.
Test Environment
- Region: Tokyo (ap-northeast-1)
- cdkd: 0.370.0 (@cdkd/cli)
- aws-cdk-lib: 2.278.0
- Node.js: 24.21.0 (Docker's node:24)
- Runtime: python3.15 (Web Function, migration Lambda)
- Migration Lambda architecture: arm64
- Django: 6.1.3
- djangorestframework: 3.18.3
- psycopg: 3.3.9
- boto3: 1.44.9
- Aurora PostgreSQL: 17.9
- ACU: 0 to 2
- Measurement interval: from
RUN_STARTEDtoRUN_FINISHEDin cdkd events (excluding build and synth)
Application
Using the PostgreSQL settings in the official Django documentation and an article introducing a web app built with Django, I deployed a Python application that uses PostgreSQL as its DB.
Two Stacks
By default, a Web Function sends traffic without going through a VPC, and Aurora PostgreSQL in express configuration is created without being associated with a VPC.
For comparison, I also prepared a configuration in which a regular Aurora PostgreSQL is launched inside a VPC with a NAT Gateway. The Web Function is associated with the VPC, communication between Lambda and Aurora takes place inside the VPC, and outbound traffic goes through the NAT Gateway.
The differences between the two stacks are as follows.
| Item | No VPC (DjangoExpress) | With NAT Gateway (DjangoNat) |
|---|---|---|
| Aurora definition | One AWS::RDS::DBCluster resource. The writer is created together with the cluster and does not appear in the stack's resources | DatabaseCluster (regular configuration). DBCluster and DBInstance |
| Network | None. No egressNetworkConnector is specified for the Web Function, and the migration Lambda is not placed in a VPC either | VPC (2 public subnets, 2 private subnets), 1 NAT Gateway, Elastic IP, 2 security groups, NetworkConnector |
| DB authentication | IAM authentication token. Both the Web Function and the migration Lambda connect with the default master user postgres | Password in Secrets Manager. The migration Lambda creates the API user django_web_api |
| Secrets Manager | None. SECRET_KEY is generated at each application startup | The stack creates 2 (SECRET_KEY and the API DB user). In addition, it uses the master user secret managed by RDS |
| Number of cdkd resources | 21 | 51 |
No-VPC Configuration
The CDK stack is based on the configuration in the Qiita article mentioned in the Application section. Hereafter, I'll call this article the "original article."
The main changes from the original article's code in the no-VPC configuration are switching the DB connection from password authentication to using IAM authentication tokens, and removing the VPC and Secrets Manager related parts.
NAT Gateway Configuration
For comparison, I prepared a stack in which the VPC endpoints from the original article are replaced with a NAT Gateway.
DjangoNat is defined in the same infra/app.cjs as the no-VPC configuration. The following collapsible section shows the parts of the file other than DjangoExpress. The DjangoExpress definition is in the "Configuration" section.
infra/app.cjs (excluding DjangoExpress)
const { existsSync } = require("node:fs");
const { join } = require("node:path");
const cdk = require("aws-cdk-lib");
const {
aws_ec2: ec2,
aws_iam: iam,
aws_lambda: lambda,
aws_rds: rds,
aws_secretsmanager: sm,
} = cdk;
function requirePackage(name) {
const directory = join(__dirname, ".lambda-build", name);
if (!existsSync(join(directory, "rds-ca.pem"))) {
throw new Error(`The ${name} package is missing. Run bash build-lambda.sh from infra before deploying.`);
}
return directory;
}
const webPackage = requirePackage("web");
const migrationPackage = requirePackage("migration");
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: "ap-northeast-1" };
const app = new cdk.App();
// ---------------------------------------------------------------------------
// (ここに、次節の DjangoExpress のブロックを置く)
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// DjangoNat: VPC + NAT Gateway。元記事の構成から、VPC エンドポイントを NAT Gateway に置き換えたもの
// ---------------------------------------------------------------------------
{
const stack = new cdk.Stack(app, "DjangoNat", { env });
const vpc = new ec2.Vpc(stack, "Vpc", {
maxAzs: 2,
natGateways: 1,
subnetConfiguration: [
{ name: "public", subnetType: ec2.SubnetType.PUBLIC, cidrMask: 24 },
{ name: "private", subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, cidrMask: 24 },
],
});
const subnets = { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS };
const appSg = new ec2.SecurityGroup(stack, "AppSg", { vpc });
const dbSg = new ec2.SecurityGroup(stack, "DbSg", { vpc });
dbSg.addIngressRule(appSg, ec2.Port.tcp(5432));
const db = new rds.DatabaseCluster(stack, "Aurora", {
engine: rds.DatabaseClusterEngine.auroraPostgres({
version: rds.AuroraPostgresEngineVersion.VER_17_9,
}),
writer: rds.ClusterInstance.serverlessV2("Writer"),
vpc,
vpcSubnets: subnets,
securityGroups: [dbSg],
defaultDatabaseName: "django",
manageMasterUserPassword: true,
serverlessV2MinCapacity: 0,
serverlessV2MaxCapacity: 2,
serverlessV2AutoPauseDuration: cdk.Duration.minutes(5),
storageEncrypted: true,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
const dbSecret = db.secret;
const connector = new lambda.NetworkConnector(stack, "WebEgress", {
configuration: lambda.NetworkConnectorConfiguration.vpcEgress({
computeType: lambda.NetworkConnectorComputeType.WEB_FUNCTION,
vpc,
vpcSubnets: subnets,
securityGroups: [appSg],
}),
});
const djangoKey = new sm.Secret(stack, "DjangoSecretKey", {
generateSecretString: { passwordLength: 64 },
});
const apiDbSecret = new sm.Secret(stack, "DjangoApiDbSecret", {
generateSecretString: {
secretStringTemplate: JSON.stringify({ username: "django_web_api" }),
generateStringKey: "password",
passwordLength: 48,
},
});
const migrationAsset = new cdk.aws_s3_assets.Asset(stack, "MigrationAsset", { path: migrationPackage });
const migrator = new lambda.Function(stack, "Migrate", {
runtime: lambda.Runtime.PYTHON_3_15,
architecture: lambda.Architecture.ARM_64,
handler: "migrate_handler.handler",
code: lambda.Code.fromBucket(migrationAsset.bucket, migrationAsset.s3ObjectKey),
timeout: cdk.Duration.seconds(120),
vpc,
vpcSubnets: subnets,
securityGroups: [appSg],
environment: {
DJANGO_SETTINGS_MODULE: "config.settings",
POSTGRES_HOST: db.clusterEndpoint.hostname,
POSTGRES_DB: "django",
DB_SECRET_ARN: dbSecret.secretArn,
APP_DB_SECRET_ARN: apiDbSecret.secretArn,
},
});
const migration = new cdk.CustomResource(stack, "RunMigrations", {
resourceType: "Custom::DjangoMigrate",
serviceToken: migrator.functionArn,
properties: {
BundleHash: migrationAsset.assetHash,
DatabaseId: db.clusterResourceIdentifier,
ApiDbSecretArn: apiDbSecret.secretArn,
},
});
dbSecret.grantRead(migrator).applyBefore(migration);
apiDbSecret.grantRead(migrator).applyBefore(migration);
migration.node.addDependency(db);
new cdk.CfnOutput(stack, "MigrateFunctionName", { value: migrator.functionName });
const fn = new lambda.WebFunction(stack, "Web", {
code: lambda.WebFunctionCode.fromAssetToManagedBucket(webPackage),
runtime: lambda.WebFunctionRuntime.of("python3.15"),
defaultEndpointAuth: lambda.WebFunctionAuthType.IAM_AUTH,
egressNetworkConnector: connector,
timeout: cdk.Duration.seconds(60),
environment: {
DJANGO_SETTINGS_MODULE: "config.lambda_settings",
POSTGRES_HOST: db.clusterEndpoint.hostname,
POSTGRES_DB: "django",
APP_DB_SECRET_ARN: apiDbSecret.secretArn,
DJANGO_SECRET_ARN: djangoKey.secretArn,
},
});
new cdk.CfnOutput(stack, "EndpointUrl", { value: `https://${fn.endpoint.domainName}` });
fn.resourceRevision.node.addDependency(migration);
apiDbSecret.grantRead(fn).applyBefore(fn.resourceRevision);
djangoKey.grantRead(fn).applyBefore(fn.resourceRevision);
}
app.synth();
Configuration
CDK Stack
DjangoExpress, the no-VPC configuration, is defined as follows.
// ---------------------------------------------------------------------------
// DjangoExpress: VPC なし。Aurora エクスプレス構成 + IAM 認証
// ---------------------------------------------------------------------------
{
const stack = new cdk.Stack(app, "DjangoExpress", { env });
const cluster = new rds.CfnDBCluster(stack, "Aurora", {
engine: "aurora-postgresql",
dbClusterIdentifier: "lwf-express-django",
withExpressConfiguration: true,
serverlessV2ScalingConfiguration: { minCapacity: 0, maxCapacity: 2, secondsUntilAutoPause: 300 },
});
cluster.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);
const connectArn = stack.formatArn({
service: "rds-db",
resource: "dbuser",
resourceName: `${cluster.attrDbClusterResourceId}/postgres`,
arnFormat: cdk.ArnFormat.COLON_RESOURCE_NAME,
});
const dbEnv = {
POSTGRES_HOST: cluster.attrEndpointAddress,
POSTGRES_DB: "postgres",
POSTGRES_USER: "postgres",
};
const migrationAsset = new cdk.aws_s3_assets.Asset(stack, "MigrationAsset", { path: migrationPackage });
const migrator = new lambda.Function(stack, "Migrate", {
runtime: lambda.Runtime.PYTHON_3_15,
architecture: lambda.Architecture.ARM_64,
handler: "migrate_handler_iam.handler",
code: lambda.Code.fromBucket(migrationAsset.bucket, migrationAsset.s3ObjectKey),
timeout: cdk.Duration.seconds(120),
environment: { DJANGO_SETTINGS_MODULE: "config.lambda_settings_iam", ...dbEnv },
});
const migratorGrant = iam.Grant.addToPrincipal({
grantee: migrator,
actions: ["rds-db:connect"],
resourceArns: [connectArn],
});
const migration = new cdk.CustomResource(stack, "RunMigrations", {
resourceType: "Custom::DjangoMigrate",
serviceToken: migrator.functionArn,
properties: {
BundleHash: migrationAsset.assetHash,
DatabaseId: cluster.attrDbClusterResourceId,
},
});
migratorGrant.applyBefore(migration);
new cdk.CfnOutput(stack, "MigrateFunctionName", { value: migrator.functionName });
const fn = new lambda.WebFunction(stack, "Web", {
code: lambda.WebFunctionCode.fromAssetToManagedBucket(webPackage),
runtime: lambda.WebFunctionRuntime.of("python3.15"),
defaultEndpointAuth: lambda.WebFunctionAuthType.IAM_AUTH,
timeout: cdk.Duration.seconds(60),
environment: { DJANGO_SETTINGS_MODULE: "config.lambda_settings_iam", ...dbEnv },
});
fn.resourceRevision.node.addDependency(migration);
iam.Grant.addToPrincipal({
grantee: fn,
actions: ["rds-db:connect"],
resourceArns: [connectArn],
}).applyBefore(fn.resourceRevision);
new cdk.CfnOutput(stack, "EndpointUrl", { value: `https://${fn.endpoint.domainName}` });
}
When I specified databaseName on the express-configuration CfnDBCluster, the cdkd deployment failed with InvalidParameterCombination. Therefore, I did not specify databaseName and connect to the default postgres database. The deploying user needs rds:EnableInternetAccessGateway as one of the permissions for creating an express-configuration cluster.
Django Connection
For an express-configuration cluster not associated with a VPC, I connect to Aurora's public endpoint using IAM authentication. An IAM authentication token is valid for 15 minutes and must be regenerated once the connection ends. So I prepared a DB backend that creates a token with generate_db_auth_token on every connection and passes it as the password.
iam_backend/base.py
import os
import boto3
from django.db.backends.postgresql import base
class DatabaseWrapper(base.DatabaseWrapper):
"""Create an IAM authentication token on every connection and pass it as the password."""
def get_connection_params(self):
params = super().get_connection_params()
rds = boto3.client("rds", region_name=os.environ.get("AWS_REGION", "ap-northeast-1"))
params["password"] = rds.generate_db_auth_token(
DBHostname=params["host"],
Port=int(params.get("port") or 5432),
DBUsername=params["user"],
)
return params
The settings go in config/lambda_settings_iam.py.
config/lambda_settings_iam.py
# For the no-VPC configuration (Aurora express configuration. Connects with an IAM authentication token)
import os
import certifi
from django.core.management.utils import get_random_secret_key
from .settings import *
DEBUG = False
ALLOWED_HOSTS = [".lambda-web.ap-northeast-1.on.aws"]
SECRET_KEY = get_random_secret_key()
DATABASES = {
"default": {
"ENGINE": "iam_backend",
"NAME": os.environ["POSTGRES_DB"],
"HOST": os.environ["POSTGRES_HOST"],
"PORT": "5432",
"USER": os.environ["POSTGRES_USER"],
"OPTIONS": {
"sslmode": "verify-full",
"sslrootcert": certifi.where(),
"connect_timeout": 35,
},
},
}
Because the connection target uses an AWS root certificate (ACM's root CA), I specify certifi's CA bundle for sslrootcert. With this setting, I was able to connect while keeping sslmode=verify-full.
The handler for the migration Lambda is as follows.
migrate_handler_iam.py
import os
import subprocess
import sys
from pathlib import Path
def handler(event, context):
physical_id = event.get("PhysicalResourceId", "django-aurora-migrations")
request_type = event["RequestType"]
if request_type == "Delete":
return {"PhysicalResourceId": physical_id}
if request_type not in {"Create", "Update"}:
raise ValueError(f"Unexpected request type: {request_type}")
root = Path(__file__).resolve().parent
env = {**os.environ, "DJANGO_SETTINGS_MODULE": "config.lambda_settings_iam"}
subprocess.run(
[sys.executable, str(root / "manage.py"), "migrate", "--noinput"],
env=env,
check=True,
)
return {"PhysicalResourceId": physical_id}
Deployment Steps
In the infra directory, run the build, cdkd installation and bootstrap, deployment, and retrieval of measurement results, in that order. Docker is required for the build.
bash build-lambda.sh
npm install aws-cdk-lib@2.278.0 constructs @cdkd/cli@0.370.0
export CDK_DEFAULT_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
npx cdkd bootstrap --region ap-northeast-1
npx cdkd deploy DjangoExpress --region ap-northeast-1
npx cdkd events DjangoExpress --region ap-northeast-1
npx cdkd events DjangoExpress --region ap-northeast-1 --run <実行ID>
If you run cdkd events with only the stack name, a list of run IDs is displayed, and adding --run displays per-resource events for the specified run. For the NAT Gateway configuration, I ran the same steps with the stack name changed to DjangoNat.
Files used for the build
infra/build-lambda.sh
#!/bin/bash
# Docker 内で Lambda 用パッケージ(Python 3.15 / Linux arm64)を作る。ホストでは pip を実行しない。
# 使い方: infra ディレクトリで bash build-lambda.sh
set -euo pipefail
infra_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
project_dir="$(cd "$infra_dir/.." && pwd)"
docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp \
-v "$project_dir:/app" -w /app python:3.13 bash -c '
set -euo pipefail
build=/app/infra/.lambda-build
stage=$(mktemp -d)
python -m pip install -q \
--platform manylinux_2_28_aarch64 \
--implementation cp --python-version 3.15 --abi cp315 \
--only-binary=:all: --no-compile \
--target "$stage/web" \
-r requirements.txt
for f in main.py manage.py config posts iam_backend requirements.txt; do cp -r "$f" "$stage/web/"; done
find "$stage/web" -name __pycache__ -type d -prune -exec rm -rf {} +
python - <<PY
import urllib.request
urllib.request.urlretrieve(
"https://truststore.pki.rds.amazonaws.com/ap-northeast-1/ap-northeast-1-bundle.pem",
"$stage/web/rds-ca.pem",
)
PY
mkdir "$stage/migration"
cp -r "$stage/web/." "$stage/migration/"
cp migrate_handler.py migrate_handler_iam.py "$stage/migration/"
rm -rf "$build"
mkdir -p "$build"
cp -r "$stage/web" "$build/web"
cp -r "$stage/migration" "$build/migration"
echo "Built Web Function and migration packages in $build"
'
requirements.txt (one directory above infra)
Django==6.1.3
djangorestframework==3.18.3
psycopg[binary]==3.3.9
boto3==1.44.9
certifi
infra/cdk.json
{"app":"node app.cjs"}
Verification
For the no-VPC configuration (DjangoExpress), I used describe-db-clusters to confirm that a writer had been created even though the stack defines no DBInstance. I also confirmed that the cluster is not associated with a VPC and is configured to connect to a public endpoint.
aws rds describe-db-clusters --db-cluster-identifier lwf-express-django --query 'DBClusters[0].{Status:Status,Engine:Engine,EngineVersion:EngineVersion,VPCNetworkingEnabled:VPCNetworkingEnabled,InternetAccessGatewayEnabled:InternetAccessGatewayEnabled,IAMDatabaseAuthenticationEnabled:IAMDatabaseAuthenticationEnabled,DBSubnetGroup:DBSubnetGroup,Members:DBClusterMembers[].DBInstanceIdentifier,Scaling:ServerlessV2ScalingConfiguration}' --output json
Output (excerpt):
"VPCNetworkingEnabled": false,
"InternetAccessGatewayEnabled": true,
"IAMDatabaseAuthenticationEnabled": true,
"DBSubnetGroup": null,
"Members": [
"lwf-express-django-instance-1"
],
The Web Function endpoint uses IAM authentication, so requests require a SigV4 signature. Using a script that makes signed calls, I tried creating a post, listing posts, and retrieving post details. <host> is the host name of the stack output EndpointUrl.
$ python posts_api.py <host> POST /api/posts/ '{"title":"Lambdaから作成した投稿"}'
HTTP 201
{"id":1,"title":"Lambdaから作成した投稿"}
$ python posts_api.py <host> GET /api/posts/
HTTP 200
[{"id":1,"title":"Lambdaから作成した投稿"}]
$ python posts_api.py <host> GET /api/posts/1/
HTTP 200
{"id":1,"title":"Lambdaから作成した投稿"}
For the NAT Gateway configuration (DjangoNat) as well, I confirmed post creation (201), listing (200), and detail retrieval (200) with the same script. The cluster is Aurora PostgreSQL 17.9, with VPCNetworkingEnabled true and InternetAccessGatewayEnabled false.
posts_api.py
Since it imports botocore, you need to run pip install botocore before running it. Credentials are loaded from environment variables or the default configuration.
"""Web Function の IAM 認証エンドポイントへ、SigV4 署名付きでリクエストする。
使い方: python posts_api.py <host> <METHOD> <path> [<json-body>]
"""
import sys
from hashlib import sha256
from http.client import HTTPSConnection
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.session import Session
host, method, path = sys.argv[1:4]
body = sys.argv[4].encode("utf-8") if len(sys.argv) > 4 else None
headers = {
"Host": host,
"Accept": "application/json",
"X-Amz-Content-SHA256": sha256(body or b"").hexdigest(),
}
if body is not None:
headers["Content-Type"] = "application/json"
credentials = Session().get_credentials()
if credentials is None:
raise SystemExit("AWS の認証情報が見つからない")
request = AWSRequest(method=method, url=f"https://{host}{path}", data=body, headers=headers)
SigV4Auth(credentials.get_frozen_credentials(), "lambda", "ap-northeast-1").add_auth(request)
connection = HTTPSConnection(host, timeout=60)
try:
connection.request(method, path, body=body, headers=dict(request.headers.items()))
response = connection.getresponse()
print(f"HTTP {response.status}")
print(response.read().decode("utf-8"))
finally:
connection.close()
Measurement Results
Each value is the measurement from the initial deployment, performed once per configuration.
Overall Deployment
The RUN_FINISHED lines from the output of cdkd events --run are shown below, for the no-VPC configuration and then the NAT Gateway configuration.
RUN_FINISHED SUCCEEDED 104617ms +21/~0/-0
RUN_FINISHED SUCCEEDED 544941ms +51/~0/-0
Per Resource
The durations reported in each resource's RESOURCE_SUCCEEDED event, converted to seconds.
| Resource | No VPC (sec) | With NAT Gateway (sec) |
|---|---|---|
| Aurora (DBCluster) | 27.6 | 28.3 |
| AuroraWriter (DBInstance) | No DBInstance resource | 366.2 |
| WebEgress (NetworkConnector) | None | 260.4 |
| NAT Gateway | None | 125.1 |
| RunMigrations | 65.5 | 39.2 |
| WebRevision | 4.8 | 5.0 |
| WebEndpoint | 3.8 | 3.4 |
| Total | 104.6 | 544.9 |
Conclusion
By using a configuration without a VPC, I was able to build a Django and PostgreSQL runtime environment with cdkd in a little over 100 seconds.
Aurora PostgreSQL in express configuration now also supports creation inside a VPC and moving to a VPC, but
using a VPC comes with side effects, such as increased costs for things like a NAT Gateway and longer setup times due to ENI creation.
For development environments running on AWS, where the application only needs to connect to PostgreSQL and public AWS services, please consider trying a VPC-less configuration.
