AWS Lambda - Theory, Acquaintance

    A quick tour of AWS Lambda

    What is it?

    AWS Lambda: This is a computing service that allows you to run code for almost any type of application or server service - all without administration. AWS Lambda does all the administration for you, including server and operating system maintenance, resource allocation and automatic scaling, code monitoring and logging. All you have to do is submit your code in one of the languages ​​that AWS Lambda supports.

    Why use it?

    • Money. You pay only for the time when the service is running.
    • Speed. Lambda itself rises and works very fast.
    • Convenience. Lambda has many features for integrating with AWS services.
    • Performance. In parallel, it can be performed, depending on the region, from a maximum of 1000 to 3000 copies. And if you wish, this limit can be raised by writing in support.

    This approach has its drawbacks, you can not control the operating system on which the code is executed, you can not control the CPU, memory and resources. All this is done by AWS.

    All you can do is choose a language from the supported AWS Lambda.

    What can?

    The following is a brief list of the main features of AWS Lambda. Next, we will consider everything in order.

    1. Triggers

    Triggers are the “pathogens” of lambda. In a way, lambda can be compared with PHP, in the sense that for us it runs and dies . Next, we will consider in detail the mechanism of work. For now, you need to understand that lambda is one function that is executed on request from triggers.

    Below is a list of all possible triggers:

    API Gateway
    AWS IoT
    Alexa Skills Kit
    Alexa Smart Home
    Application Load Balancer
    CloudWatch Events
    CloudWatch Logs
    Cognito Sync Trigger

    For each of them, you will need to configure unique parameters that are available for these triggers. You can also configure multiple triggers on one lambda. It depends on the type of trigger whether the lambda will execute synchronously or asynchronously.
    Notice: Please note that the lambda can be made to execute either by using the AWS CLI, AWS SDK in manual mode, passing all the necessary parameters. Including whether it will run synchronously or not

    Let's look at an example:

    1. Gateway API - allows you to pull the lambda on the http request and requires that the result be returned to the user. Such an operation cannot be performed asynchronously, because requires an answer. For synchronous operations, some functions are not available.

    2. SQS - for example, if our lambda processes messages from SQS, you do not need to return the result anywhere and it can be performed asynchronously. With asynchronous execution, several new features appear, for example, we can configure repeated execution in case of an error, or send such requests further to the “dead” SQS queue .

    2. Permissions to AWS Services

    These are AWS services that lambda has default access to. What does it mean? You can always connect the AWS SDK to the function that you will write, and without the keys or any authorization parameters, you can use the available services. You define all available services in the IAM Role that you use for this lambda.

    Each language used has its own SDK that can communicate with the main AWS services.
    Notice: for each lambda you configure IAM Role from the person who will run the lambda

    3. VPC

    You can configure a virtual network for your lambda, for example, to securely connect to RDS .

    4. Online Editor

    AWS Lambda also provides the ability to edit the code of your function directly from the interface in your browser.

    5. Logging

    All requests for lambda are logged in CloudWatch , the data on runtime and memory are also recorded there, this data can be very useful for setting limits. Also, the code has the ability to log your own data (for example, in Node.js via console.log).

    Additionally, you can always see statistics on lambda usage on the Monitoring tab.

    6. Environment Variables

    You have the opportunity to transfer environment variables safely into code, which allows you to configure important parts of the system without delivering code. It is possible to encrypt environment variables through keys.
    Notice: Note that there is a list of predefined environment variables

    7. Code

    Now the most interesting part, the lambda itself consists of several parts.

    1. Layers - the bottom layer. It is not necessary, but if you need to add some libraries to use the lambda, then you need to put them separately from the main code, so you greatly save on the amount of main code and the speed of the function itself.

    Layers in AWS Lambda are somewhat similar to layers in docker , in that they are permanent with respect to a function, and they need to be changed separately. They can also be reused in other lambdas.

    2. Function Environment - the code must necessarily contain a function that will be directly executed each time the lambda (Handler) is launched. About her below. And in front of her is her environment, which we ask. The fact is that resource management occurs in such a way that this environment is stored separately from the function for some time after its completion. And at the next start, it resumes without spending time and resources on initialization. Thus, everything that is possible needs to be initialized to the function itself, for example, configuration, connecting libraries, etc.

    3. Handler - directly executed code itself, depending on the language, is defined differently. For example, take Node.Js. In order for your code to execute, you need:

    1. js file - 1pc
    2. exports.yourFunction = () => {// Your code} - 1pc

    By default, index.js is launched and looks for a function called “handler” in it. Then performs it. Your function may be asynchronous in code. This does not affect the synchronous execution of lambda.

    Below is a sample code, I will try to describe what happens there:

    //AWS SDK уже встроен, его не нужно загружать отдeльно
    var AWS = require('aws-sdk'); // только подключить
    //Все что вам нужно, лучше подключать здесь
    //Это пример с API Gateway. 
    //Если проще, то это обычный http запрос
    exports.handler = async(event, context) => {
    //В event нам приходит вся инфа о запросе
    //В context нам приходит текущий контекст aws lambda функции: 
    // почему была запущена, кем и прочая вспомогательная инфа
       console.log('testing cloud watch'); 
       // ^ Таким образом мы можем писать в Cloud Watch кастомные сообщения
       return { 
           //Таким образом мы отвечаем на http запрос, думаю ниже все понятно
           statusCode: 200,
           body: 'Hello world',
           headers: {}
    exports.handler = (event, context, callback) => {
        //Это второй вариант с callback,
        //в каких-то случаях это может быть удобнее
            null, //<- Первый параметр, это если вам нужно вернуть ошибку  
            { // Второй параметр это успешно
                statusCode: 200,
                body: 'Hello world'

    8. Versioning

    The service supports convenient versioning. In short, we can issue a version for each downloaded copy. And add aliases that point to some version. How it works? See the chart below.

    And so, now let's figure out what needs to be done to get what we see in the diagram

    State one

    1. Create the first version of our lambda. Together with the first version, we create a pointer to the version of "$ LATEST" . It always indicates the latest version added.
    2. Add the alias "Dev" . Here we choose where to bind, we have several options - create a pointer to a specific version number, in our case "1" , bind the pointer to "$ LATEST" , or bind to another alias. In this case, we attach to the "$ LATEST" pointer , and now our "Dev" alias will always point to the last branch, so we can always test our application with the latest version of lambda on the dev environment. And if suddenly we need to check how it works on the old version, we just need to switch the alias in the trigger or change the link to the version in the alias without touching our application
    3. Add the Stage alias and bind it to the first version of our lambda
    4. Add the alias “Prod” and repeat what we did for the “Stage”

    Notice: here it is described how to work with aliases in practice. The practical part on lambda will be in the next article along with SQS

    And so, now we got something incomprehensible, in fact 3 aliases refer to one version, it is not clear. But nothing, everything in order

    Second state

    1. Create a second version of our lambda (It's possible to add the second output of “Hello world”). Here I want to note that at this moment "$ LATEST" will look immediately at the second version. And since "Dev" is tied to "$ LATEST" , he will also look at the second version.
    2. Next, we want our Stage to look at the second version. Now it is tied to version "1" . Here we need to manually change the version indicated by "Stage ".
    3. Rejoice. We got what we see as the second state on the chart. That is, our “Prod” looks at the first version, and “Dev” and “Stage” at the second.

    Third state

    Now, to get the third state, we just need to add a couple more lines to our code and there will be a third version of our lambda. And "Dev" will now look at her.


    And so what do we have?

    A little one. Quick. Relatively cheap. Autoscale. Versioned. Function.
    In this article, we considered only the theoretical part, familiarity with this service. Same as with SQS in the last article. In the next article, we will consider how these two services interact with each other and in practical form we will learn how to configure and use them.

    Also popular now: