AWS Lambda Serverless Functions

backend
JavaScript
scaffolding
corporate_pm
Remix

Build serverless functions on AWS Lambda with API Gateway, DynamoDB, and S3 integration.

12/8/2025

Prompt

AWS Lambda Serverless Application

Build serverless functions for [Application] using AWS Lambda with API Gateway, DynamoDB, and other AWS services.

Requirements

1. Lambda Functions

Create functions for:

  • [Function 1] - [Purpose] (e.g., API endpoint)
  • [Function 2] - [Purpose] (e.g., data processing)
  • [Function 3] - [Purpose] (e.g., event handler)

2. Trigger Configuration

Set up triggers:

  • API Gateway - HTTP/REST API endpoints
  • S3 Events - File upload processing
  • DynamoDB Streams - Database change events
  • EventBridge - Scheduled/custom events
  • SQS/SNS - Message queue processing

3. AWS Integration

Integrate with:

  • DynamoDB for data storage
  • S3 for file storage
  • SES for email sending
  • Secrets Manager for credentials
  • CloudWatch for logging

4. Infrastructure as Code

Use:

  • AWS SAM template for deployment
  • CloudFormation for resources
  • Environment variables
  • IAM roles and permissions

5. Error Handling & Monitoring

Implement:

  • Proper error responses
  • CloudWatch logging
  • X-Ray tracing (optional)
  • Dead letter queues
  • Retry logic

Implementation Pattern

// handler.js - Basic Lambda function
exports.handler = async (event, context) => {
  console.log('Event:', JSON.stringify(event, null, 2))
  
  try {
    // Parse input
    const body = JSON.parse(event.body || '{}')
    
    // Your logic here
    const result = await process[Operation](body)
    
    // Return success response
    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        message: 'Success',
        data: result
      })
    }
  } catch (error) {
    console.error('Error:', error)
    
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        error: error.message
      })
    }
  }
}

// DynamoDB integration
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB.DocumentClient()

exports.handler = async (event) => {
  const { id, [field] } = JSON.parse(event.body)
  
  // Put item
  await dynamodb.put({
    TableName: process.env.TABLE_NAME,
    Item: {
      id,
      [field],
      createdAt: new Date().toISOString()
    }
  }).promise()
  
  // Get item
  const result = await dynamodb.get({
    TableName: process.env.TABLE_NAME,
    Key: { id }
  }).promise()
  
  // Query items
  const items = await dynamodb.query({
    TableName: process.env.TABLE_NAME,
    KeyConditionExpression: 'id = :id',
    ExpressionAttributeValues: {
      ':id': id
    }
  }).promise()
  
  return {
    statusCode: 200,
    body: JSON.stringify(result.Item)
  }
}

// S3 trigger
exports.handler = async (event) => {
  const s3 = new AWS.S3()
  
  for (const record of event.Records) {
    const bucket = record.s3.bucket.name
    const key = decodeURIComponent(record.s3.object.key.replace(/\\+/g, ' '))
    
    console.log(`Processing file: ${bucket}/${key}`)
    
    // Get file from S3
    const file = await s3.getObject({
      Bucket: bucket,
      Key: key
    }).promise()
    
    // Process file
    await process[File](file.Body)
  }
}

SAM Template (template.yaml)

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Runtime: nodejs20.x
    Environment:
      Variables:
        TABLE_NAME: !Ref [TableName]

Resources:
  [FunctionName]:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./
      Handler: index.handler
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /[path]
            Method: [method]
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref [TableName]

  [TableName]:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: [table-name]
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH

Deployment

# Build and deploy
sam build
sam deploy --guided

# Local testing
sam local invoke [FunctionName] -e event.json
sam local start-api

Best Practices

  • Use environment variables for configuration
  • Implement proper error handling
  • Keep functions small and focused
  • Use layers for shared dependencies
  • Enable X-Ray tracing for debugging
  • Set appropriate timeout and memory
  • Use provisioned concurrency for critical functions
  • Implement proper IAM least privilege
  • Monitor with CloudWatch metrics

Tags

aws
lambda
serverless
cloud

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In
AWS Lambda Serverless Functions | vibeprompt.directory