0% found this document useful (0 votes)
20 views9 pages

Lambda Vs EC2

The document compares and contrasts implementing APIs using Amazon EC2 virtual machines versus AWS Lambda serverless computing. With EC2, the developer has full control over the virtual machine but must manage infrastructure like scaling and maintenance. Lambda automatically scales based on requests and removes the need for server provisioning, but functions must be stateless and handle individual requests.

Uploaded by

Annapoorani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views9 pages

Lambda Vs EC2

The document compares and contrasts implementing APIs using Amazon EC2 virtual machines versus AWS Lambda serverless computing. With EC2, the developer has full control over the virtual machine but must manage infrastructure like scaling and maintenance. Lambda automatically scales based on requests and removes the need for server provisioning, but functions must be stateless and handle individual requests.

Uploaded by

Annapoorani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

vs

Amazon EC2:
● EC2 provides virtual machines (instances) in the cloud, allowing us to run
applications on a variety of operating systems.
● We have full control over the virtual machine, including the choice of the
operating system, software installations, and configurations.
● When implementing APIs on EC2, we typically deploy our application on the EC2
instance and use a web server (e.g., Apache, Nginx) or a framework (e.g., Flask,
Express) to handle HTTP requests and serve the API.
● We need to manage the infrastructure, including scaling, load balancing, and
maintaining the operating system and software.

AWS Lambda:
● Lambda is a serverless computing service where we upload the code, and AWS
automatically manages the execution environment.
● We don't need to worry about server provisioning, scaling, or maintenance.
Lambda automatically scales our application based on the number of requests.
● In Lambda, we create functions that are triggered by events. WE can use API
Gateway to create an HTTP endpoint that triggers our Lambda function.
● Lambda function should be designed to handle individual requests, and it should
be stateless.

Implementation Examples:

Node.js API on EC2:

Setting up EC2:

● Launch an EC2 instance with the preferred operating system.


2
o

● Connect to the instance and install Node.js and npm.

Writing a Simple API using Express:

● Install Express and a data storage library (e.g., maongodb) using npm install
express mongodb.

Create a MongoDB database:

● Install MongoDB on our EC2 instance or use a cloud-based MongoDB


service.
● Create a file, controller files.

Run the API:

● Start the server by running node app.js.


● Access the API at http://<our-ec2-instance-ip>:3000/api/saveEntity using a tool like curl
or Postman to make a POST request with the entity data.

Node.js API on AWS Lambda:


​ Writing a Lambda Function:
● Create a file, e.g., lambda.js;
​ Package the Lambda Function:
● Zip the lambda.js file along with any dependencies (e.g., mongodb).
● Upload the zip file to AWS Lambda.
​ Setting up API Gateway:
● Create an API Gateway on AWS.
● Create a resource and a method (e.g., POST) in the API Gateway.
● Connect the method to the Lambda function.
​ Test the API:
● Once deployed, we can test the API using the provided URL by making a
POST request with the request data.
3
o

Important things to be noted:

MongoDB Connection:
● In the EC2 implementation, we connect directly to the MongoDB instance
running on the EC2 instance or another accessible server.
● In the Lambda implementation, we should consider using a cloud-based
MongoDB service like MongoDB Atlas, as Lambda functions are stateless
and may not maintain persistent connections.

Error Handling:

● Adjust error handling based on Lambda's asynchronous nature. We


should consider using promises or async/await consistently.

Dependency Management:

● Ensure that all dependencies are packaged along with our Lambda
function when deploying to AWS.

Lambda Integration with API Gateway:


​ AWS Lambda Function:
● Once the Lambda function is already created and deployed. Note down
the ARN (Amazon Resource Name) of Lambda function.
​ AWS API Gateway:
● Go to the AWS Management Console.
● Navigate to the API Gateway service.
​ Create a New API:
● Click on "Create API."
● Choose "HTTP API."
● Click on "Build" to create a new API.
​ Create a Resource:
● Under "Routes," click on "Add Integration."
4
o

● Choose "Lambda Function" as the integration type.


● Select our Lambda function from the list.
● Click "Create."
​ Define a New Resource and Method:
● Click on "Add Integration" under the "Routes" section.
● Choose a resource name (e.g., "user-access").
● Choose an HTTP method (e.g., POST).
● Click on "Create."
​ Deploy the API:
● Go to the "Deploy" tab.
● Choose a stage (e.g., "prod").
● Click on "Deploy."
​ Access the Endpoint URL:
● Once deployed, we will get an API Gateway endpoint URL. This URL is
where the Lambda function will be accessible through the API Gateway.

Testing:
​ Invoke the Lambda Function through API Gateway:
● Copy the API Gateway endpoint URL.
● Use a tool like curl, Postman, or a browser to send a POST request to the
API Gateway endpoint, providing the required payload.
​ Check Lambda Logs (Optional):
● In the AWS Lambda console, we can check the CloudWatch logs for our
Lambda function to see any logs or errors generated during the API
Gateway invocation.
​ View API Gateway Metrics (Optional):
● In the API Gateway console, we can view metrics and monitoring
information related to the performance of our API.

BE Structure:

● Src/: This directory contains source code.


5
o

● controllers/: Handles the business logic of our application. Each controller


can represent an endpoint or a set of related functionalities.
● models/: Contains the data models representing our application entities.
These models define the structure of data.
● validators/: Includes validation logic for incoming requests. This is where
we can define validation functions to ensure the integrity of data.
● errors/: Holds custom error classes or functions that help in handling and
responding to specific errors in a consistent manner.
● utils/: Houses utility functions that can be shared across different parts of
application.
● lambdaFunction.js: The entry point for the AWS Lambda function. This file
should handle the integration with API Gateway, parse incoming events,
and invoke the appropriate controller.
● package.json: Manages project's dependencies and scripts. We may include
AWS SDK, mongoose (if using MongoDB), and other necessary libraries here.
● serverless.yml: Defines our serverless architecture, including Lambda functions,
API Gateway configurations, and other AWS resources. Serverless Framework
uses this file to deploy applications.
● .env: Stores environment-specific configurations for local development.
● README.md: Documentation for project, including setup instructions, usage
guidelines, and any other relevant information.

Yml file Example:

service:

name: our-service-name

provider:

name: aws
6
o

runtime: nodejs14.x

region: our-aws-region

functions:

getUserAccess:

handler: functions/getprofile.lambdaHandler //example handler

events:

- http:

path: api/getProfile

method: post

cors: true

function2:

handler: functions/function2.lambdaHandler

# Add necessary events and configurations for function2

function3:

handler: functions/function3.lambdaHandler

# Add necessary events and configurations for function3


7
o

# ... Repeat the pattern for the remaining functions ...

function25:

handler: functions/function25.lambdaHandler

# Add necessary events and configurations for function25

plugins:

- serverless-webpack

package:

individually: true

Explanation:

● functions Section: Each Lambda function is defined with a unique name (e.g.,
getprofile, function2, ..., function25). Each function has its own handler property
pointing to the Lambda handler file.
● Lambda Handler Paths: The handler paths (functions/getUserAccess.lambdaHandler,
functions/function2.lambdaHandler, etc.) point to the file and exported handler for
each function. Ensure that the file paths are correct based on our project
structure.
● Configuration for Each Function: Inside each function block, we can add specific
configurations, events, and settings for that function. For instance, the events
section configures the API Gateway for the getUserAccess function.
● Repeat for Each Function: Repeat the pattern for each function.
8
o

The lambdaFunction.js file serves as the entry point for our AWS Lambda
function. It handles the integration with API Gateway, parses incoming events, and
invokes the appropriate controller. Below is a basic example of how might structure this
file will be:

const getUserAccessController = require('./src/controllers/userController');

exports.handler = async (event, context) => {


try {
// Extract relevant information from the event
const httpMethod = event.httpMethod;
const path = event.path;

// Log incoming event for debugging (optional)


console.log('Received event:', JSON.stringify(event, null, 2));

// Define routing logic based on HTTP method and path


if (httpMethod === 'POST' && path === '/api/getUserAccess') {
// Invoke the userController for POST requests to /api/getUserAccess
return await getUserAccessController(event, context);
} else {
// Handle unsupported routes or methods
return {
statusCode: 404,
body: JSON.stringify({ message: 'Not Found' }),
};
}
} catch (error) {
// Handle unexpected errors and return an appropriate response
console.error('Error:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Internal Server Error' }),
};
}
};
9
o

EC2 Implementation vs. Lambda Implementation:


● For EC2, we would set up an Express app on the server, handle routes, and
connect to MongoDB directly.
● For Lambda, we would create a Lambda function, integrate it with API Gateway,
and use event-driven programming.
● Lambda functions are stateless, so connections like MongoDB should be
managed carefully.

You might also like