Mastering AWS Lambda - Yohan Wadia - E-Book

Mastering AWS Lambda E-Book

Yohan Wadia

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build cost-effective and highly scalable Serverless applications using AWS Lambda.

About This Book

  • Leverage AWS Lambda to significantly lower your infrastructure costs and deploy out massively scalable, event-driven systems and applications
  • Learn how to design and build Lambda functions using real-world examples and implementation scenarios
  • Explore the Serverless ecosystem with a variety of toolsets and AWS services including DynamoDB, API Gateway, and much more!

Who This Book Is For

If you are a Cloud administrator and/or developer who wishes to explore, learn, and leverage AWS Lambda to design, build, and deploy Serverless applications in the cloud, then this is the book for you! The book assumes you have some prior knowledge and hands-on experience with AWS core services such as EC2, IAM, S3, along with the knowledge to work with any popular programming language such as Node.Js, Java, C#, and so on.

What You Will Learn

  • Understand the hype, significance, and business benefits of Serverless computing and applications
  • Plunge into the Serverless world of AWS Lambda and master its core components and how it works
  • Find out how to effectively and efficiently design, develop, and test Lambda functions using Node.js, along with some keen coding insights and best practices
  • Explore best practices to effectively monitor and troubleshoot Serverless applications using AWS CloudWatch and other third-party services in the form of Datadog and Loggly
  • Quickly design and develop Serverless applications by leveraging AWS Lambda, DynamoDB, and API Gateway using the Serverless Application Framework (SAF) and other AWS services such as Step Functions
  • Explore a rich variety of real-world Serverless use cases with Lambda and see how you can apply it to your environments

In Detail

AWS is recognized as one of the biggest market leaders for cloud computing and why not? It has evolved a lot since the time it started out by providing just basic services such as EC2 and S3 and today; they go all the way from IoT to Machine Learning, Image recognition, Chatbot Frameworks, and much more! One of those recent services that is also gaining a lot of traction is AWS Lambda! Although seemingly simple and easy to use, Lambda is a highly effective and scalable compute service that provides developers with a powerful platform to design and develop Serverless event-driven systems and applications.

The book begins with a high-level introduction into the world of Serverless computing and its advantages and use cases, followed by a deep dive into AWS Lambda! You'll learn what services AWS Lambda provides to developers; how to design, write, and test Lambda functions; as well as monitor and troubleshoot them. The book is designed and accompanied with a vast variety of real-world examples, use cases, and code samples that will enable you to get started on your Serverless applications quickly.

By the end of the book, you will have gained all the skills required to work with AWS Lambda services!

Style and approach

This step-by-step guide will help you build Serverless applications and run Serverless workloads using the AWS Lambda service. You'll be able to get started with it in a matter of minutes with easy-to-follow code snippets and examples.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 315

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering AWS Lambda

 

 

 

 

 

 

 

 

 

 

 

 

 

Learn how to build and deploy serverless applications

 

 

 

 

 

 

 

 

 

 

 

 

Yohan Wadia
Udita Gupta

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

 

Mastering AWS Lambda

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: August 2017

 

Production reference: 1100817

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78646-769-0

 

www.packtpub.com

Credits

Authors

 

Yohan Wadia

Udita Gupta

Copy Editors

 

Juliana Nair

Stuti Srivastava

Reviewer

 

Legorie Rajan

Project Coordinator

 

Virginia Dias

Commissioning Editor

 

Kartikey Pandey

Proofreader

 

Safis Editing

Acquisition Editor

 

Heramb Bhavsar

Indexer

 

Tejal Daruwale Soni

Content Development Editor

 

Sharon Raj

Graphics

 

Kirk D'Penha

Technical Editor

 

Khushbu Sutar

Production Coordinator

 

Aparna Bhagat

About the Authors

YohanWadia is a client-focused evangelist and technologist with more than 7 years' experience in the cloud industry, primarily focused on helping customers succeed with the cloud. As a technical consultant for one of the world's leading IT companies, Yohan provides guidance and implementation services to customers looking to leverage cloud computing through either Amazon Web Services, Windows Azure, or Google Cloud Platform, helping them come up with pragmatic solutions that make practical as well as business sense. Yohan is also an avid blogger and the author of two successful books:

Learning VMware vCloud Air

--2015

Administering AWS: The Definitive Guide

--2016

He loves speaking about, blogging about, and training people on cloud platforms and technologies.

I wish to start off by dedicating yet another book to my small and crazy family...Ma, Pa, Sister, and Fred! Thank you for all your love, support, and encouragement. I would also like to thank the entire Packt Publishing team for giving me yet another wonderful opportunity, especially Sharon Raj (for the constant follow-ups and pushes to complete the chapters on time...I know I gave him a really tough time on this) and Heramb Bhavsar (for all the help and support with my books payments! Yeah, can't forget that now, can I?). Not to forget my bestie and biggest competitor, Mitesh Soni. Thank you for being a role model whom I can look up to! PS: I think it's high time we wrote a book together as well. And finally, special thanks and shout out goes to Udita as well. This book would have been a lot emptier if it weren't for your code! Really appreciate all the effort and work you put into this. All we have to decide is what to do with the time that is given to us. - J. R. R. Tolkien

Udita Gupta is an experienced cloud engineer with a passion for developing customized solutions, especially on the Amazon Web Services Cloud platform. She loves developing and exploring new technologies and designing reusable components and solutions around them. She particularly likes using the serverless paradigm, along with other upcoming technologies such as IoT and AI. A highly animated creature and an avid reader, Udita likes to spend her time reading all kinds of books, with a particular interest in Sheryl Sandberg and Khaled Hosseini. She is also an AWS Certified Solutions Architect.

First and foremost, I would like to dedicate this book to my family my parents and my dear sister. I wouldn't have taken up writing this book without their love and support. I would also like to thank the entire team at Packt for giving me this opportunity and guiding me through the entire authoring process. I also wish to thank the technical reviewers for their effort, time, and keen suggestions and recommendations. It is your effort that makes this book complete! We couldn't have done it without you! Last but definitely not least, I'd like to thank the entire AWS community for their help, support, and insights, that were invaluable to us when writing this book.

About the Reviewer

Legorie Rajan is a cloud consultant working with enterprise customers in the banking and insurance domains. His love for computers drove him to pursue a degree in CS, and he has not looked back since. He started his career as a mainframe developer and is currently migrating and architecting solutions on the cloud. His love for new technologies has never ceased, and he uses his spare time to hack around Node.js, Mongo, and Kubernetes. He has a BTech(CS) degree from Pondicherry University and an MS in management from Grenoble School of Business.

I would like to thank my wife, Anitha Sophie, for being my rock, and the team at Packt for the opportunity.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1786467690.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

Introducing AWS Lambda

What is serverless computing?

Pros and cons of serverless computing

Introducing AWS Lambda

How it works

Getting started with AWS Lambda

Using the AWS Management Console

Using the CLI

Pricing and limitations

Planning your next steps

Summary

Writing Lambda Functions

The Lambda programming model

Handler

The context object

Logging

Exceptions and error handling

Versioning and aliases

Environment variables

Packaging and deploying

APEX

Claudia.js

Recommendations and best practices

Planning your next steps

Summary

Testing Lambda Functions

The need for testing Lambda function

Manually testing your functions with the AWS Management Console

Testing functions with Mocha and Chai

Testing functions using the npm modules

Testing with a simple serverless test harness

Recommendations and best practices

Planning your next steps

Summary

Event-Driven Model

Introducing event-driven architectures

Understanding events and AWS Lambda

Lambda architecture patterns

Exploring Lambda and event mapping

Mapping Lambda with S3

Mapping Lambda with DynamoDB

Mapping Lambda with SNS

Mapping Lambda with CloudWatch events

Mapping Lambda with Kinesis

Creating the Kinesis Stream

Setting up the log streaming

Packaging and uploading the function

Planning your next steps

Summary

Extending AWS Lambda with External Services

Introducing Webhooks

Integrating GitHub with AWS Lambda

Integrating Slack with AWS Lambda

Invoking Lambda using an external application

Planning your next steps

Recommendations and best practices

Summary

Build and Deploy Serverless Applications with AWS Lambda

Introducing SAM

Writing SAM templates

AWS::Serverless::Function

AWS::Serverless::Api

AWS::Serverless::SimpleTable

Building serverless applications with SAM

Introducing AWS step functions

Under the hood

Getting started with step functions

Building distributed applications with step functions

Planning your next steps

Summary

Monitoring and Troubleshooting AWS Lambda

Monitoring Lambda functions using CloudWatch

Introducing AWS X-Ray

Monitoring Lambda functions using Datadog

Logging your functions with Loggly

Recommendations and best practices

Summary

Introducing the Serverless Application Framework

What is the Serverless Framework?

Getting started with the Serverless Framework

Working with the Serverless Framework

Recommendations and best practices

Summary

AWS Lambda - Use Cases

Infrastructure management

Scheduled startup and shutdown of instances

Periodic snapshots of EBS volumes using Lambda

Enabling governance using EC2 tags and Lambda

Data transformation

Summary

Next Steps with AWS Lambda

Processing content at the edge with Lambda@Edge

Building next generation chatbots with Lambda and Lex

Processing data at the edge with Greengrass and Lambda

Introducing Snowball Edge

Summary

Preface

AWS is recognized as one of the market leaders for cloud computing, and why not? It has evolved a lot since it started out providing basic services such as EC2 and S3. Compare that to today: they go all the way from IoT to machine learning, image recognition, chatbot frameworks, and much more! One of these recent services that is also gaining a lot of traction is AWS Lambda. Although seemingly simple and easy to use, Lambda is a highly effective and scalable compute service that provides developers with a powerful platform to design and develop serverless event-driven systems and applications.

The book begins with a high-level introduction to the world of serverless computing and its advantages and use cases, followed by a deep dive into AWS Lambda. You'll learn what services AWS Lambda provides to developers; how to design, write, and test Lambda functions; as well as how to monitor and troubleshoot them. The book is accompanied by a vast variety of real-world examples, use cases, and code samples that will enable you to quickly get started on your journey toward serverless applications.

By the end of the book, you will have gained all the skills required to work with and master AWS Lambda services!

What this book covers

Chapter 1, Introducing AWS Lambda, covers the introductory concepts and general benefits of serverless computing, along with an in-depth look at AWS Lambda. The chapter also walks you through your first steps with AWS Lambda, including deploying your first functions using the AWS Management Console and the AWS CLI.

Chapter 2, Writing Lambda Functions, covers the fundamentals of writing and composing your Lambda functions. The chapter introduces you to concepts such as versioning, aliases, and variables, along with an easy-to-follow code sample.

Chapter 3, Testing Lambda Functions, discusses the overall importance of testing your function for code defects and bugs. It also introduces you to some out-of-the-box testing frameworks in the form of Mocha and Chai, and summarizes it all by demonstrating how you can test your functions locally before actual deployments to Lambda.

Chapter 4, Event-Driven Model, introduces the concept of the event-based system and how it actually works. The chapter also provides a deep dive into how Lambda's event-based model works with the help of event mappings and a few easy-to-replicate, real-world use cases.

Chapter 5, Extending AWS Lambda with External Services, discusses the concept and importance of Webhooks and how they can be leveraged to connect your serverless functions with any third-party services. The chapter also provides a few real-world use cases, where Lambda functions are integrated with other services such as Teamwork, GitHub, and Slack.

Chapter 6, Build and Deploy Serverless Applications with AWS Lambda, provides you with a hands-on approach to building scalable serverless applications using AWS services such as SAM and Step Functions with a few handy deployment examples.

Chapter 7, Monitoring and Troubleshooting AWS Lambda, covers how you can leverage AWS CloudWatch and X-ray to monitor your serverless applications. The chapter also introduces other third-party tools, such as Datadog and Loggly, for effectively logging and monitoring your functions.

Chapter 8, Introducing the Serverless Application Framework, provides a brief introduction and outlines the benefits provided by the Serverless Framework, followed by some hands-on implementation and deployment of functions using it.

Chapter 9, AWS Lambda - Use Cases, provides a comprehensive set of real-world serverless use cases with some easy-to-follow code examples and snippets.

Chapter 10, Next Steps with AWS Lambda, summarizes the next phase in the evolution of serverless applications and discusses how new and improved enhancements in Lambda are expected to come about in the near future.

What you need for this book

To start using this book, you will need the following set of software installed on your local desktop:

An SSH client such as PuTTY, a key generator such as PuTTYgen, and a file transferring tool such as WinSCP

You can alternatively even set up your own development/sandbox server on Linux using VirtualBox

Any modern web browser, preferably Mozilla Firefox

Who this book is for

This book is intended for any and all IT professionals and developers who wish to learn and implement the ins and outs of serverless computing using AWS Lambda. Although no prior experience or knowledge is required, it will be beneficial for you to have at least a basic development background--preferably with Java or Node.js--hands-on Linux knowledge, as well as some understanding of AWS's core services, such as IAM, EC2, and VPCs.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support, and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-AWS-Lambda. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringAWSLambda_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support, and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Introducing AWS Lambda

I still remember the days when there was a clear demarcation between IT developers and system administrators; so much so that, each time a developer wanted a simple software platform or environment to be set up on their workstations, they would have to log one or more change requests, then dubiously wait for an IT admin to come along, who would more often than not provide you with an incorrect version of the software that you requested. Basically, you would end up wasting a week's effort just to get some simple software like Java or Tomcat to be setup, right? Many of us have sometime or the other been through this so called vicious cycle in IT and some still do, even today. But what if I told you that there is some ray of light around the corner! What if you, as a developer had the flexibility to simply write your code and put it up for execution; without having to worry about the underlying software platform, the OS or the hardware on which your code will run? Sounds too good to be true? Well fret no more, because that is what this book is all about! How you, as a developer start leveraging certain cloud-based services to develop, test, and host applications without having to even manage anything! Welcome to the amazing world of serverless computing!

In this chapter, we are going to get an understanding of the following topics:

What serverless computing is, along with its pros and cons

Introduction of AWS Lambda as a service and how it works

Getting started with AWS Lambda using the AWS Management Console, as well as the CLI

Pricing and a few of Lambda's limitations

So, without further ado, let's get started!

What is serverless computing?

To understand what serverless computing is all about and how it came to be, we first need to travel back in time to the era of mainframes and traditional data centers! Sounds like a long-lost time, right? Don't worry, we are not going that far back. This is probably in the time when most IT organizations had massive in-house data centers for hosting almost all enterprise applications and services. First, these applications were hosted directly on physical servers, and then eventually migrated onto the virtualized environments that provided a better utilization of resources as well as helped to slash down the overall costs and time for deployments from months to days. With the advent of the virtualization era, we also started to develop and use more convenient deployment tools that helped to deploy our applications with more ease, but it still meant managing the application's underlying operating system, software platform, and so on:

With virtualization clearly not having all the answers, we started looking for a much simpler application deployment model and, in return, found Containers. Unlike their earlier counterparts, Virtual Machines, Containers don't require a lot of resources or overhead to run. They are far easier and quicker to deploy, hence, reduce the overall application deployment time from days to minutes! You could now easily roll out a new patch for your application, scale your application dynamically based on incoming requests, and even orchestrate various other functions using a vast variety of container management products. However, the question of managing the Containers still remains, and trust me, managing a fleet of thousands of Containers and their underlying physical servers is no easy task. A better, more efficient, deployment model was needed; something that provided us with the agility and flexibility of containers, but without all the hassle and trouble of managing them. Enter serverless computing!

Serverless computing is all about running your application code on small ingots of some CPU and memory without having to worry about the OS type, the software platform, or any of the underlying hardware either. Just take your code and run it! Yes! It's that simple! Serverless computing today is offered by most public cloud providers, such as Amazon Web Services, Google Cloud Platform, Microsoft Azure, and even by IBM as a managed service. This essentially means that all you need to do is write your code or functions that perform a very specific task, select the quantity of resources (in this case RAM) required to run your code and submit it to the serverless cloud computing service to execute on. The service makes sure that your code gets the required amount of memory and CPU cycles it needs to execute. Hence, the collective term Function as a Service (FaaS).

Pros and cons of serverless computing

Here is a quick look at some of the key benefits that you, as a developer, can attain with the help of serverless computing:

No ware to manage

: Perhaps one of the biggest reasons for the hype about serverless computing is the fact there is absolutely no hardware or software to manage. The management of the serverless computing environment all the way from the underlying hardware to the OS, to even the application's platform layer, is managed by the cloud provider itself.

Faster execution time

: Unlike your standard cloud instances, which generally take a good minute or two to boot up, functions, on the other hand, spin up very quickly, mostly in a matter of seconds. This could be due to the fact that the functions are made to run on top of a containerized platform.

Really low costs

: Since there is virtually no opex involved with serverless computing, it is fairly cheap, even when compared to hosting and managing instances in the cloud. Also, the pricing model for serverless computing is a little different from that of your traditional cloud pricing model. Here, you are generally billed on the duration of your function's execution and the amount of memory it consumed during its execution period. The duration is calculated from the time your code begins executing until it returns or otherwise terminates and is rounded up to the nearest 100 ms.

Support of popular programming languages

: Most cloud providers that provide serverless computing frameworks today, support a variety of programming languages, such as Java, Node.js, Python, and even C#. 

Azure functions allows the use of F#, PHP, Bash, Batch and PowerShell scripts in addition to the few mentioned.

Microservices compatible

: Since serverless computing functions are small, independent chunks of code that are designed to perform a very specific set of roles or activities, they can be used as a delivery medium for microservices as well. This comes as a huge advantage as compared to hosting your monolithic applications on the cloud, which do not scale that effectively.

Event-driven applications

: Serverless functions are an ideal choice for designing and running event-driven applications that react to certain events and take some action against them. For example, an image upload operation to a cloud storage triggers a function that creates associated thumbnail images for the same.

Feeling excited already about giving serverless computing a try? Hold on! There are a few cons to serverless computing as well that you should be aware of before we proceed further:

Execution duration

: Serverless functions are designed to run for short durations of time, ideally somewhere under 300 seconds only. This is a hard limit set by most cloud providers, however, there are a few workarounds to this as well.

Stateless

: Serverless functions are purely stateless, which means that once the function completes its execution or is terminated for some reason, it won't store any data locally on its disk.

Complexity

: The smaller you make things, the more complex it's going to become. Although writing functions that perform very particular tasks is a good idea, it can cause complexity issues when you view your application as a whole system. A simple example can break one large application into some ten different functions such that each perform a specific task. Now you need to manage ten different entities rather than just one. Imagine if you had a thousand functions instead.

Lack of tools

: Although serverless computing is all at its hype, it still doesn't provide a lot of out-of-the-box tools for management, deployment, and even monitoring. Most of your monitoring tools that you use today were designed for long-running, complex applications; not for simple functions that execute in a mere seconds.

Vendor lock-in

: With each cloud provider providing its own unique tool sets and services around serverless computing, you often tend to get tied down to a particular vendor. This means that you cannot change your cloud provider without making some changes to your functions as well.

With these key points in mind, let us get to understanding and learning a bit more about the core serverless computing service that this book is all about--AWS Lambda.

Introducing AWS Lambda

So, here we are, finally to the fun part! In this section, we will learn what Lambda is actuallyall about, what some of its salient features are, how it works and some steps on getting started with your very first Lambda invocation.

AWS Lambda was first introduced way back in 2014, at the yearly AWS re:Invent conference in Las Vegas. The idea back then, and which pretty much holds true even today, is that Lambda is a simple compute service that runs your code in response to certain events. These events can be anything, from an upload operation of an object to an S3 bucket, a record insertion in a DynamoDB table, or even some form of event triggered from your mobile app. The idea here is simple--you simply provide your code to AWS Lambda. Lambda will internally take care of provisioning and managing the underlying infrastructure resources, making sure your code gets deployed successfully; even things like your code's scalability and high availability are taken care of by Lambda itself! Now, that's neat!

Source: https://aws.amazon.com/lambda/

Lambda was specially introduced by AWS to answer a very particular issue with EC2. Although EC2 still remains one of the most widely used core AWS services, it's still not designed to handle or respond to events; something that is required more often than not in today's applications. For example, a simple image upload activity to an S3 bucket triggers some form of operation, such as checking whether the object is actually a valid image, or whether it contains any viruses or unwanted malware. You can even have a requirement to create thumbnails of the uploaded image and put that up on your website. Now, imagine an EC2 instance doing all these activities for you. Firstly, you would have to program some mechanism for S3 to notify your EC2 instances to periodically perform checks on your S3 bucket, as EC2 has no way of telling when a new object has been uploaded.

Then again, you would have to manage the EC2 instance and handle all failovers, such as what happens if the EC2 instance fails to poll the S3 bucket, or what happens if the EC2 instance gets terminated for some reason. There's also the issue of scalability, right? Today you may be uploading just about 30-40 odd images, enough for a single EC2 instance to work on; but what happens when there is a large surge of upload operations? Will your EC2 instances scale effectively? And most important of all and by far the biggest issue for most enterprises--cost. Your EC2 instance will be running even on those days when there are no upload operations occurring in your S3 bucket. Sure there are many ways in which we can create workarounds for this, such as by creating a separate instance that polls continuously and by leveraging SQS or SNS as well, but isn't all that really overkill for something so simple? That's exactly the reason why Lambda is so popular and so widely used today. It just makes things simple!

How it works

Well, we do know for sure that Lambda powers your code on some form of container technology which explains how AWS is able to get it to spin up so quickly as compared to running your code on standard EC2 instances. These containers are spun up on underlying EC2 instances that are all created from a common image (Amazon Linux AMI: amzn-ami-hvm-2016.03.3.x86_64-gp2). Once again, we cannot control or see these containers or EC2 instances; they are managed by AWS itself.

There is a short latency between the time a Lambda function is invoked. This is primarily because AWS has to bootstrap the container that runs your code and provides the necessary resources for it to run as well. This latency is generally observed when the function is either invoked for the first time or when it is updated.

At the heart of the container is your code, which, as a rule of thumb, has to be written specifically to perform a single task or a few simple processes; similar to how you would write functions in your normal code. Each Lambda project that you deploy can thus be termed as a Lambda function, or just a function. At the time of writing this book, AWS supports Java, Python, Node.js, and even C# as programming languages for your functions. Each function can be invoked either on demand or invoked dynamically based on certain types of supported events. A few event examples are listed out as follows:

Amazon S3

: Lambda functions can be triggered when an object is created, updated, or deleted in an S3 bucket

Amazon DynamoDB

: Lambda functions are triggered when any updates are made to a particular DynamoDB table, such as row insertion, deletion, and so on

Amazon Simple Notification Service

(

SNS

): Trigger a Lambda function when a message is published on a, SNS topic

Amazon CloudWatch Logs

: Use Lambda functions to process CloudWatch Logs as feeds

Scheduled events

: Run Lambda functions as scheduled events, just like a

cron

job

AWS CodeCommit

: Execute Lambda functions whenever new code is pushed to an existing branch, and so on

For a complete list of the latest AWS services that are supported as Lambda invokers, refer to http://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html.

When creating Lambda functions, you have to specify the amount of memory resource your function will require, as well as the approximate time it will take to execute before timing out. The memory can be set from 128 MB to 1.5 GB of RAM and the timeouts anywhere from one second to a max of 300 seconds. Both the memory and duration values are upper limits to your Lambda function, which means that if you have allocated 512 MB of RAM to your function, it doesn't mean the function will have to use all 512 MB, of it. It can work at any value up to 512 MB post which Lambda will simply throw you an error message stating that your function ran out of memory. The same applies for the duration of your function as well. You may set your function to timeout after 60 seconds and the function may only run for, say, 10 seconds. However, if your function fails to complete its processing by the 60th second, Lambda once again will time it out and pop you up an error message.

It is important to note, however, that varying the amount of memory for your function or the duration of the timeout also impacts the cost of your Lambda function. We will have a look at Lambda's pricing and limitations a bit later on in this chapter. For now, let us learn a bit more on how to actually get started with deploying Lambda functions using the AWS Management Console, as well as the AWS CLI.

Getting started with AWS Lambda

In this section, we will look at how easy and effortless it is to execute a simple Lambda function using both the AWS Management Console, as well as the AWS CLI, and in the process learn a few necessary components and configurable items along the way.

Using the AWS Management Console

The AWS Management Console is by far the simplest way to getting started with AWS Lambda. Now I'm going to assume that you already have a valid AWS account and some basic hands-on knowledge with the core AWS services and products such as EC2, IAM, S3, and so on. If not, then you can always create a new account with AWS and leverage the awesome one-year Free Tier scheme as well.

To read more about Free Tier usage, check out this link here https://aws.amazon.com/free/.

The following are the steps to create a new Lambda function:

Log in to your AWS Management Console using your IAM credentials and from the

AWS Services

filter, type in

Lambda

to get started. You should see the AWS Lambda dashboard, as shown in the following screenshot.

Click on the 

Get Started Now

option to create a new Lambda function:

Creating a Lambda function is a straightforward four-step process and it begins with the selection of a function blueprint. Just the way we have AMIs for easy and fast deployments of EC2 instances, the same applies for a Lambda function as well. Blueprints are nothing more than sample code that you can use as starting points to writing your very own functions. AWS provides a cool 70-odd blueprints that you can select from, this can help you integrate S3, DynamoDB, and Kinesis with Lambda for to perform specific tasks. For this section, we are going to be using a very simple hello-world Lambda function blueprint from the catalog. We can do so by following the given steps:

First, simply type in the keyword

hello