AWS Lambdas

AWS Lambda Functions

Here’s a quick reference for AWS Lambda that covers key concepts, use cases, best practices, and troubleshooting tips.


Basic Concepts

  1. What is AWS Lambda?
    • AWS Lambda is a serverless compute service that runs your code in response to events (e.g., HTTP requests, file uploads, etc.) without provisioning or managing servers.
    • You pay only for the compute time you consume.
  2. Components of Lambda:
    • Function: The core logic that runs in Lambda.
    • Trigger/Event Source: AWS services (e.g., S3, API Gateway, DynamoDB) that invoke the Lambda function.
    • Execution Role: An IAM role that grants Lambda permission to access other AWS services/resources.
    • Layer: A deployment package that can include libraries, custom runtimes, etc., shared across multiple functions.

Lambda Function Structure

  1. Lambda Function Handler:
    • Handler: The entry point of the Lambda function. Defined as file_name.function_name in the Lambda console.
    • Event: The input data passed into the handler, often in JSON format.
    • Context: Provides runtime information (e.g., function name, memory limit).
  2. Lambda Runtime:
    • Supports multiple languages such as Python, Node.js, Java, Ruby, Go, .NET Core, and custom runtimes.
  3. Response Format:
    • Return value is typically a JSON-encoded response or status code.

Key AWS Lambda Features

  1. Event Sources:
    • Amazon API Gateway: Invoke Lambda via HTTP endpoints.
    • Amazon S3: Trigger Lambda when an object is uploaded.
    • Amazon DynamoDB: Trigger Lambda on DynamoDB table updates.
    • Amazon SNS: Trigger Lambda when a message is published.
    • CloudWatch Events: Schedule Lambda functions or respond to system events.
    • AWS Step Functions: Orchestrate multiple Lambda invocations.
  2. Timeouts:
    • Maximum execution time per invocation is 15 minutes (900 seconds).
    • Exceeding this limit results in an automatic function timeout.
  3. Memory:
    • Lambda functions can be configured to use between 128 MB and 10 GB of memory.
  4. Concurrency:
    • AWS Lambda can scale horizontally to handle high traffic.
    • Reserved concurrency: Set the maximum number of concurrent executions for a function.
    • Provisioned concurrency: Pre-warm a set number of function instances for faster response times.

Best Practices

  1. Keep functions small: Functions should perform one task well (single responsibility).
  2. Stateless: Lambda functions are stateless by design. Use external storage (S3, DynamoDB) to persist data.
  3. Environment Variables: Store configuration settings, secrets, or API keys in environment variables instead of hardcoding them.
  4. Error Handling: Use try-catch blocks and return error messages in the response. Optionally, configure dead-letter queues (DLQ) for failed invocations.
  5. Optimize Code: Minimize cold start time by reducing the size of deployment packages (e.g., avoid heavy dependencies).
  6. Use Layers: Share common libraries (e.g., logging, monitoring) across functions via Lambda layers.
  7. Logging: Enable Amazon CloudWatch Logs for detailed function logs and troubleshoot issues.

Lambda Security

  1. IAM Role Permissions:
    • Lambda functions need an IAM role with permissions to access AWS services (S3, DynamoDB, etc.).
    • Use the least-privilege principle to grant only the required permissions.
  2. VPC Access:
    • Lambda can be configured to access resources inside a VPC (e.g., RDS, EC2).
    • Ensure proper VPC configuration (subnets, security groups, etc.) to allow Lambda to communicate with resources.
  3. Encryption:
    • Data at rest: Lambda supports encryption of environment variables and function code.
    • Data in transit: Use TLS to secure communication with event sources.

Lambda Function Deployment

  1. Deployment Packages:
    • Deployment can be done using a zip file (direct upload), Amazon S3 (for larger packages), or AWS SAM(Serverless Application Model).
  2. AWS Lambda Layers:
    • Layers allow you to package dependencies (e.g., libraries) separately from the function code, which reduces deployment size and reusability.
  3. Versioning:
    • Lambda supports versioning, enabling you to publish multiple versions of a function and manage traffic to specific versions.
  4. AWS SAM / Serverless Framework:
    • Use AWS SAM or Serverless Framework to define infrastructure as code for deploying Lambda functions and other resources.

Performance Considerations

  1. Cold Starts:
    • Cold start refers to the initialization time of a Lambda function when it hasn’t been invoked recently or is scaled to zero.
    • Reduce cold start time by using smaller function packages, and optimized code, and considering Provisioned Concurrency for low-latency applications.
  2. Provisioned Concurrency:
    • Pre-warm instances to avoid cold starts.
    • Useful for performance-critical applications, such as low-latency APIs.

Cost Management

  1. Lambda Pricing:
    • Lambda charges based on:
      • Number of requests: $0.20 per 1 million requests.
      • Compute time: Based on the function’s execution time and allocated memory.
    • AWS provides free tier: 1 million requests and 400,000 GB-seconds per month.
  2. Optimizing Cost:
    • Reduce function execution time by optimizing code and memory allocation.
    • Monitor with CloudWatch to analyze function usage and adjust memory allocation accordingly.

Monitoring & Debugging

  1. CloudWatch Logs:
    • Enable logging to CloudWatch for real-time function insights (e.g., execution duration, error logs).
  2. CloudWatch Metrics:
    • Lambda automatically publishes metrics to CloudWatch, such as:
      • Invocations
      • Duration
      • Errors
      • Throttles
  3. X-Ray:
    • AWS X-Ray helps trace requests through the Lambda function and visualize performance bottlenecks and errors.
  4. Dead Letter Queue (DLQ):
    • Configures a destination (SQS, SNS) for failed Lambda invocations to capture errors for later analysis.

Common Interview Questions

  1. How does AWS Lambda handle scaling?
    • AWS Lambda automatically scales horizontally, creating additional instances to handle more traffic. It automatically adjusts to the volume of incoming events.
  2. What is a “cold start” and how can you minimize it?
    • A cold start occurs when a Lambda function is invoked for the first time or after scaling, leading to a longer response time as AWS initializes the runtime environment.
    • Minimize by using provisioned concurrency, optimizing the function code, and reducing package size.
  3. What are the differences between “Provisioned Concurrency” and “Reserved Concurrency”?
    • Provisioned Concurrency pre-warms a set number of Lambda instances to ensure low-latency execution.
    • Reserved Concurrency limits the maximum number of concurrent executions for a function, helping control resource usage and avoid resource exhaustion.
  4. How do you handle Lambda function errors?
    • Use error handling (try-catch) within the function code.
    • Utilize Dead Letter Queues (DLQs) for failed invocations.
    • Leverage Amazon CloudWatch for error monitoring and diagnostics.
  5. Can a Lambda function access resources in a VPC?
    • Yes, Lambda can access resources within a VPC by configuring the function’s VPC settings (subnets, security groups).

Advanced Topics

  1. Lambda Destinations:
    • A feature for asynchronously invoked Lambda functions to send the results to destinations such as SQS, SNS, Lambda, and EventBridge.
  2. Lambda with Step Functions:
    • AWS Step Functions can orchestrate multiple Lambda invocations to create complex workflows, handle retries, and implement state management.
  3. Custom Runtimes:
    • Lambda allows creating custom runtimes if your language is not natively supported. You need to provide an HTTP-based API for the Lambda service to invoke your runtime.

This cheat sheet should give you a good foundation for AWS Lambda-related interview questions and provide practical insights into Lambda’s capabilities.

Leave a Reply