Writing

AWS Fundamentals: Building Server-less Applications

AWSGeneralTech trendsAWS ApI gatewayAWS Identity Access ManagementAWS LambdaAmazon web servicesSeverless website with s3amazon cloudfrontamazon dynamo Dbamazon lexamazon s3chat botfundamentals of awsseverless applicationseverless website

Q.What do you mean by serverless ?

The serverless architecture is a way to build and run applications and services without having to manage the infrastructure behind it. Your application still runs on servers, of course, but the server management is done by AWS.

You no longer have to provision, scale, and maintain services to run your applications, databases, or storage systems. With the serverless architecture, you can execute your code only when needed, and scale automatically from a few requests per day to thousands of requests per second. And you only pay for the compute time you consume. There is no charge when your code’s not running. You can run code for virtually any type of application or back end service, all with zero administration.

So, why use serverless? Well, serverless enables you to build modern applications with increased agility and lower total cost of ownership. Building serverless applications means that your developers can focus on their core product, instead of worrying about managing and operating servers, or runtime, either in the cloud, or on premises.

So, what are the benefits of serverless? Serverless has four main benefits.

  1. One, no server management. There’s no need to provision, or maintain any servers. There’s no software or runtime to install, maintain, or administer. All of that is taken care of for you.
  2. Two, flexible scaling. Your application’s going to be scaled automatically by adjusting its capacity through toggling the units of consumption. For example, throughput or memory, rather than units of individual servers.
  3. Three, you pay for value. You pay for a consistent throughput, or execution duration, rather than by the server unit.
  4. Four, Automated high availability. Serverless provides built-in availability and fault tolerance. You don’t need an architect for these capabilities since the servers running the application provide them by default.

Amazon Lex :

Q. What is a chat bot?

The term itself is derived from chat robot. Why would we need a chat robot? If you think about a chat interaction you may have had with a support team, think how long you waited in line to get a simple query answered, the tome taken to answer your simple query could have been automated. However, this machine needs to be highly engaging, and provide conversational experiences through texts or even voice.

I need a bot that can take both text and may send over a chat in Facebook, Messenger, Slack, or via SMS or an audio input. If the input method is text, the machine can start parsing what I have typed. However, if it’s voice, the bot needs to take that input and recognize what was said to transfer the audio to text.

Q. Why is audio to text tough?

It needs to act as a human to parse that text, to recognize the intent of the text. It needs to deduce what the speaker actually means, and not just the words that they say here. That is what we call “natural-language understanding,” or NLU.

Q. How to convert text to speech ?

Amazon Polly is a text to speech service that uses advanced deep learning technologies to synthesize speech that sounds like a human voice.

While Lex integrates with Polly automatically, when the user interacts with Lex via speech, it sends this text to synthesize to speech to Polly, which in turn returns an audio file, that is then sent back to the user.

Q. What is flow of Amazon Lex?

A few basic terminologies used are :

  1. An intent is a particular goal that the user wants to achieve. So, the user sends a few utterances.
  2. The utterances are things like, “I’d like to book a hotel.” So, the utterance is sent into the bot. The bot will now look at part of all of its utterances and will try to match it to one of those intents.
  3. Next, we don’t have all of the information to be able to book a hotel. So, we need to start asking a few more questions toward the user. Well, those questions are sent via something we call a “prompt.”
  4. The prompt can be,”Sure, which city?”, will ask the user for that question. The user will now answer that question by saying, “Chicago” And then, that will fill something that we call a “slot.”
  5. A slot is data that the user must provide to fulfill the intent. They are required slots.
  6. And then, the bot will need to have the answer to every one of the slots to be able to fulfill this entire intent. Once all of the required slots have been filled, it is now time to ask the user.
  7. It’s time to fulfill this bot. The fulfillment is the business logic required to fulfill your entire goal, your intent, here.

You can also find the Error Handling section. In the case where the bot can’t match the ask of a user to an utterance in an intent, it will retry twice, as you see it right here. By sending the clarification prompt, that you can see at the top here. “Sorry, what can I help you with?” You can add more prompts, and it will randomly select one of them, which makes the bot seem a lot more human. In the case where it can’t understand what the user wants to either do by not being able to match it with an utterance in an intent or when a user doesn’t provide a valid answer to a prompt, one of the hang-up phrases will be used. In this case, it’s, “Sorry, I am not able to assist at this time.”

You don’t need to specify each one of the possibilities as Lex utilizes natural language understanding deep learning algorithms to expand those sample utterances. Sometimes though, you may need to add a few more utterances that the model doesn’t associate properly. For example, Book a Car intent you can use three utterances, which i can think of

  1. make a car reservation,
  2. reserve a car,
  3. book a car.

There are many built-in slot types, and all will start with the amazon prompt, as you see there. This particular one will take a date entered by a user and transform it to a date that machines can understand. For example, using “tomorrow” and transforming that to 2019-02-21. You can also specify to restrict values to only the ones you add Restrict to slot values and synonyms in Slot types.

Q.Why are those versions required?

It’s to create immutable versions of your bot. You may have a bot version you use for dev, beta, and prod. They may each use a different version of intent, and those intents may use a different version of a slot type.

I could point my application to this latest version and be done with it, but if I make any modifications, what do you think happens? I’m impacting my users, which isn’t great for customer satisfaction. So, I want my application to point to a version. That would mean that each time I modify my bot I need to redeploy my application? That sounds pretty bad. Yeah, that would be.

That’s why you shouldn’t do that. Instead, you should use an alias. I’ll click Publish. It asks me to create an alias version or update an alias version. An alias points to a version, so you can still only have one deployment of your code. Let me create a new alias. I’ll call that “prod” and hit the Publish button. Well, by clicking Publish, it creates a new version – version 1. And an alias name “prod” is created, pointing to version 1 of our bot.

Now, I can go in my application and make it point to the prod alias, without having to worry about making changes to the bot as the only way to impact the application will be to publish the bot again and then change the prod alias to point to that new version. That’s a lot of mistakes in a row, if you were to have that problem.

[Image no longer available]

Creating a Serverless Website with Amazon S3 :

Amazon S3 provides easy-to-use management features so you can organize your data and configure finely tuned access controls to meet your specific business, organizational, and compliance requirements.

One of the biggest advantages for using S3 is that you can host your website from an S3 bucket and reduce stress on origin or on your actual data center or AWS Cloud. This also minimizes your “attack surface” for your site adding in an additional layer of security. It’s cost-effective because it’s a frugal method for storage and website hosting, and you’re also reducing traffic to your origin site so you don’t have to pay for more web servers by scaling vertically or horizontally. It works to help with your security by reducing your attack surface by not sending traffic to your infrastructure or origin.

You just can’t use server-side processing code, like .NET or PHP. You can use a client-side script, like JavaScript. You can still set up your website to interact with other AWS services, like DynamoDB or API Gateway, and pull dynamic information by passing variables using query strings.

Instead of using the website endpoint for S3, you can also bring your own domain name – such as example.com – to serve your content. Amazon S3, along with Amazon Route 53, supports hosting a website at the root domain.

  1. Click on Create bucket
  2. You can see your bucket, click on it.
  3. You need to do is go to Properties. Even though I made it open to the public, I want to say that this is going to be a static website. Because if do not, no one’s going to be able to get to it still.
  4. You have to identify my index document or the main client side page.
  5. Also have an error.html or a error side page , if you wanted to have redirects, you can do that.
  6. If you want to take this site offline, you can always disable that website hosting.
  7. Click Save on that, go back to Overview.
  8. Now we’re actually going to upload our website.

But this is how easy it is, and because this website is hosted on S3, I don’t have to worry about, is it going to be resilient? Because it is resilient, because it’s a managed service from AWS. It’s going to be cost-effective, again, because it is a managed service from AWS. And it’s secure, because it’s a managed service from AWS. So this is a great way that I can have a public-facing website and not have to worry about servers in the back end, scaling up or down.

Introduction to Amazon Cloud Front:

Amazon Cloud Front speeds up content delivery by leveraging its global network of data centers, known as “edge locations.” Cloud Front has edge servers and locations all around the world.

There are no longer requests traversing the globe to get our content. Instead, requests are routed to the least latent edge location that is the closest in terms of delivery speed. Cloud Front then serves cached content quickly and directly to the user nearby. If content is not yet cached, with an edge server, Cloud Front retrieves it from the S3 bucket origin. And because the content traverses the AWS private network instead of public internet, and Cloud Front optimizes the TCP handshake, the request and content return is still so much faster than crossing the public internet.

By using Cloud Front, we can set up additional access restrictions, like GO restrictions, signed URLs, and signed cookies, to further constrain access to the content following different criteria.

Another security feature of Cloud Front is origin access identity, or OAI. Let’s take a look. OAI restricts access to an S3 bucket and its content to only Cloud Front in operations that Cloud Front performs. Cloud Front includes additional protection against malicious exploits. To provide these safeguards, Cloud Front integrates with both AWS WAF, a web application firewall that helps protect web applications from common web exploits, and AWS Shield, a managed DDoS protection service for web applications running on AWS.

  1. AWS WAF lets you control access to your content based on conditions that you specify. For example, IP addresses or the query string on a content request. Cloud Front then responds with either the requested content, if the conditions are met, or with an HTTP 403 forbidden error.
  2. All Cloud Front customers benefit from the automatic protection of AWS Shield standard at no additional charge.

Introduction to Amazon API Gateway:

So API Gateway is a fully managed service that’s designed to make it easy for developers to create, publish, maintain, and monitor secure application programming interfaces, or APIs, at any scale. With a few clicks in the AWS Management Console, you can create REST and Web Socket APIs that act as a front door for your applications to access data, business logic, or other functionality from your back end services. Like workloads, running on EC2, and web applications. API Gateway also provides an easy interface for code running on AWS Lambda and other AWS services,

Q. Why would you want to use API Gateway?

Well, turns out that software development organizations are moving more towards micro service architectures. Micro services are an approach to software development where software is composed of small independent services that communicate over well-defined APIs. Micro services architectures make applications easier to scale and faster to develop. And that really enables innovation and accelerates the time-to-market for new features.

Q. Why would you want to use it?

Well, developers can add headers, map input variables from POST events, to something your target application needs.Here are several more reasons you might want to use API Gateway.

  1. Efficient API development: You can run multiple versions of the same API simultaneously with API Gateway. This allows you to quickly iterate, test, and release new versions.
  2. Easy monitoring: You can monitor performance of metrics and information – on API calls, data latency, error rates – from the API Gateway dashboard, which allows you to see millions of requests in a single pane of glass.
  3. Performance: You can provide end users with the lowest possible latency for API requests and responses, by taking advantage of our global network of edge locations using Amazon Cloud Front. You can also throttle traffic and cache the output of API calls, to ensure that the back end operations withstand traffic spikes, and back end systems are not unnecessarily called.
  4. Cost savings: API Gateway provides a tiered pricing model for API requests. You can decrease your costs based on the number of API requests you make, per Region, across your AWS accounts.
  5. Flexible security controls: You can authorize access to your APIs with AWS Identity and Access Management, or IAM, as well as Amazon Cognito. If you use OAuth tokens or other authorization mechanisms, API Gateway can help you verify incoming requests as well. By providing an extra layer in front of your back end service, you can add extra layers to protection and security as well.

Mock Integrations in API Gateway

Amazon API Gateway supports mock integrations for API methods. This feature enables API developers to generate API responses from API Gateway directly, without the need for an integration backend. As an API developer, you can use this feature to unblock dependent teams that need to work with an API before the project development is complete. You can also use this feature to provision a landing page for your API, which can provide an overview of and navigation to your API. For an example of such a landing page, see the integration request and response of the GET method on the root resource of the example API discussed in Build an API Gateway API from an Example.

Origin Access Identity (OAI)

Origin Access Identity provides a method to restrict access to S3 content to only a CloudFront Distribution.

AWS Identity Access Management (IAM):

An IAM role is an IAM entity that defines a set of permissions for making AWS service requests. IAM roles allow you to delegate access with defined permissions to trusted entities without having to share long-term access keys. You can use an IAM role to delegate access to IAM users – managed within your account – to IAM users under a different AWS account, or to an AWS service like EC2.

An IAM user has permanent, long-term credentials, and is used to directly interact with AWS services. A group is primarily a management convenience to manage the same set of permissions for a set of IAM users.

For troubleshooting purposes, keep in mind that there’s an implicit denial for all actions. IAM policies are evaluated along with the service’s resource-based policies. When a policy of any type grants access without explicitly denying it, the action is allowed. Meaning if I have anywhere in the policy, an explicit deny statement, that will override any allow statement.

[Image no longer available]

AWS lambda :

AWS Lambda is a serverless compute service. It lets you run your code without provisioning or managing servers. You pay only for the compute time you consume. That means no charge when your code is not running.

1.Traditional deployment:

  1. I’ve got a VPC. And that provides me logical isolation at the network level.
  2. I have an internet gateway, which allows inbound and outbound traffic.
  3. I have an ELB, which distributes the traffic across two Availability Zones.
  4. I’ve chosen two for high availability and fault tolerance.
  5. I have two EC2 instances. The ELB will distribute the load to those.
  6. Traffic comes inbound through the internet gateway to the ELB, and then is distributed to the EC2 instances.

2.A different way:

  1. API Gateway is going to receive traffic from the user.
  2. It will send that traffic into Lambda,
  3. Lambda will be replying back with that traffic all the way down to the user.

With Lambda, you can run code for virtually any type of application or back end service, all with zero administration. Just upload your code, and Lambda takes care of everything required to run and scale your code with high availability. With AWS Lambda, you pay only for the requests served and the compute time required to run your code for each of those requests. Billing is metered in increments of 100 milliseconds, making it cost-effective and easy to scale automatically from a few requests to thousands per second.

let’s go through a flow of creating a lambda function

1.It needs you to pick a programming language. As of today, Lambda natively supports six programming languages: Node.js, Python, Java, C#, Ruby, and Go. Sometimes those native runtime aren’t enough because you may have a tool that you don’t want to rewrite that’s in C++, or maybe because your expertise isn’t PHP. That’s why it’s possible to use your own runtime, but you will need to develop that piece as well.

2.Next step required to create a Lambda function is to upload our code. This can be done in three ways,

  1. You can use the inline code editor,
  2. upload your own ZIP file containing your code,
  3. to store that ZIP file in S3 and point Lambda to that file.

Depending on what your code does, you may require Lambda to access other AWS services. For that, you will need to specify an Identity and Access Management role. That role is required to do logging, as you may need to troubleshoot the execution of your Lambda function. To do so, you can just output to the console in Node.js and Python. Anything that is sent there will automatically be sent to the CloudWatch Logs service, which is just a service to collect logs.

3.However, a Lambda function on its own doesn’t do much. It needs to be executed. We call that triggers. There are many AWS services that can trigger a Lambda function,

For example, a Lambda function can be triggered by S3 when a new object gets uploaded. So if you wanted to transform a picture that is uploaded to an S3 bucket and flip it upside down towards another S3 bucket.

There are a few ways to do the above task,

1.Sever world way:
  1. You will have to pull the S3 bucket to know if a new image has been uploaded every once in a while.
  2. I’ll need to poll that S3 bucket constantly until the image is there.
  3. And then once I’m ready, I can then send that towards the other S3 bucket.
2.AWS lambda way:
  1. You can configure S3 to trigger the Lambda function as soon as that image is uploaded.
  2. S3 needs to be allowed to trigger your Lambda function. As by default, nothing can trigger it.
  3. To do so, you use a function policy referencing the S3 bucket, if we use the AWS Management Console, that policy can be automatically created,

When your Lambda function gets executed, Lambda – the service – needs to know what piece of your code it needs to execute. That is the entry point for your code. In the Lambda world, that’s called a “handler.” This tells Lambda in which file or class the function to execute is, as well as its name.

Lambda will use that handler to execute your Lambda from the trigger it received, but your code probably needs to receive some more information about what just triggered it. That information is passed to the handler via what we call an “event payload.”

If we go back to our example of a picture uploaded to S3 to be transformed, that event payload will contain the bucket name and the object key of the blue triangle, which Lambda can now use to know which one of the objects from that input S3 bucket to transform.

[Image no longer available]

Those are the two types of invocation of Lambda,

  1. Asynchronous invocation : When a service like S3 invokes the Lambda function, there is no need for S3 to get return data from the function. It really doesn’t care about what Lambda does.
  2. Synchronous invocation : If we take another example where we will have API Gateway that sends a request to Lambda for a REST API call, API Gateway is really interested in the response from Lambda to be able to send it back towards the user.

While the function is running and transforming that image from S3, RAM and CPU are used. How are those allocated in Lambda? Well, you don’t allocate CPU power, you only allocate RAM. However, the more RAM you provide, the more CPU power your Lambda function will also have. As of today, that RAM allocation can go from 128 MB to 3 GB.This all depends on the complexity of your Lambda function code, you will need to execute some tests to figure out which amount of RAM is better here, which is the lower cost.

Now a limitation of Lambda is that a single execution can only run for maximum of 15 minutes. After 15 minutes, Amazon will yank the carpet under your code and you will now have no choice but to stop abruptly. If you do need to run for more than that, you are probably looking for another type of compute. Staying in the serverless world, you can take a look at AWS Fargate, or you could go to an architecture. Since you paid per 100 milliseconds of your code running and Lambda has a maximum timeout of 15 minutes, what happens if your code was to go in an infinite loop? Will you be charged for all the way to those 15 minutes? The answer here is: Yes, you will. However, there’s a timeout that is configurable for your Lambda function to prevent this kind of behavior.

Well, every time that I change my Lambda function, a brand new container gets deployed, a brand new Lambda function gets invoked in there, which means there will be a brand new log stream that gets created.Lambda is using console.log, or any print output in Python, for example, will be sent into CloudWatch Logs, and you can go in and review them inside of CloudWatch Logs.

API Gateway sends its data into Lambda via automatically packaging everything up into a JSON payload, the name parameter may not be passed the same way as how I’ve done my test in the first place. In fact, we’re going to need to go and modify our code.

Amazon Dynamo DB :

It’s important to understand the foundational concepts of DynamoDB, such as partition keys and sort keys, as well as local and global secondary indexes.

In DynamoDB, we call a set of information “tables.” A table is a collection of items, and each item is a collection of attributes.

  1. the partition key, which is a simple primary key, composed of one attribute.
  2. next to the partition key is a sort key.
  3. When a partition and a sort key exist in a table, it is referred to as a “composite primary key” and is composed of two attributes.
  4. So, while this table isn’t super useful yet, it will become useful when we add attributes.

But now, we need to figure out how this data will be queried to derive meaningful insights. Let’s talk indexes. A “secondary index” is a data structure that contains a subset of attributes from a table, along with an alternate key to support query operations. A table can have multiple secondary indexes, which give you application access to many different query patterns.

  1. Local secondary index. That’s an index that has the same partition key as the base table, but a different sort key. So, an example of a query that we could use on a local secondary index, A “local secondary index” is an index that has the same partition key as the base table, but a different sort key.
  2. A “global secondary index” is an index that has a partition key and a sort key that can be different from those based on the base table.

By the way, if it’s a local secondary index, there is only one and only opportunity to add it. Provision throughput is represented in units of read and write capacity. There are several options to manage this.

  1. First is the ability for you to provision throughput, again, based on read and write capacity units.
  2. Be sure to use our good friend Amazon CloudWatch to help guide you with your decision to increase or decrease.
  3. You can use the on-demand mode for DynamoDB. This will help you get up and running quickly without much concern to performance configurations.
  4. Auto scaling. Auto scaling is a way for you to run a more forgiving type of DynamoDB environment.
  5. As far as performance goes, these tools are largely automated, since it’s a managed service, which is really nice for you.

Extending our application :

Amazon Lex :

When we just had Amazon lex we didn’t have a validation perspective of slots, this is solved by AWS Lambda function, it validates each slot or response sent to Lex by the User.

When the intent in configured to invoke a Lambda function as initialization and validation code hook, Amazon Lex invokes the specified Lambda function on each user input after Amazon Lex understands the intent. If the intent is not clear, Amazon Lex can’t invoke the Lambda function. Why would we want a Lambda function invoked for every single utterance or prompt? Validation, of course! But don’t we already do validations in the case where we select Restrict to Slot values and Synonyms in a slot type? Well, yes, but sometimes we don’t control the slot because it’s a built-in slot. As you can see, the Amazon ones.

To add validation, we first need to create a Lambda function. I will be using a blueprint, as the Lex team was nice enough to give us a template for the Lex sample bot that we all need to use. In the Lex console, I will modify both intents to use this Lambda function for initialization and validation, as well as fulfillment.

Session attributes : They contain application-specific information that is passed between a bot and the client application during a session. Amazon Lex passes session attributes to all Lambda functions configured for a bot. If a Lambda function adds or updates session attributes, Amazon Lex passes the new information back to the client application. Session attributes can also be used to add more information in the prompts to the user,

You may also be wondering what constitutes a user to Lex. Well, when a request is sent to Lex, a user ID is also passed, and that’s what Lex will use as its key to associate all of the session’s attributes until the timeout is reached.

We can also integrate various channels into our AWS lex chatbot, On top of easily integrating Lex into web UI,or in your mobile application via the AWS mobile SDK, you can integrate your bot with Facebook Messenger, Kik, Slack, and Twilio SMS.

Let’s see how to do that with Facebook Messenger. First, we need a name. I’ll input ServerlessChatBot.

[Image no longer available]

  1. Then, I need to fill which alias I want to associate to my Facebook page. .
  2. Then, I need to select which Key Management Service key I want to use to encrypt all of the data.
  3. I need to input a verify token that I will use, reuse it in fact, on the Facebook developer portal. For the other two parameters, I need to go on Facebook to get those.
  4. First, I will create a Facebook page. I hit the Create button and select Page. I will use Community or Public Figure by clicking the Get Started button.
  5. Now that I have a page, I will need to jump over to the developer portal of Facebook,
  6. I’ll create a brand new application by clicking on the My Apps menu at the top, and clicking Add New App. For the Display Name, I’m going to use Serverlesschatbot.
  7. Going under the Settings, under Basic, I am going to find my App Secret. I’ll need to click that Show button right here to display it. I’ll take this App Secret, go back to Amazon Lex, and enter it as my App Secret input here.
  8. Next, I’ll go back to my developer portal in Facebook. I will go under the Products page, and I will add Messenger, and I’ll set up Messenger here. I will go under the Token Generation, and I’ll select the Facebook page I created called Serverlesschatbot. I’ll continue as myself.
  9. Now, this gives me a page access token that I’ll copy and paste back onto my Lex console.
  10. I will get an Endpoint URL. I will copy this Endpoint URL. So, still under the developer portal, under the setting of Messenger, I’ll go under Webhooks. I’ll click the Setup Webhooks button, where I will input this Endpoint URL that I have just copied from the Lex endpoint.
  11. Then, I need my Verify Token. If you remember. Then I need to specify Subscription Fields – those are messages, messaging_post backs, and messaging_options. I’ll click Verify and Save. And it seems like it worked.
  12. The next step is to subscribe, under my Webhooks, subscribe my Serverlesschatbot page to this application
  13. In my Facebook page, I will add a button, by clicking the Add button. I’ll select Contact you, send the message, click Next, select Messenger, and hit Finish.
  14. Now, this Send Message button allows us to send a message to the chatbot.
  15. My chatbot is now available via my Facebook page.

Examples and details about how to do this can be found in the Lex Documentation.

Previous blog in the series was about migrating to cloud, http://programmerprodigy.code.blog/2020/06/05/aws-fundamentals-migrating-to-the-cloud/