← Back to AI Lab

AWS Lambda API

I built a serverless voting API with AWS Lambda and API Gateway. Zero servers to manage.

exports.handler = async (event) => { const { httpMethod, body, headers } = event; // CORS handling const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS' }; if (httpMethod === 'OPTIONS') { return { statusCode: 200, headers: corsHeaders }; } };

API Gateway routes requests to Lambda functions. DynamoDB stores vote data.

// DynamoDB integration const AWS = require('aws-sdk'); const dynamodb = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'project-votes', Key: { projectId: 'terrellflautt-portfolio' }, UpdateExpression: 'ADD voteCount :val', ExpressionAttributeValues: { ':val': 1 }, ReturnValues: 'UPDATED_NEW' }; const result = await dynamodb.update(params).promise();

Cost: $0.00. Handles 1M requests monthly on free tier.

Auto-scaling built-in. No capacity planning needed.

// Rate limiting with DynamoDB const rateLimit = { TableName: 'rate-limits', Key: { ip: clientIP }, UpdateExpression: 'ADD requestCount :val', ExpressionAttributeValues: { ':val': 1 }, ReturnValues: 'UPDATED_NEW' }; if (result.Attributes.requestCount > 10) { return { statusCode: 429, body: 'Rate limited' }; }

Deployment through CloudFormation:

Resources: VotingFunction: Type: AWS::Lambda::Function Properties: Runtime: nodejs18.x Handler: index.handler Code: ZipFile: | exports.handler = async (event) => { // Function code here }; VotingApi: Type: AWS::ApiGateway::RestApi Properties: Name: voting-api VotingDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !Ref VotingApi StageName: prod

Infrastructure as code. Version controlled. Reproducible deployments.

Cold start optimization:

// Keep connections warm let dynamodb; exports.handler = async (event) => { if (!dynamodb) { dynamodb = new AWS.DynamoDB.DocumentClient(); } // Use existing connection };

Response time: 100ms average. 50ms when warm.

Monitoring with CloudWatch. Errors trigger SNS notifications automatically.