cloud professional services

Aug 23, 2020 10:28:02 AM by Ran Dvir

5 Serverless Development Best Practices with AWS Lambda

AWS, High-Tech, Lambda


Application development is changing and improving with new serverless technologies. You can shorten the amount of code needed to write and reduce or eliminate the issues associated with a traditional server-based model when you use a serverless model. But with this development model, there are some key aspects to focus on to ensure you are building robust applications.

We’re going to talk about Infrastructure as Code, Testing functions Locally, Managing Code, Testing, and Continuous Integration/Continuous Delivery (CI/CD) and do a high-level recap of what serverless means.

What is Serverless?

A serverless application is an app that doesn’t require the provisioning or management of any servers. Your application code still runs on a server, of course; you just don’t need to worry about managing it. You can just write code and let AWS handle the rest.

Lambda code is stored in S3, and when a function is invoked, the code is downloaded onto a server, managed by AWS, and executed.

AWS also covers the scalability and availability of your code. When you receive traffic to your lambda functions, AWS will scale up or down based on the number of requests to your application.

This approach to application development makes it easier to build and scale your application quickly. You don’t have to worry about servers, you just write code.

1. Infrastructure as Code (IaC)

When creating your infrastructure, you can use the AWS CLI, the AWS Console, or IaC. IaC is what AWS recommends as a best practice when developing new applications.

When you build your infrastructure as code, you have more control overyour environment in terms of audibility, automatability, and repeatability. You could create a Dev environment with IaC templates and then replicate that environment exactly for stage or prod. (while with the alternative you increase the likelihood to do something incorrectly and not replicate environments). When testing your application, it’s important to replicate what’s in prod to be sure that your code does what you intend for itto do.

Traditionally when using AWS, you would write CloudFormationTemplates. CloudFormationTemplates can become very long and hard to read so AWS came out with a solution to this if you’re writing a serverless app. You can use AWS SAM (Serverless Application Model). These templates can be written in JSON or YAML format and AWS SAM has it’s own CLI to help you build your applications. SAM is built on top of CloudFormation. Designed to shorten the amount of code needed to build your serverless infrastructure.

2. Testing Locally — AWS SAM Local

Before making deployments and updates to your application you should be testing everything to make sure you’re getting the desired outcome.

AWS SAM Local offers command-line tools that you can use to test your serverless applications before deploying them to AWS. SAM Local uses Docker behind the scenes enabling you to test your functions.

You can locally test an API you defined in your SAM template before creating it in API Gateway. You can validate templates you create to make sure you don’t have issues with deployment. Using these tools can help reduce the risk of error with your application. You can view logs locally and debug your code, allowing you to iterate changes quickly & smoothly.

3. Optimizing Code Management

Ideally, Lambda functions shouldn’t be overly complicated and coupled together. There are some specific recommendations around how you should write and organize your code.

Coding Best Practices
  • Decoupling Business Logic from the Handler

When writing your Lambda functions, you should receive parameters from within the “handler.” This is the root of Lambda functions. For example, if you had an API Gateway endpoint as the event source, you may have parameter values that are passed into the endpoint. Your handler should take those values and pass them to another function that handles the business logic. Doing this enables you to have code that is decoupled. This makestesting your code much more accessible, because the code is more isolated. Also, this allows you to reuse business logic through your app.

  • Fail Fast

Configure short timeouts for your functions. You don’t want to have a function spinning helplessly while waiting for a dependency to respond. Lambda is billed based on the duration of your function’s execution time. There is no reason to incur a higher charge when your functions’ dependencies are unresponsive.

  • Trim Dependencies

To reduce cold start times, you should trim the dependencies included to just the essentials at runtime. Lambda function code packages are permitted to be at most 50 MB compressed and 250 MB when extracted in the runtime environment.

Code Management Best Practices

Writing good code is only a battle, now you need to manage it properly to win the war. Like stated earlier, the development speed of serverless applications is generally much faster than a typical environment. Having a good solution for source control and management of your Lambda code will help ensure secure, efficient, and smooth change management processes.

AWS recommends having a 1:1 relationship between Lambda functions and code repositories and organizing your environment to be very fine-grained.

If you were developing multiple environments for your Lambda code, Dev and Prod, it makes sense to separate those into different release branches. The primary purpose of organizing your code this way is to ensure that each environment has it’s own separate, decoupled, environment. You don’t want to work on developing a modern application only to be left with a monolithic coupled code-base.

4. Testing

Testing your code is the best way to ensure quality when you are developing a serverless architecture.

  • Unit Tests

AWS recommends that you unit test your Lambda function code thoroughly, focusing mostly on the business logic outside your handler function. The bulk of your logic and tests should occur with mock objects and functions that you have full control over within your code-base.

You can create local test automation using AWS SAM Local, which can serve as local end-to-end testing of your function code.

  • Integration Tests

For integration tests, AWS recommends that you create lower life-cycle versions of your Lambda functions where your code packages are deployed and invoked through sample events that your CI/CD pipeline can trigger and inspect the results of.

5. Continuous Integration/Continuous Delivery (CI/CD)

AWS recommends that you programmatically manage all of your serverless deployments through CI/CD pipelines. Because the speed of development with a serverless architecture will be much more frequent. Creating manual deployments and updates along with the need to deploy more often can result in bottlenecks and errors.

AWS provides a suite of tools for setting up a CI/CD pipeline.

  • AWS CodeCommit

CodeCommit is AWS’s equivalent to GitHub or BitBucket. Providing private Git repositories and the ability to create branches. Allowing for best practices of code management with fine-grained access control.

  • AWS CodePipeline

CodePipeline automates the build, test, and deploy phases of your release process every time there is a code change. CodePipeline integrates with CodeCommit or other third-party services such as GitHub.

  • AWS CodeBuild

CodeBuild can be used for the build stage of your pipeline. You can use it to execute unit tests and create a new Lambda code package. Integrating it with AWS SAM to push your code to Amazon S3 and push the new packages to Lambda via CodeDeploy.

  • AWS CodeDeploy

CodeDeploy is used to automate deployments of new code to your Lambda functions, eliminating the need for error-prone manual operations. CodeDeploy has different deployment preferences you can use depending on what your needs are. For example, you can create a “Linear10PercentEvery1Minute” deployment, transferring 10% of your functions’ traffic to the new version of the function every one minute for 10 minutes.

  • AWS CodeStar

CodeStar is a unified user interface that allows you to create a new application with best practices already implemented. When you create a CodeStar project, it creates a fully implemented CI/CD pipeline from the start with tests already defined. CodeStar is the easiest way to get started building an application.

Sample Serverless Architectures

Now that we’ve covered some best practices for developing serverless applications, you should get some hands-on experience building applications. Here is a repository of tutorials for sample serverless applications.

Recap

Serverless applications take away the restraints of managing servers and allow you to focus on your application code. You can develop applications that meet business needs faster than ever. AWS provides a whole host of serverless technologies and tools to help you maintain and deploy your applications.

Need to dive fast into app development and deployment? At Cloudride, we provide end-to-end AWS Lambda serverless and other comprehensive services that help optimize the performance, business value, cost, and security of your cloud solution.

Contact us to learn more.

 

Subscribe today

For weekly special offers and new updates!