|
| 1 | +# PostgreSQL and Lambda Integration Example |
| 2 | + |
| 3 | +A complete AWS CDK example demonstrating bidirectional integration between Aurora PostgreSQL Serverless v2 and AWS Lambda functions. |
| 4 | + |
| 5 | +## What This Example Demonstrates |
| 6 | + |
| 7 | +- **Lambda → PostgreSQL**: Lambda function that connects to and queries PostgreSQL |
| 8 | +- **PostgreSQL → Lambda**: PostgreSQL database that invokes Lambda functions using the `aws_lambda` extension |
| 9 | +- **Secure Architecture**: Private subnets, IAM roles, and Secrets Manager integration |
| 10 | +- **Production-Ready**: Includes error handling, connection pooling, and security best practices |
| 11 | +- **Automated Setup**: Custom CDK resource automatically configures PostgreSQL extensions and functions |
| 12 | +- **Yarn Workspaces**: Organized monorepo structure for managing multiple Lambda functions |
| 13 | + |
| 14 | +## Architecture |
| 15 | + |
| 16 | +```mermaid |
| 17 | +graph TD |
| 18 | + subgraph VPC |
| 19 | + subgraph "Private Subnet" |
| 20 | + DB[Aurora PostgreSQL\nServerless v2] |
| 21 | + L1[Lambda Function\nLambdaToPostgres] |
| 22 | + L2[Lambda Function\nPostgresFunction] |
| 23 | + L3[Lambda Function\nPostgresSetup] |
| 24 | + end |
| 25 | + end |
| 26 | + |
| 27 | + L1 -->|"1. Connect and Query"| DB |
| 28 | + DB -->|"2. Invoke via aws_lambda extension"| L2 |
| 29 | + L2 -->|"3. Return Result"| DB |
| 30 | + L3 -->|"4. Setup Extensions & Functions"| DB |
| 31 | + |
| 32 | + SM[AWS Secrets Manager] -->|Provide Credentials| L1 |
| 33 | + SM -->|Provide Credentials| L3 |
| 34 | + |
| 35 | + style DB fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#000 |
| 36 | + style L1 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#000 |
| 37 | + style L2 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#000 |
| 38 | + style L3 fill:#E8F5E8,stroke:#4CAF50,stroke-width:2px,color:#000 |
| 39 | + style SM fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#000 |
| 40 | +``` |
| 41 | + |
| 42 | +**Components:** |
| 43 | +- Aurora PostgreSQL Serverless v2 cluster (private subnet) |
| 44 | +- Lambda function for database operations (`LambdaToPostgres`) |
| 45 | +- Lambda function invokable from PostgreSQL (`PostgresFunction`) |
| 46 | +- Lambda function for automated setup (`PostgresSetupFunction`) |
| 47 | +- IAM roles with least-privilege permissions |
| 48 | +- Security groups for network access control |
| 49 | +- AWS Secrets Manager for credential storage |
| 50 | +- Custom CDK resource for automated PostgreSQL configuration |
| 51 | + |
| 52 | +## Quick Start |
| 53 | + |
| 54 | +### Prerequisites |
| 55 | + |
| 56 | +- AWS CDK v2 installed (`npm install -g aws-cdk`) |
| 57 | +- Node.js 18.x or later |
| 58 | +- Yarn package manager installed |
| 59 | +- AWS CLI configured with appropriate credentials |
| 60 | + |
| 61 | +### Deploy |
| 62 | + |
| 63 | +```bash |
| 64 | +# Install dependencies using yarn workspaces |
| 65 | +yarn install |
| 66 | + |
| 67 | +# Deploy the stack (setup is now automated!) |
| 68 | +yarn cdk deploy |
| 69 | +``` |
| 70 | + |
| 71 | +The deployment will automatically: |
| 72 | +- Create the Aurora PostgreSQL cluster |
| 73 | +- Deploy all Lambda functions |
| 74 | +- Configure PostgreSQL extensions and functions |
| 75 | +- Set up all necessary permissions |
| 76 | + |
| 77 | +No manual setup required! 🎉 |
| 78 | + |
| 79 | +## Testing |
| 80 | + |
| 81 | +### Test Lambda → PostgreSQL |
| 82 | + |
| 83 | +Using AWS CLI directly: |
| 84 | +```bash |
| 85 | +aws lambda invoke \ |
| 86 | + --function-name <LAMBDA_TO_POSTGRES_FUNCTION_NAME> \ |
| 87 | + --payload '{"message": "Hello from CLI!"}' \ |
| 88 | + response.json && cat response.json |
| 89 | +``` |
| 90 | + |
| 91 | +### Test PostgreSQL → Lambda |
| 92 | + |
| 93 | +Connect to PostgreSQL and test the functions: |
| 94 | +```bash |
| 95 | +psql -h <DB_CLUSTER_ENDPOINT> -U postgres -d demodb |
| 96 | +``` |
| 97 | + |
| 98 | +```sql |
| 99 | +-- Test the PostgreSQL to Lambda integration |
| 100 | +SELECT process_data('{"id": 123, "value": "test"}'::JSONB); |
| 101 | +SELECT transform_data('{"id": 456, "value": "hello world"}'::JSONB); |
| 102 | +SELECT validate_data('{"id": 789, "value": "valid data"}'::JSONB); |
| 103 | +``` |
| 104 | + |
| 105 | +## How It Works |
| 106 | + |
| 107 | +### Automated Setup Process |
| 108 | + |
| 109 | +1. **CDK Deployment**: Stack creates all resources including a setup Lambda function |
| 110 | +2. **Custom Resource**: Triggers the setup Lambda after database is ready |
| 111 | +3. **Extension Installation**: Setup function creates the `aws_lambda` extension |
| 112 | +4. **Function Creation**: Creates SQL functions that wrap Lambda invocations |
| 113 | +5. **Ready to Use**: Database is immediately ready for bidirectional Lambda integration |
| 114 | + |
| 115 | +### Lambda to PostgreSQL Flow |
| 116 | + |
| 117 | +1. **Credential Retrieval**: Function retrieves DB credentials from Secrets Manager |
| 118 | +2. **Connection**: Establishes secure SSL connection to PostgreSQL |
| 119 | +3. **Table Management**: Creates demo table if it doesn't exist |
| 120 | +4. **Data Operations**: Inserts message and queries recent records |
| 121 | +5. **Response**: Returns formatted results with error handling |
| 122 | + |
| 123 | +### PostgreSQL to Lambda Flow |
| 124 | + |
| 125 | +1. **Extension Setup**: Uses `aws_lambda` extension for Lambda invocation (automated) |
| 126 | +2. **Function Creation**: SQL functions wrap Lambda calls with proper ARN construction (automated) |
| 127 | +3. **Synchronous Invocation**: Uses 'RequestResponse' invocation type for immediate results |
| 128 | +4. **Event Processing**: Lambda receives structured JSON events from PostgreSQL |
| 129 | +5. **Result Return**: Lambda response becomes available in SQL query results |
| 130 | + |
| 131 | +## Project Structure |
| 132 | + |
| 133 | +``` |
| 134 | +├── bin/ # CDK app entry point |
| 135 | +├── lib/ # CDK stack definition |
| 136 | +├── lambda/ # Lambda function source code |
| 137 | +│ ├── lambda-to-postgres/ # Lambda that calls PostgreSQL |
| 138 | +│ ├── postgres-to-lambda/ # Lambda called by PostgreSQL |
| 139 | +│ └── postgres-setup/ # Lambda for automated setup |
| 140 | +├── test/ # Unit tests |
| 141 | +├── .yarn/ # Yarn 2+ configuration |
| 142 | +└── README.md # This file |
| 143 | +``` |
| 144 | + |
| 145 | +## Yarn Workspaces |
| 146 | + |
| 147 | +This project uses Yarn Workspaces to manage multiple packages in a monorepo structure: |
| 148 | + |
| 149 | +```bash |
| 150 | +# List all workspaces |
| 151 | +yarn workspaces list |
| 152 | + |
| 153 | +# Run a command in all workspaces |
| 154 | +yarn workspaces foreach -v -A run <command> |
| 155 | + |
| 156 | +# Run a command in a specific workspace |
| 157 | +yarn workspace postgres-to-lambda run <command> |
| 158 | + |
| 159 | +# Install dependencies for all workspaces |
| 160 | +yarn install |
| 161 | +``` |
| 162 | + |
| 163 | +The workspace structure allows for: |
| 164 | +- Shared dependencies between packages |
| 165 | +- Individual package management |
| 166 | +- Simplified build and deployment process |
| 167 | +- Better organization of Lambda functions |
| 168 | + |
| 169 | +## Configuration |
| 170 | + |
| 171 | +### Environment Variables |
| 172 | + |
| 173 | +The Lambda functions use these environment variables (set automatically by CDK): |
| 174 | + |
| 175 | +- `DB_SECRET_ARN`: ARN of the database credentials secret |
| 176 | +- `DB_NAME`: Database name (default: `demodb`) |
| 177 | +- `POSTGRES_FUNCTION_NAME`: Name of the Lambda function called by PostgreSQL |
| 178 | +- `AWS_REGION`: AWS region for Lambda ARN construction |
| 179 | + |
| 180 | +### Customization |
| 181 | + |
| 182 | +- **Database Configuration**: Modify `lib/postgres-lambda-stack.ts` |
| 183 | +- **Lambda Logic**: Update files in `lambda/` directories |
| 184 | +- **Setup SQL**: Customize `lambda/postgres-setup/index.js` |
| 185 | + |
| 186 | +## Security Features |
| 187 | + |
| 188 | +✅ **Network Security** |
| 189 | +- Database in private subnets |
| 190 | +- Security groups with minimal required access |
| 191 | +- No direct internet access to database |
| 192 | + |
| 193 | +✅ **Access Control** |
| 194 | +- IAM roles with least-privilege permissions |
| 195 | +- Secrets Manager for credential storage |
| 196 | +- SSL/TLS encryption for database connections |
| 197 | + |
| 198 | +✅ **Monitoring** |
| 199 | +- CloudWatch logs for all Lambda functions |
| 200 | +- Database performance insights available |
| 201 | +- VPC Flow Logs (can be enabled) |
| 202 | + |
| 203 | +## Production Considerations |
| 204 | + |
| 205 | +Before using in production: |
| 206 | + |
| 207 | +- [ ] Enable SSL certificate validation (`rejectUnauthorized: true`) |
| 208 | +- [ ] Implement connection pooling (consider RDS Proxy) |
| 209 | +- [ ] Set up proper monitoring and alerting |
| 210 | +- [ ] Configure backup and disaster recovery |
| 211 | +- [ ] Review and tighten IAM policies |
| 212 | +- [ ] Enable database encryption at rest |
| 213 | +- [ ] Set up VPC endpoints for AWS services |
| 214 | +- [ ] Implement proper error handling and retry logic |
| 215 | + |
| 216 | +## Troubleshooting |
| 217 | + |
| 218 | +### Common Issues |
| 219 | + |
| 220 | +**Connection Timeouts** |
| 221 | +- Check security group rules |
| 222 | +- Verify Lambda is in correct VPC/subnets |
| 223 | +- Confirm database is running |
| 224 | + |
| 225 | +**Permission Errors** |
| 226 | +- Verify IAM roles have required permissions |
| 227 | +- Check Secrets Manager access |
| 228 | +- Confirm Lambda execution role |
| 229 | + |
| 230 | +**Setup Function Issues** |
| 231 | +- Check CloudWatch logs for the PostgresSetupFunction |
| 232 | +- Verify custom resource completed successfully |
| 233 | +- Ensure database is accessible from setup Lambda |
| 234 | + |
| 235 | +### Useful Commands |
| 236 | + |
| 237 | +```bash |
| 238 | +# Build all packages |
| 239 | +yarn build |
| 240 | + |
| 241 | +# Build only Lambda functions |
| 242 | +yarn build:lambda |
| 243 | + |
| 244 | +# Build and watch for changes |
| 245 | +yarn watch |
| 246 | + |
| 247 | +# Run tests |
| 248 | +yarn test |
| 249 | + |
| 250 | +# View CloudFormation template |
| 251 | +yarn cdk synth |
| 252 | + |
| 253 | +# Compare deployed vs current state |
| 254 | +yarn cdk diff |
| 255 | + |
| 256 | +# View stack outputs |
| 257 | +aws cloudformation describe-stacks --stack-name PostgresLambdaStack --query 'Stacks[0].Outputs' |
| 258 | + |
| 259 | +# Check setup function logs |
| 260 | +aws logs describe-log-groups --log-group-name-prefix /aws/lambda/PostgresLambdaStack-PostgresSetupFunction |
| 261 | +``` |
| 262 | + |
| 263 | +## Cleanup |
| 264 | + |
| 265 | +```bash |
| 266 | +yarn cdk destroy |
| 267 | +``` |
| 268 | + |
| 269 | +**Note**: This will delete all resources including the database and any data stored in it. |
| 270 | + |
| 271 | +## Cost Optimization |
| 272 | + |
| 273 | +- Aurora Serverless v2 scales to zero when not in use |
| 274 | +- Lambda functions only charge for execution time |
| 275 | +- Setup function runs only once during deployment |
| 276 | +- Consider Reserved Capacity for consistent workloads |
| 277 | +- Monitor usage with AWS Cost Explorer |
| 278 | + |
| 279 | +## Related Examples |
| 280 | + |
| 281 | +- [Lambda with RDS Proxy](../lambda-rds-proxy/) |
| 282 | +- [Aurora Serverless v1](../aurora-serverless-v1/) |
| 283 | +- [PostgreSQL with CDK](../postgresql-cdk/) |
| 284 | + |
| 285 | +## Contributing |
| 286 | + |
| 287 | +1. Fork the repository |
| 288 | +2. Create a feature branch |
| 289 | +3. Make your changes |
| 290 | +4. Add tests if applicable |
| 291 | +5. Submit a pull request |
| 292 | + |
| 293 | +## License |
| 294 | + |
| 295 | +This example is provided under the MIT-0 License. See the LICENSE file for details. |
0 commit comments