AWS LAMBDA INTERVIEW QUESTION-Set 1

Q: What is serverless computing?
  • Serverless computing is a cloud-computing execution model in which the cloud provider runs the server, and dynamically manages the allocation of machine resources.
  • It allows us to build and run applications and services without thinking about servers.
  • With serverless computing, our application still runs on servers, but all the server management is done by AWS.
  • That is why it became important for all projects or companies.
  • AWS Lambda is core of this serverless computing. We can run our code without servers.
Q: What is AWS Lambda?
  • AWS Lambda is a compute service where we can upload our code and create a Lambda function.
  • AWS Lambda takes care of provisioning and managing the servers that we use to run the code.
  • We don’t have to worry about operating systems, patching, scaling, etc.
  • Basically, we can run code without provisioning or managing servers with help of AWS Lambda.
  • We must pay only for the compute time.
  • There is no charge when our code is not running.
  • With Lambda, we can run code for virtually any type of application or backend service – all with zero administration. Just upload your code and Lambda takes care of everything.

We can use Lambda in the following ways;

  • As an event-driven compute service where AWS Lambda runs our code in response to events.
  • These events could be changes to data in an Amazon S3 bucket or DynamoDB table.
  • As a compute service to run your code in response to HTTP requests using Amazon API Gateway or API calls made using AWS SDKs.

What does AWS Lambda mean and how it is different from other AWS services?

  • AWS Lambda is one of the best computing services in the market, which is serverless.
  • It allows you to run codes without the help of managing servers or provisioning, means users do not need to worry about its backend provisioning or managing servers.
  • You have to pay for the computing time when you consume data while processing data.
  • There are no charges to be paid when you are not running your code.
  • Using Lambda, you can quickly run codes for any application or backend service virtually, without any administration.
  • You have to upload the code and rest everything is taken care of by Lambda.
  • Lambda runs and scales your code with high availability.
  • You can even set the code up to trigger from the other AWS available or give it a call directly from the mobile app or any web.

What is the time limit for execution in Lambda when you perform DDOS?

  • The time limit is 15 minutes.

There are some of the very complex querying capabilities that need to be handled without having a warehouse? Which database do you consider during such a case?

  • The Amazon RDS is a good option as others such as ElasticCache suffer from some issues.

What are the best practices for security in Lambda?

  • For security, there are some of the best options available in Lambda.
  • One can use Identity Access and Management. This would be beneficial when it comes to controlling access to resources.
  • Privilege is another option that basically opens up the permissions.

What is elastic blockage storage in Lambda?

  • It is basically a virtual storage area network where tasks can be started. It can tolerate faults easily and users need not worry about the loss of data even in case the disk damages in the RAID.
  • Provisioning and allocating the storage can also be done in Elastic Block Storage.

Give a simple method to improve performance in AWS Lambda?

  • This can be done simply by using the Linux software RAID. Also, better security can simply be assured.

If you are going to use AWS Lambda in your project then what restrictions will you apply to AWS Lambda function code?

  • First of all, AWS Lambda imposes very few restrictions on operating system activities and standard language.
  • However, there are few of the activities that have been disabled like for instance, inbound network connections and trace calls, which is a debugging system, and TCP port 25 traffic as a measure to anti-spam.

How long can an AWS Lambda function execute?

  • The complete execution has to take place within 15mins from placing the calls to AWS Lambda.
  • 3 seconds is the default timeout.

If you are using AWS Lambda in your banking project then How will AWS Lambda secure your code?

  • What Lambda does is, it stores the code in the Amazon S3 and encrypts it when it is resting.
Which all languages are supported by AWS Lambda?
  • Lambda supports the codes that are written in Python, C# (.NET Core), Node.js (JavaScript), Java (Java 8 compatible), powershell and Go. The code can also include existing libraries and even the native ones.

Is the infrastructure accessible on which the AWS Lambda runs?

  • No.

Is vertical scaling possible in Lambda?

  • Yes, it’s possible.
  • Basically, it is considered when you need to spin a larger instance.

What is SQS in Lambda? What role does it play?

  • SQS is basically nothing but an approach used for information sharing and passing among the different hosts and connectors.
  • Different components of Lambda can be made accessible or in other words, communication can be made possible in them.

What are the use cases for which Lambda was actually designed?

  • The overall response to the clicks made on the website, Image uploading, Sensor’s reacting monitoring, as well as reading from the IoT devices are some of the use cases of AWS Lambda.

Can I use packages with AWS Lambda?

  • Absolutely yes!
Question: Which of the following distinguishes the AWS API Gateway versus directly calling an AWS Lambda function?

Ans – API throttling

AWS _ is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you.

Ans:-Lambda

Which AWS services support Parameter Store?
  • CloudFormation, Lambda and EC2 (amongst others) all natively support the Systems Manager Parameter Store.
  • AWS Systems Manager Parameter Store provides secure, hierarchical storage for configuration data and secrets management.

You are working as AWS Engineer in your project and
You got service ticket from Client and you noticed that data events for Lambda and S3 are not available in Amazon CloudWatch Events. What could be the reason for this?

  • Step 1: You have to check whether your Lambda function and S3 resources have been added to a CloudTrail trail or not.
  • Step 2: Data events are not logged by default.
  • Data events provide visibility into the resource operations performed on or within a resource.
  • Data events are not logged by default when you create a trail. To record CloudTrail data events, you must explicitly add the supported resources or resource types for which you want to collect activity to a trail.
You would like to run a Lambda function at the same time every night. How will you do this?

We can create rules that self-trigger on an automated schedule in CloudWatch Events using cron.

Q: When should I use AWS Lambda versus Amazon EC2?
  • Amazon EC2 offers flexibility, with a wide range of instance types and the option to customize the operating system, network and security settings, and the entire software stack, allowing you to easily move existing applications to the cloud.
  • With Amazon EC2 you are responsible for provisioning capacity, monitoring fleet health and performance, and designing for fault tolerance and scalability. 
    • Where AWS Lambda makes it easy to execute code in response to events, such as changes to Amazon S3 buckets, updates to an Amazon DynamoDB table, or custom events generated by your applications or devices.
    • With Lambda we do not have to provision our instances; Lambda performs all the operational and administrative activities on our behalf, including capacity provisioning, monitoring fleet health, applying security patches to the underlying compute resources, deploying your code, running a web service front end, and monitoring and logging your code.
Question: In which web application tier would the AWS API Gateway reside?

Ans – Logic tier

What Languages Does Lambda Support?

Node.js

Java

python

GO

PowerShell

Why Is Lambda good?

NO SERVERS!

Continuous Scaling

As we came to know that AWS Lambda is a serverless computing platform that allows us to create a small function.

  • After creating function, we can configure the function in the AWS console.
  • Once it is configured then can execute code without the need to provision servers and can pay only for the resources used during the execution.
  • As many organizations move towards implementing serverless architectures, AWS Lambda will play big role in future.
  • To understand how to write a Lambda function, we should understand what goes into one.
  • A Lambda function has a few requirements.
  • The first requirement
    • we need to satisfy is to provide a handler.
    • The handler is the entry point for the Lambda.
    • A Lambda function accepts JSON-formatted input and will usually return the same.
  • The second requirement is
    • that we need to specify the runtime environment for the Lambda.
    • The runtime will usually correlate directly with the language that we have selected to write function.
  • The final requirement is a trigger.
    • We can configure a Lambda request in response to an event, such as a new file uploaded to S3, or a similar AWS event.
    • You can also configure the Lambda to respond to requests to AWS API Gateway, or based on a timer triggered by AWS Cloudwatch.

Use Case: We will understand Lambda concept through simple use case.

Let’s pass two numbers into the function, and have it return the sum, product, difference, and quotient of the two numbers.

Input

{

   “Number1”: 20,

   “Number2”: 10

}

 Response:

{
   "Number1": 20,
   "Number2": 10,
   "Sum": 30,
   "Product": 200,
   "Difference": -10,
   "Quotient": 1
}
Writing Your Lambda function with Python
  • Step 1: Log in to your AWS Account, and navigate to the Lambda console.
  • Step 2: Click on Create function.
  • Step 3: We’ll be creating a Lambda from scratch, so select the Author from scratch option.
  • Enter name for your Lambda function, select a Python runtime and define a role for your Lambda to use.

  • Step 4: click on the Create function button. Next we can see below screen:
  • Click on the Select a test event drop-down and choose Configure test events.
  • Click on Test  button.
  • Step 5: Amazon provides collection of test templates. Select Create new test event and provide Event name as our EventName i.e. validatetwonumber.
  • Now We will modify the Hello World template with data of our own.

  • click on Create to create the new test event.
  • Step 6: We can modify code as per our need. So I have changed it as below:
import json

def lambda_handler(event, context):

   number1 = event[‘Number1’]

   number2 = event[‘Number2’]

   sum = number1 + number2

   product = number1 * number2

   difference = abs(number1 – number2)

   quotient = number1 / number2

   return {

       “Number1”: number1,

       “Number2”: number2,

       “Sum”: sum,

       “Product”: product,

       “Difference”: difference,

       “Quotient”: quotient

   }
  • Same I have kept in lambda function.
  • Save it.
  • Now click on Test Button to execute.


  • After execution we can see Results as below:
  • This is an example through which we can understand Lambda function and its uses.

Important Points:

  • • Lambda scales out (not up) automatically
  • • Lambda functions are independent, 1 event = 1 function
  • • Lambda is serverless
  • Lambda functions can trigger other lambda functions, 1 event can = x
  • functions if functions trigger other functions
Boto3 and Lambda functions using Python

As per Boto 3 documentation,Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3. Boto provides an easy to use, object-oriented API, as well as low-level access to AWS services.

First create IAM role having programmatic access:

How to create an ec2 instance using boto3?
import boto3
client = boto3.client('ec2')

resp = client.run_instances(ImageId='ami-4652ca39',
                     InstanceType='t2.micro',
                     MinCount=1,
                     MaxCount=1)
for instance in resp['Instances']:
    print(instance['InstanceId'])
How to start EC2 instance through boto3?
import boto3
client = boto3.client('ec2')
client.start_instances(InstanceIds=['i-dfghjkghjvbn6788'])

Do the AWS Lambda-based functions stay available when code or its configuration is changed?

  • Yes. When a Lambda function is updated, there shall be a brief period, less than a minute, when requests can be served by either the old or the new version of the function.

Is there any limit to the quantity of AWS Lambda functions that can be executed at once?

  • No. The AWS Lambda is designed so that it can run some instances of functions simultaneously. However, AWS Lambda has a by default safety threshold for some consecutive runs for every account per region.

What happens when my account surpasses the default threshold limit on the executions?

  • Upon exceeding the threshold limit, the AWS Lambda functions are being called synchronously and will return a threshold error (429 error- code).
  • The tasks of Lambda functions that are called asynchronously shall absorb the reasonable traffic bursts for 15-30 minutes, after which the incoming events shall be rejected as they are throttled.
  • In case the Lambda function is being called in response to the Amazon S3 events, events that are rejected by AWS Lambda may be retained back and retried by S3 for 24 hours.
  • The events coming from streams of Amazon Kinesis and Amazon DynamoDB are retried along as the Lambda function doesn’t succeed, or the data doesn’t expire.
  • Amazon Kinesis and Amazon DynamoDB Streams hold the data for 24 hours.
How to stop EC2 instance through boto3?
import boto3
client = boto3.client('ec2')
client.stop_instances(InstanceIds=['i-dfghjkghjvbn6788'])

How to terminate EC2 instance?

import boto3
client = boto3.client('ec2')

resp = client.terminate_instances(InstanceIds=['i-0158ab7a03bb6a954'])

for instance in resp['TerminatingInstances']:
    print("The instance with id {} Terminated".format(instance['InstanceId']))

How will you describe EC2 instances?
import boto3

client = boto3.client('ec2')

resp = client.describe_instances(Filters=[{
    'Name': 'tag:Env',
    'Values': ['Prod']
}])

for reservation in resp['Reservations']:
    for instance in reservation['Instances']:
        print("InstanceId is {} ".format(instance['InstanceId']))
How will you use filter while describing EC2 instance?
import boto3

client = boto3.client('ec2')

resp = client.describe_instances(Filters=[{
    'Name': 'tag:Env',
    'Values': ['Prod']
}])

for reservation in resp['Reservations']:
    for instance in reservation['Instances']:
        print("InstanceId is {} ".format(instance['InstanceId']))

it will give you ec2 instances which match filter conditions.

How will you stop all running instances using Boto 3?
import boto3

client = boto3.client('ec2')

resp = client.describe_instances(Filters=[{
    'Name': 'instance-state-name',
    'Values': ['running']
}]).stop()
How will you find out instance type and Instance ids for all EC2 instances?
import boto3

ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
    print('Instance id is {} and Instance type is {}'.format(instance.instance_id,instance.instance_type))))
How will you find out instance type and Instance ids for all EC2 instances available in any specific zone?
import boto3

ec2 = boto3.resource('ec2')
for instance in ec2.instances.filter(Filters=[
{
'Name':'availbility-zone',
'value':['us-east-1d']
}
]):

    print('Instance id is {} and Instance type is {}'.format(instance.instance_id,instance.instance_type))))
How will you find out those instances which has tag as backup?
How will you delete EBS Snapshots which is older than 15days?
from datetime import datetime, timedelta, timezone

import boto3
ec2 = boto3.resource('ec2')

# List(ec2.Snapshot)
snapshots1 = ec2.snapshots.filter(OwnerIds=['self'])

for snapshot in snapshots1:
    start_time = snapshot.start_time
    delete_time = datetime.now(tz=timezone.utc) - timedelta(days=15)
    if delete_time > start_time:
        snapshot.delete()
        print('Snapshot with Id = {} is deleted '.format(snapshot.snapshot_id))
How will you Migrate AMIs To different regions using Boto3 ?
import boto3

##########################
## Part-1 Create Images ##
##########################

west_region = 'ap-west-1'
ec2 = boto3.resource('ec2', region_name=west_region)


instances = ec2.instances.filter(InstanceIds=['i-0067eeaab6c81c'])

image_ids = []

for instance in instances:
    image = instance.create_image(Name='Demo Boto - '+instance.id, Description='Demo Boto'+instance.id)
    image_ids.append(image.id)

print("Images to be copied {} ".format(image_ids))


#############################################
## Part-2 Wait For Images to be available  ##
#############################################
# Get waiter for image_available

client = boto3.client('ec2', region_name=west_region)
waiter = client.get_waiter('image_available')

# Wait for Images to be ready
waiter.wait(Filters=[{
    'Name': 'image-id',
    'Values': image_ids
}])

##########################################
## Part-3 Copy Images to other regions  ##
##########################################

# Copy Images to the region, us-east-1

destination_region = 'us-east-1'
client = boto3.client('ec2', region_name=destination_region)
for image_id in image_ids:
    client.copy_image(Name='Boto3 Copy'+image_id, SourceImageId=image_id, SourceRegion='ap-south-1')



What are the factors that decide how AWS Lambda is charged?

  • You are charged based on the amount of time it takes for your code to execute is dependent on the number of requests for your functions and the duration.

Question: What must be configured with a Lambda function to enable Lambda edge?

Ans – CloudFront trigger

What can trigger an execution of the Lambda function?

This is a list of services invoking asynchronous functioning of Lambda
• Amazon Simple Storage Service
• Amazon Simple Notification Service
• Amazon Simple Email Service
• AWS CloudFormation
• Amazon CloudWatch Logs
• Amazon CloudWatch Events
• AWS CodeCommit
• AWS Config

Question: Which types of CloudFront CDNs can be deployed?

Ans – Web

RTMP

What events can trigger an AWS Lambda function?

  • Lambda-based applications are composed of functions triggered by events.
  • A standard serverless application consists of one or more functions triggered by events such as object uploads to Amazon S3, Amazon SNS notifications, or API actions.