graph TD
%% BEFORE LAMBDA (Triggers)
subgraph Before["Triggers & Event Sources"]
subgraph Storage["Storage Events"]
S3["fa:fa-database S3 Events"]
DynamoStream["fa:fa-table DynamoDB Streams"]
end
subgraph API_Events["API & HTTP"]
API["fa:fa-globe API Gateway"]
SDK["fa:fa-code AWS SDK"]
end
subgraph Messaging["Messaging Systems"]
SQS["fa:fa-tasks SQS"]
SNS["fa:fa-bell SNS Topics"]
Kinesis["fa:fa-stream Kinesis"]
end
subgraph Schedulers["Scheduling"]
EventBridge["fa:fa-clock EventBridge"]
end
end
%% INSIDE LAMBDA (Runtime & Config)
subgraph LambdaDetails["Lambda Configuration & Execution"]
subgraph RuntimeEnv["Runtime Environment"]
Languages["fa:fa-language Node.js, Python, Java, .NET, Go, Ruby"]
Package["fa:fa-file-archive Max 50MB zip/250MB uncompressed"]
end
subgraph ConfigOptions["Configuration Options"]
Memory["fa:fa-memory Memory: 128MB-10GB"]
Timeout["fa:fa-hourglass-end Timeout: Max 15 Min"]
TemporaryStorage["fa:fa-database Temporary Storage (Max 512MB)"]
EnvVars["fa:fa-sliders-h Environment Variables"]
Concurrency["fa:fa-layer-group Concurrency: 1000 default"]
end
subgraph Permissions["Security & Permissions"]
Policies["fa:fa-lock Policy Documents"]
IAM["fa:fa-user-shield IAM Roles"]
Secrets["fa:fa-key Secrets Manager"]
end
subgraph ExecModel["Execution Model"]
Cold["fa:fa-snowflake Cold Start"]
Warm["fa:fa-fire Warm Start"]
Stateless["fa:fa-recycle Ephemeral Runtime"]
end
end
%% AFTER LAMBDA (Integrations & Monitoring)
subgraph After["Output & Monitoring"]
subgraph DataStores["Data Storage Options"]
DocumentDB["fa:fa-file-alt DocumentDB"]
DynamoDB["fa:fa-database DynamoDB"]
RDS["fa:fa-server RDS"]
S3out["fa:fa-hdd S3 Buckets"]
ES["fa:fa-search Elasticsearch"]
end
subgraph ResponseTypes["Response Types"]
SyncResp["fa:fa-exchange-alt Synchronous Response"]
AsyncResp["fa:fa-tasks Asynchronous Process"]
Step["fa:fa-project-diagram Step Functions"]
end
subgraph Monitoring["Monitoring & Logging"]
CloudWatch["fa:fa-tachometer-alt CloudWatch Metrics"]
CloudWatchLogs["fa:fa-list-alt CloudWatch Logs"]
XRay["fa:fa-sitemap X-Ray"]
Cost["fa:fa-coins Cost Explorer"]
end
end
%% EXTENDED FEATURES
subgraph Extended["Advanced Features"]
subgraph CodeOrg["Code Organization"]
CommonCode["fa:fa-layers Lambda Layers & Libraries"]
end
subgraph SecurityFeatures["Security Features"]
VPC["fa:fa-network-wired VPC Integration"]
SecretsManager["fa:fa-key Secrets Manager"]
ResourcePolicy["fa:fa-shield Resource Policies"]
end
subgraph DeployOps["Deployment & Operations"]
SAM["fa:fa-file-code SAM/CloudFormation"]
CICD["fa:fa-sync CodePipeline/GitHub Actions"]
Aliases["fa:fa-random Versions & Aliases"]
end
end
%% CONNECTIONS
Before -->LambdaDetails
LambdaDetails -->|"Function completes"| After
LambdaDetails -->|"Extends functionality"| Extended
graph TD
subgraph HandlerPatterns["Lambda Handler Code Patterns"]
subgraph BasicStructure["Basic Structure"]
ExportHandler["fa:fa-file-export exports.handler"]
AsyncFunction["fa:fa-tasks async function"]
TryCatch["fa:fa-shield-alt try/catch block"]
ReturnResponse["fa:fa-reply return response"]
end
subgraph EventProcessing["Event Processing"]
ParseEvent["fa:fa-filter Parse event object"]
ExtractParams["fa:fa-code-branch Extract parameters"]
ValidateInput["fa:fa-check-circle Validate input"]
ProcessData["fa:fa-cogs Process data"]
end
subgraph ResponsHandling["Response Formatting"]
StatusCode["fa:fa-hashtag statusCode"]
Headers["fa:fa-list headers"]
BodyContent["fa:fa-file-alt body content"]
Stringify["fa:fa-quote-right JSON.stringify()"]
end
subgraph ErrorHandling["Error Handling"]
CatchBlock["fa:fa-bug catch(error)"]
LogError["fa:fa-exclamation console.error()"]
CustomErrors["fa:fa-exclamation-triangle Custom error classes"]
ErrorResponse["fa:fa-reply-all Error response format"]
end
end
subgraph CommonPatterns["Common Code Patterns"]
subgraph AsyncOperations["Asynchronous Operations"]
PromiseAll["fa:fa-layer-group Promise.all()"]
AsyncAwait["fa:fa-hourglass async/await"]
Callbacks["fa:fa-phone-alt Callbacks"]
end
subgraph Middleware["Middleware Pattern"]
RequestValidation["fa:fa-filter Input validation"]
Authentication["fa:fa-lock Authentication"]
DataTransformation["fa:fa-random Data transformation"]
ResponseFormat["fa:fa-file-export Response formatting"]
end
subgraph StateManagement["State Management"]
GlobalVars["fa:fa-globe Global variables"]
DbConnections["fa:fa-database DB connections"]
HttpClients["fa:fa-server HTTP clients"]
ServiceInstances["fa:fa-cubes Service instances"]
end
subgraph LambdaOptimizations["Performance Optimizations"]
LazyLoading["fa:fa-spinner Lazy loading"]
ConnectionPooling["fa:fa-network-wired Connection pooling"]
Memoization["fa:fa-memory Memoization"]
CodeSplitting["fa:fa-cut Code splitting"]
end
end
%% CONNECTIONS
HandlerPatterns -->|"implements"| CommonPatterns
%% Internal connections
BasicStructure -->|"includes"| EventProcessing
EventProcessing -->|"produces"| ResponsHandling
EventProcessing -->|"may trigger"| ErrorHandling
# AWS Lambda Reference
## Table of Contents
- [Basic Lambda Function](#basic-lambda-function)
- [SQS Event Processing](#sqs-event-processing)
- [Common Triggers](#common-triggers)
- [Environment Variables](#environment-variables)
- [AWS SDK Integration](#aws-sdk-integration)
- [Error Handling](#error-handling)
- [Best Practices](#best-practices)
- [Cold Start Optimization](#cold-start-optimization)
- [Local Testing](#local-testing)
## **Basic Lambda Function** (Node.js):
Handle parameters when invoked via API Gateway:
```javascript
exports.handler = async (event, context) => {
try {
// Log the full event object
console.log('Event:', JSON.stringify(event, null, 2));
// Extract query parameters (for HTTP GET requests)
const queryParams = event.queryStringParameters || {};
// Extract path parameters (if defined in API Gateway)
const pathParams = event.pathParameters || {};
// Extract request body (for HTTP POST/PUT requests)
let body = {};
if (event.body) {
body = JSON.parse(event.body);
}
// Response with received parameters
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Hello from Lambda!',
queryParams,
pathParams,
body
})
};
return response;
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal Server Error' })
};
}
};
```
## **SQS Event Processing**
```js
async function processSqsEvent(event) {
const results = [];
const errors = [];
// Process each record individually
for (const record of event.Records) {
try {
// Parse the SQS message body
const body = JSON.parse(record.body);
// Process the message
const result = await processMessage(body);
results.push(result);
} catch (error) {
// Track errors but continue processing other records
console.error(`Error processing SQS record ${record.messageId}:`, error);
errors.push({
messageId: record.messageId,
error: error.message
});
}
}
// Return summary of processing
return {
processed: results.length,
failed: errors.length,
results,
errors
};
}
```
## **Common Triggers**:
- API Gateway (HTTP/REST API):
```yaml
Events:
ApiEvent:
Type: Api
Properties:
Path: /hello
Method: GET
```
- S3 Event:
```yaml
Events:
S3Event:
Type: S3
Properties:
Bucket: !Ref MyBucket
Events: s3:ObjectCreated:*
```
## **Environment Variables**:
```javascript
// Access environment variables
const tableName = process.env.TABLE_NAME;
const region = process.env.AWS_REGION;
```
## **AWS SDK Integration**:
```javascript
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const dynamodb = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
// Example: Write to DynamoDB
const params = {
TableName: process.env.TABLE_NAME,
Item: {
id: 'unique-id',
timestamp: Date.now()
}
};
await dynamodb.put(params).promise();
};
```
## **Error Handling**:
```javascript
exports.handler = async (event) => {
try {
// Your logic here
} catch (error) {
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({
error: 'Internal Server Error'
})
};
}
};
```
## **Best Practices**:
- Keep dependencies minimal to reduce cold start time
- Reuse AWS SDK clients outside the handler
- Use environment variables for configuration
- Implement proper error handling and logging
- Use IAM roles with minimum required permissions
## **Cold Start Optimization**:
```javascript
// Initialize clients outside handler
const dynamodb = new AWS.DynamoDB.DocumentClient();
const s3 = new AWS.S3();
// Reuse connections
exports.handler = async (event) => {
// Handler code using initialized clients
};
```
## **Local Testing** (using AWS SAM):
```bash
# Initialize SAM project
sam init
# Local testing
sam local invoke -e events/event.json
# Start local API
sam local start-api
```