Introduction: Big factories are doing Serverless, he is what east east? Probably many people have not heard of this, I have heard that this is a trend in the big front end, more popular in the last two years, if you have not heard of it, then you need to pay attention to it. Today, Sun Calls beast to take you to know about Serverless.

directory

 

What does Serverless solve?

What does Serverless do?

Some common Serverless platforms

How to understand Serverless technologies – FaaS and BaaS

How does Serverless computing work?

Serverless Application scenario

Advantages and disadvantages Serverless

Small white operation guide

The working process


What does Serverless solve?

Problem: After the front-end and back-end are separated, they are independent of each other. As a result, the front-end needs to pay attention to some problems of the back-end, as follows:

  • Complete back-end application online process
  • Machine management operation and maintenance: expanding and shrinking capacity
  • Downgrading, fusing, current limiting
  • Domain name, performance, and monitoring

Has touched the knowledge blind spot of many classmates. As a front-end, it’s true that most people don’t know much about the server-side environment, deployment infrastructure, etc. But now that the front end is a standalone deployment, the front end is bound to face these things. That’s the problem Serverless is trying to solve.

 What does Serverless do?

Question: Is it possible to make a tool, we only need to care about the front-end code, server things tools automatically do for us.

That’s what Serverless does. As shown below, we only need to worry about the business code, not the server infrastructure.

Some common Serverless platforms

(Here are some serverless platforms for you to try and explore if you are interested.)

How to understand Serverless technologies – FaaS and BaaS

Serverless The server-side logic implemented by the developer runs in a stateless computing container. It is triggered by events and is completely managed by third parties. Its business-level state is recorded by the database and storage resources used by the developer. Serverless covers many technologies and falls into two categories: FaaS and BaaS.

FaaS (Function as a Service)

FaaS is intended to run back-end code directly without having to manage your own server system or your own server applications. By server applications, I mean the technology’s biggest difference from other modern architectures such as containers and PaaS (platform as a Service).

FaaS can replace some service processing servers (maybe physical computers, but definitely need to run some kind of application), so that not only do you not need to supply the server itself, but you don’t need to run the application full-time.

FaaS products are not required to be developed using a specific framework or library. In terms of language and environment, FaaS functions are normal applications. Functions such as AWS Lambda can be implemented in Javascript, Python, and any JVM language (Java, Clojure, Scala). However, Lambda functions can also execute any process that is bundled with the required deployment artifacts, so you can use any language, as long as you can compile as a Unix process. FaaS functions do have some architectural limitations, especially in terms of state and execution time.

In moving to FaaS, the only code that needs to be changed is the “main method/start” code, which may need to remove the code associated with the top-level message handler (the implementation of the “message listener interface”), but this may only require changing the method signature. In the world of FaaS, all the rest of the code, such as code written to a database, does not change.

Compared to traditional systems, the deployment approach is a big change — the code is uploaded to the FaaS vendor, and everything else is done by the vendor. The current approach usually means uploading a new definition of the code (for example, uploading a ZIP or JAR file) and then calling a proprietary API to initiate the update process.

Functions in FaaS can be triggered by vendor-defined event types. For Amazon AWS, such triggering events can include S3 (file) updates, timing (scheduled tasks), and messages added to the message bus (such as Kinesis). Usually your function needs to specify the event source to which it wants to bind.

Most vendors also allow functions to be fired in response to incoming Http requests, usually from some type of API gateway (for example, AWS API Gateway, Webtask).

BaaS (Backend as a Service)

Backend as a Service (BaaS) means that we no longer write or manage all server-side components and can use domain-generic remote components (rather than in-process libraries) to provide services. To understand BaaS, you need to understand how it differs from PaaS.

First, BaaS are not PaaS. The difference is that PaaS need to participate in application lifecycle management, while BaaS only provide third-party services that the application depends on. A typical PaaS platform needs to provide a means for developers to deploy and configure applications, such as automatically deploying applications into a Tomcat container and managing the application lifecycle. BaaS does not contain these contents. BaaS only provides the back-end services that applications depend on, such as databases and object storage, in the form of apis. BaaS can be provided by public cloud service providers or third-party vendors. Second, functionally, BaaS can be seen as a subset of PaaS, that is, the part that provides third party dependent components.

The BaaS service also allows us to rely on application logic that others have already implemented. Certification is a good example of this. Many applications have to write their own code to implement the logic of registration, login, password management, and so on, and the code is often the same for different applications. It’s perfectly possible to take these repetitive tasks and turn them into external services, which is the goal of products like Auth0 and Amazon Cognito. They enable comprehensive authentication and user management, and the development team no longer has to write or manage the code that implements these capabilities.

How does Serverless computing work?

The nature of synchronous invocation is that the client expects the server to return the calculation results immediately. When the request arrives at the function evaluation, the execution environment is immediately assigned to execute the function.

Take the API gateway as an example. The API gateway synchronously triggers function calculation, and the client waits for the execution result of the server. If an error occurs during execution, the function calculation directly returns the error without retry. In this case, the client needs to add a retry mechanism for error handling.

The nature of an asynchronous call is that the client does not rush to know the result of the function immediately, and the function evaluates the request by putting it on a queue and returning success without waiting until the function call finishes.

Function evaluation gradually consumes the requests in the queue, allocates the execution environment, and executes the function. If an error is encountered during execution, the calculation retries the incorrect request, retries the function error three times, and the system error is exponentially retried indefinitely until it succeeds.

Asynchronous invocation applies to data processing, for example, the OSS trigger function processes audio and video, and the log trigger function cleans logs. These scenarios are insensitive to delay and need to ensure task execution success as much as possible. The Destination function can be used if the user needs to learn about failed requests and customize the processing of the request. Function computation is Serverless. This does not mean that there is no server, but the developer does not need to care about the server. Function computation assigns the developer instances to execute the function.

Serverless Application scenario

Send a notification

Services like PUSH Notification, email Notification interfaces, SMS, they all require infrastructure to build. Moreover, their requirements for real-time performance are relatively low. Even a few seconds later in time is acceptable to users. In the text messaging examples we have seen, it is generally assumed that the user can receive the message within 60 seconds. Therefore, the user will not be annoyed by the error of 1s in this time.

Lightweight API

Serverless is particularly well suited to lightweight, fast-changing apis. In fact, I have never thought of a suitable example. In my hypothetical scenario, an AutoSuggest API might be such an API, but such an API is sometimes accompanied by quite complex business. So, an example of Featrue Toggle, though a little inappropriate. But perhaps the most valuable part.

The Internet of things

When we talk about the Internet of Things, we talk about event triggers, transport protocols, massive data (data storage, data analytics). And with Serverless, so much data, processing is also quite easy. For the server of an Internet of things application, the system needs to collect data from various places, and create a pipeline to process, filter, transform these data, and store the data in the database. For hardware developers, docking different hardware is a challenge in itself. Directly using countries such as AWS IoT can help us develop better applications that write server connections in a way.

Statistical analysis of data, etc

Data statistics themselves require very little computation, but generating charts can be done on a regular basis. When receiving data, we do not need to consider any delay problems. The delay of 50~200 ms does not have any impact on our system.

Advantages and disadvantages Serverless

advantages

1. Faster time to market We can get applications to market faster because OPS is easier and will help developers focus on their development. OPS teams don’t need to write code that can handle extensions or worry about the underlying infrastructure. In addition, teams can build applications faster with the help of third-party integration, such as API services such as OAuth, Twitter, and Maps.

2. Highly scalable Every company wants their applications to run better, have zero downtime, and scale quickly and easily as traffic increases, but with a single application development, it can become very difficult. As application load increases, Ops teams must be vigilant when scaling the underlying infrastructure. Due to increased traffic, downtime wastes a lot of time and money. But serverless computing is highly scalable, allowing applications to be scaled and scaled in seconds.

3. Low cost In serverless computing, developers pay only when functionality is running, unlike IaaS and PaaS, which charge 24/7 per server. This can be very useful for companies with large application, API, or microservice setups that currently run 24/7 and use resources 100% of the time, whether they are needed or not. But with no server, we can perform functions on demand and share resources instead of running the application 24/7, so we can greatly reduce idle time and make the application run faster.

4. Latency and geolocation. Improving application scalability depends on three factors: number of users, location of users, and network latency. In today’s world, apps have a global audience, which can add to delays. But a serverless platform can greatly reduce the risk of latency. With serverless, the container is instantiated to run the function on every event invocation, and can be created near the user’s geographic area, which automatically improves the performance of the application.

disadvantages

1. Increasing complexity The more elaborate we use an application, the more complex it becomes. The code for each function may become simpler, but the entire application will become more complex. For example, we split the application into 10 different microservices. We had to manage 10 different applications, and within a single application, it was just one application that had to be managed.

2. Lack of tool support Suppose we split the monolithic application into 50 different functions. There are still a variety of processes and tools to manage, document, monitor, and deploy the overall application. Because serverless is new to the market, monitoring or recording applications that run for a few seconds is limited and challenging, but over time there will be many effective ways to do this.

3. With the complexity of the architecture it is difficult to determine the granularity of the functions, and it is time consuming to evaluate, implement, and test to check our preferences.

4. Managing too many features can be cumbersome, and ignoring granularity can lead to mini boulders.

5. Disadvantages in implementation The biggest challenge of serverless is the difficulty of integration testing.

Small white operation guide

The installation

Serverless is the Node.js CLI tool, so the first thing you need to do is install Node.js on your computer.

Note: No servers are running on Node v6 or later.

Open a terminal, then type NPM install -g serverless to install Serverless.

After the installation process is complete, you can verify that Serverless was successfully installed by running the following command from your terminal:

serverless
Copy the code

To see the installed serverless version:

serverless --version
Copy the code

test

Separate the business logic from the FaaS Provider

class Users { constructor(db, mailer) { this.db = db; this.mailer = mailer; } save(email, callback) { const user = { email: email, created_at: Date.now(), }; this.db.saveUser(user, function (err) { if (err) { callback(err); } else { this.mailer.sendWelcomeEmail(email); callback(); }}); } } module.exports = Users;Copy the code
const db = require('db').connect();
const mailer = require('mailer');
const Users = require('users');

let users = new Users(db, mailer);

module.exports.saveUser = (event, context, callback) => {
  users.save(event.email, callback);
};
Copy the code

 

Now, the above classes separate the business logic. In addition, the code responsible for setting up dependencies, injecting dependencies, calling business logic functions, and interacting with AWS Lambda is in its own file, which changes less frequently. This way, the business logic is not dependent on the provider and is easier to reuse and test.

In addition, this code does not need to run any external services. Instead of real DB and Mailer services, we can pass the mock exam and assert the appropriate parameters if saveUser and sendWelcomeEmail are called.

Unit tests can easily be written to cover the above lessons. You can add integration tests by calling the Serverless Invoke function () with the fixture email address to check that the user is indeed saved to the database, and to check that the email has been received to see if everything is okay.

The deployment of

Deploying with a serverless framework:

serverless deploy
Copy the code

The serverless framework converts all syntax serverless.yml into a single AWS CloudFormation template. By relying on CloudFormation for deployment, users without a server framework can obtain the security and reliability of CloudFormation.

  • The AWS CloudFormation template is created from itserverless.yml.
  • If a stack has not been created, the stack will be created without storing any resources except S3 buckets, which will store zip files of your functional code.
  • If you use a locally built ECR image, a dedicated ECR repository is created for your services.docker loginYou will also log in to the repository if necessary.
  • Your functional code is then packaged as a ZIP file.
  • If you are using locally built ECR images, build and upload them to the ECR.
  • None The server retrieves the hashes of all files from the previous deployment, if any, and compares them to the hashes of local files.
  • If all file hashes are the same, Serverless terminates the deployment process.
  • The Zip file for your functional code has been uploaded to your code S3 bucket.
  • Any IAM roles, functions, events, and resources are added to the AWS CloudFormation template.
  • The CloudFormation stack has been updated with the new CloudFormation template.
  • Each deployment releases a new version for each function in the service.

Deployment capabilities

serverless deploy function --function myFunction
Copy the code

Deployment package

serverless deploy --package path-to-package
Copy the code
  • the--packageThe parameter of the flag is previously made by Serverless (withserverless package) package directory.
  • The deployment bypasses the software package step and uses existing software packages to deploy and update the CloudFormation stack.

The working process

The development process

  1. Write your function
  2. serverless deployOnly in theserverless.ymlUsed when making changes to the CI/CD system. For more information about setting CI/CD for serverless applications, readIn this paper,.
  3. In the use ofserverless deploy function -f myFunctionSpecific AWS Lambda functions are available for rapid deployment of changes.
  4. Used forserverless invoke -f myFunction -lTest your AWS Lambda functions on AWS.
  5. Open a separate TAB in the console, and then go through the flow logserverless logs -f myFunction -t.
  6. Write tests to run locally.

Using the phase

  • At least usedevandproductionPhase.
  • Use different AWS accounts for phases.
  • In larger teams, each member should use a separate AWS account and their own development phase.

Larger project

  • Decompose your application/project into serverless services.
  • Model serverless services around a data model or workflow.
  • Keep functionality and resources in serverless services to a minimum.

Common commands

Create a new service

serverless create -p [SERVICE NAME] -t aws-nodejs
Copy the code

Installation services

serverless install -u [GITHUB URL OF SERVICE]
Copy the code

All deployment

serverless deploy -s [STAGE NAME] -r [REGION NAME] -v
Copy the code

Deployment capabilities

serverless deploy function -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME]
Copy the code

Call the function

serverless invoke -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME] -l
Copy the code

Flow log

serverless logs -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME]
Copy the code

 

 

 

 

 

 

 

[this article is to participate in “100% prize | I Serverless combat” filling activities 】, address: marketing.csdn.net/p/15940c87f…