41,99 €
Build scalable, efficient, and highly available web apps using AWS
If you're looking to learn more about scalable and cost-efficient architectures, this book is for you. Basic knowledge of Node.js skills or familiarity with cloud services is required. For other topics, we cover the basics.
This book will equip you with the knowledge needed to build your own serverless apps by showing you how to set up different services while making your application scalable, highly available, and efficient.
We begin by giving you an idea of what it means to go serverless, exploring the pros and cons of the serverless model and its use cases. Next, you will be introduced to the AWS services that will be used throughout the book, how to estimate costs, and how to set up and use the Serverless Framework.
From here, you will start to build an entire serverless project of an online store, beginning with a React SPA frontend hosted on AWS followed by a serverless backend with API Gateway and Lambda functions. You will also learn to access data from a SimpleDB database, secure the application with authentication and authorization, and implement serverless notifications for browsers using AWS IoT. This book will describe how to monitor the performance, efficiency, and errors of your apps and conclude by teaching you how to test and deploy your applications.
This book takes a step-by-step approach on how to use the Serverless Framework and AWS services to build Serverless Applications. It will give you a hands-on feeling, allowing you to practice while reading. It provides a brief introduction of concepts while keeping the focus on the practical skills required to develop applications.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 322
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
< html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
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 author, 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: July 2017
Production reference: 2040817
ISBN 978-1-78712-647-3
www.packtpub.com
Author
Diego Zanon
Copy Editor
Pranjali Chury
Reviewer
Chintan Mehta
Project Coordinator
Vaidehi Sawant
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Nitin Dasan
Indexer
Aishwarya Gangawane
ContentDevelopmentEditor
Rohit Kumar Singh
Graphics
Jason Monteiro
Technical Editor
Vibhuti Gawde
Production Coordinator
Arvindkumar Gupta
Diego Zanon is a full-stack developer for both JavaScript and .NET applications. He is passionate about understanding and trying new technologies and frameworks, especially those designed to solve scalability problems. In his free time, he likes to contribute to Stack Overflow and write in his blog.
Diego is a computer engineer with experience on a wide range of projects, from industrial systems to e-commerce websites, for customers around the world, including the USA, Brazil, Netherlands, and Kazakhstan.
Chintan Mehta is a cofounder af KNOWARTH Technologies (https://www.knowarth.com) and heads Cloud/RIMS/DevOps. He has a diploma in computer hardware and network certification and has rich progressive experience in systems and server administration of Linux, AWS Cloud, Devops, RIMS, and Server Administration on open source technologies. He is also an AWS Certified Solutions Architect-Associate. Chintan's roles during his career in infrastructure and operations include requirement analysis, architecture design, security design, high availability and disaster recovery planning, automated monitoring, automated deployment, building processes to help customers, performance tuning, infrastructure setup and deployment, and application setup and deployment along with setting up various offices at different locations with a fantastic sole ownership to achieve operation readiness for the organizations he has been associated with. He headed the Managed Cloud Services practice at his previous job and received multiple awards for his valuable contribution to the business of the group. He was involved in creating solutions and consulting to build SAAS, IAAS, and PAAS services on Cloud. He also led the ISO 27001:2005 implementation team as a joint management representative. Chintan has authored Hadoop Backup and Recovery Solutions and reviewed Liferay Portal Performance Best Practices.
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.com and 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.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
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/1787126471.
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!
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
Understanding the Serverless Model
Introducing serverless
Thinking serverless
Serverless and PaaS
IaaS and On-Premises
The main goals of serverless
Scalability
Availability
Cost efficiency
The pros and cons of serverless
Pros
Reduced operational costs
Focus on business
System security
Continuous delivery
Microservices friendly
Cost model
Cons
Higher latency
Constraints
Hidden inefficiencies
Vendor dependency
Debugging difficulties
Atomic deploys
Uncertainties
Use cases
Static websites
Lean websites
Small e-commerce websites
Temporary websites
Triggered processing
Chatbots
IoT backends
Scheduled events
Big Data
What you should avoid
Summary
Getting Started with AWS
Amazon Web Services
Handling user accounts and security
AWS IAM
Creating users and groups
Sign in with a non-root user account
Amazon Cognito
Managing AWS resources
AWS Management Console
AWS SDKs
AWS CLI
AWS CloudFormation
Amazon CloudWatch
Frontend services
Amazon S3
Using S3 with the CLI
Amazon Route 53
Amazon CloudFront
AWS Certificate Manager
Messaging and notifications
Amazon SNS
AWS IoT
Backend services
AWS Lambda
Creating a Lambda function
Amazon API Gateway
Expose your Lambda function using API Gateway
Database services
Amazon SimpleDB
Amazon DynamoDB
The serverless architecture of our online store
Estimating costs
Assumptions
Route 53 pricing
S3 pricing
CloudFront pricing
Certificate Manager pricing
IAM pricing
Cognito pricing
IoT pricing
SNS pricing
CloudWatch pricing
API Gateway pricing
Lambda pricing
SimpleDB pricing
DynamoDB
Total pricing
Summary
Using the Serverless Framework
Serverless Framework
Understanding the Serverless Framework
Other frameworks
Installing the framework
Configuring the framework
Managing permissions in a team
Creating a new project
The handler.js file
The serverless.yml file
Configuring the Lambda limits
Deploying a service
Invoking a function
Retrieving logs
Adding endpoints
Cross-Origin Resource Sharing
Removing a service
Going beyond the basics
Using npm packages
Accessing other AWS resources
Events
The S3 event
Schedule events
Serving HTML pages with Lambda
Using configuration variables
Plugins
Showing deployment information
Scaffolding
Summary
Hosting the Website
Serving static files with Amazon S3
Creating a bucket
Enabling web hosting
Handling errors
Using redirection rules
Using an error document
Delegating to CloudFront
Prerendering pages
Supporting www anchors
Uploading static files
Automating website publishing
Serving gzip files
Setting up Route 53
Creating a hosted zone
Creating record sets
Setting up CloudFront
Creating a distribution
Handling CloudFront caching
Invalidating server-side cache
Invalidating client-side cache
Updating Route 53 to use CloudFront
Supporting HTTPS
Creating a mail exchange record
Requesting free certificates with AWS Certificate Manager
Configuring CloudFront to support HTTPS connections
Summary
Building the Frontend
Getting started with React
React principles
The Flux pattern
React hello-world
Building a shopping cart
Preparing the development environment
Organizing the solution
Composing components
Implementing a component
The App component
The Product List component
The Product component
The Shopping Cart component
The Cart Item component
Publishing our demo
Making Ajax requests
Retrieving data from the server
Sending data to the server
Handling the page routes
Linking pages
Using the query parameters
Single-Page Applications
Pros and cons of Single-Page Applications
Pros
Cons
Considerations
Prerendering pages
Using PhantomJS
Using the Lambda functions for prerendering
Rendering on the fly
Building an online store
The Navbar component
The Home page
The product details page
The Shopping Cart page
The Login and Signup pages
The error pages
Summary
Developing the Backend
Defining the project architecture
Monolith versus Microservices
Nanoservices
Microservices
Monolith
Graph
Naming differences
Developing the backend
Defining the functionalities
Organizing the code
Referencing Lambda functions in other folders
Using multiple services
Setting the endpoints
RESTful APIs
Routing the HTTP verbs
Handling HTTP responses
Implementing the Lambda functions
Retrieving all products
Saving the Shopping Cart
Checking out
Summary
Managing a Serverless Database
Amazon SimpleDB
Modeling the database
Handling one-to-many relations
Handling numbers
Handling Booleans
Handling dates
Creating a domain
Limits
Inserting and querying data
Performance and concurrency
Managing the database
Backing up and restoring data
Controlling user access
DynamoDB
Modeling the database
Creating a table
Limits
Inserting and querying data
Inserting data
The Document Client API
Querying data
The scan method
The query method
Performance and concurrency
Managing the database
Provisioned throughput
Auto scaling
Backing up and restoring data
Controlling user access
Improving the serverless store
Retrieving all products
Retrieving the user's shopping cart
Saving the user's shopping cart
Processing the checkout
Amazon S3 (for media files)
Uploading and downloading files
Enabling CORS
Backing up and restoring data
Using S3 versioning
Summary
Securing the Serverless Application
Security basics
Information security
Authentication
Authorization
Confidentiality
Integrity
Non-repudiation
Availability
Security on AWS
Shared responsibility model
The Trusted Advisor tool
Pen testing
AWS CloudTrail
MFA
Handling authentication and authorization
Amazon Cognito
Creating a user pool
Creating an identity pool
Using Cognito in our serverless store
The Signup page
The Login page
Persisting the user token
Logging out
Handling authentication in Lambda functions
Summary
Handling Serverless Notifications
AWS IoT
Protocols
Finding the IoT endpoint
AWS IoT SDK
Implementing serverless notifications
Public notifications
Adding a comment box
Updating the list of comments
Creating a new instance of the IoT SDK
Sending and receiving new comments
Triggering a Lambda function with IoT
Private notifications
Using credentials of an authenticated user
Updating the logout feature
Creating an IoT policy
Attaching an IoT policy and connecting
Passing the Cognito Identity to the Lambda function
Sending IoT messages with Lambda
Summary
Testing, Deploying, and Monitoring
Testing your solution
Unit testing Lambda functions
Mocking external services
Using Sinon.JS for mocking
Testing the frontend
Simulating AWS services locally
Deploying your application
Development workflow
Blue-green deployment
Deploying new versions with a different database model
Creating a new table or column
Renaming a table or column
Dropping a table or column
Rollback a deployment
Creating staging environments
Being careful with the production environment
Test data
Keeping your functions warm
Monitoring the operation
Monitoring costs
Monitoring errors
Retrieving metrics with the Serverless Framework
Streaming Lambda logs
Handling errors
Monitoring performance
Monitoring efficiency
Summary
Serverless is a buzzword created to identify cloud services that are totally managed by the provider and have a different billing model where you pay only for the time that you use them, measured in a granularity of tenths of a second and not hours. Serverless Computing allows a wide range of applications to benefit from reduced costs, faster development, and much less trouble with availability and scalability. Those are enough reasons for you to start learning how to build serverless applications.
Besides teaching you what is and how to use serverless, this book offers a broader view on the subject. Serverless is frequently associated with FaaS and people don't realize that you can do much more with serverless than just running functions on demand. Serverless offers many services for databases, security, notifications, and others. I will teach you how to use them.
This book can be divided into the following three parts:
Introduction
: This is where you will be introduced to the serverless concepts and tools that will be used in this book. You will learn about AWS services and the Serverless Framework. This introduction ranges from
Chapter 1
,
Understanding the Serverless Model
, to
Chapter 3
,
Using the Serverless Model
.
Building a serverless application
: From
Chapter 4
,
Hosting the Website
, to
Chapter 7
,
Managing a Serverless Database
, you will follow how to develop and host a serverless application and build the frontend, backend, and data access layer.
Advanced features
: This book ends with
Chapter 8
,
Securing the Serverless Application
, to
Chapter 10
,
Testing, Deploying, and Monitoring
, giving you the knowledge of how to use serverless to implement security and real-time notifications in addition to how to test, deploy, and monitor your application.
Chapter 1, Understanding the Serverless Model, introduces the concept and its pros and cons along with some use cases.
Chapter 2, Getting Started with AWS, gives an introduction to new AWS users and describes which tools will be used throughout the book.
Chapter 3, Using the Serverless Framework, teaches you how to configure and use the Serverless Framework, which is a must-have tool to build serverless applications.
Chapter 4, Hosting the Website, helps you to configure your domain and host your website with HTTPS support.
Chapter 5, Building the Frontend, uses the approach of Single-Page Applications to design a React frontend.
Chapter 6, Developing the Backend, covers how to design a RESTful interface and build the backend code using Node.js.
Chapter 7, Managing a Serverless Database, shows how to use SimpleDB and DynamoDB to store data for a serverless project.
Chapter 8, Securing the Serverless Application, covers the standard security practices and how to implement authentication and authorization in a serverless application.
Chapter 9, Handling Serverless Notifications, demonstrates how to build serverless notifications using the publisher-subscriber pattern.
Chapter 10, Testing, Deploying, and Monitoring, shows how to test a serverless solution, what are the standard practices to deploy your application in production, and what you need to monitor.
This book assumes previous knowledge of web development using JavaScript and Node.js. While you have many options of programming languages to develop a serverless application, all code examples of this book uses Node, so some basic knowledge of Node.js is necessary at least to understand how npm and the JavaScript ES6 syntax are used.
There are many cloud providers that offer serverless services, but this book focuses on AWS. You don't need to have prior knowledge of AWS because we will cover the basics too, but you will need to create an account to develop and test the code examples. If it is a brand new account, AWS offers a free tier of 12 months for you to learn and develop without any cost.
This book was designed for web developers who want to use cloud services to be more productive, reducing the time wasted on configuration and maintenance of the infrastructure or for developers who want to build solutions using existing services to solve common problems with very little effort.
Also, as I work as a full-stack developer, my job requires me to understand a little bit of everything such as frontend, backend, databases, security, and DevOps. So I tried to give in this book a broad view of web development using the serverless concept. If you have a similar role or, at least, want to learn more about the different layers of web development, this book will suit you well.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "This example defines a <HelloReact/> HTML element and the rendered output will use the value of the name property".
A block of code is set as follows:
class HelloReact extends React.Component { render() { return <div>Hello, {this.props.name}!</div>; } } ReactDOM.render( <HelloReact name="World"/>, document.getElementById('root') );
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
aws s3 sync ./path/to/folder s3://my-bucket-name --acl public-read
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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/Building-Serverless-Web-Applications. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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/BuildingServerlessWebApplications_ColorImages.pdf.
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 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.
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.
Serverless is a model where the developer doesn't need to worry about servers: configuring, maintaining, or updating is none of their business. Although it is not an entirely new concept, the services that are offered nowadays are much more powerful and enable a wider range of applications. If you want to build cost-effective and scalable solutions, you should dive deeper into this subject and understand how it works.
In this chapter, we will cover the following topics:
What is serverless?
The main goals of serverless
Pros and cons
Use cases
After this chapter, you will be ready to start our hands-on approach, building an online store demo application, one piece per chapter.
Serverless can be a model, a type of architecture, a pattern, or anything else you prefer to call it. For me, serverless is an adjective, a word that qualifies a way of thinking. It's a way to abstract how the code that you write will be executed. Thinking serverless is to not think in servers. You code, you test, you deploy, and that's (almost) enough.
Serverless is a buzzword. You still need servers to run your applications, but you should not worry about them that much. Maintaining a server is none of your business. The focus is on development and writing code, and not in the operation.
DevOps is still necessary, although with a smaller role. You need to automate the deployment and have at least a minimal monitoring of how your application is operating and how much it costs, but you don't need to start or stop machines to match the usage and neither do you need to replace failed instances or apply security patches to the operating system.
A serverless solution is entirely event-driven. Every time that a user requests some information, a trigger will notify your cloud vendor to pick your code and execute it to retrieve the answer. In contrast, a traditional solution also works to answer requests, but the code is always up and running, consuming machine resources that were reserved specifically for you, even when no one is using your system.
In a serverless architecture, it's not necessary to load the entire codebase into a running machine to process a single request. For a faster loading step, only the code that is necessary to answer the request is selected to run. This small piece of the solution is referenced as a function. So we only run functions on demand.
Although we call it simply as a function, it's usually a zipped package that contains a piece of code that runs as an entry point along with its dependencies.
In the following diagram, the serverless model is illustrated in a sequence of steps. It's an example of how a cloud provider could implement the concept, though it doesn't have to implement it in this way:
Let's understand the following steps shown in the preceding diagram:
The user sends a request to an address handled by the cloud provider.
Based on the message, the cloud service tries to locate which package must be used to answer the request.
The package (or function) is selected and loaded into a Docker container.
The container is executed and outputs an answer.
The answer is sent to the original user.
What makes the serverless model so interesting is that you are only billed for the time that was needed to execute your function, usually measured in fractions of seconds, not hours of use. If no one is using your service, you pay nothing.
Also, if you have a sudden peak of users accessing your application, the cloud service will load different instances to handle all simultaneous requests. If one of those cloud machines fails, another one will be made available automatically, without needing to configure anything.
Serverless is often confused with Platform as a Service (PaaS). PaaS is a kind of cloud computing model that allows developers to launch applications without worrying about the infrastructure. According to this definition, they have the same objective! And they do. Serverless is like a rebranding of PaaS, or you can call it the next generation of PaaS.
The main difference between PaaS and serverless is that in PaaS you don't manage machines, but you are billed by provisioning them, even if there is no user actively browsing your website. In PaaS, your code is always running and waiting for new requests. In serverless, there is a service that is listening for requests and will trigger your code to run only when necessary. This is reflected in your bill. You will pay only for the fractions of seconds that your code was executed and the number of requests that were made to this listener. Also, serverless has an immutable state between invocations, so it's always a fresh environment for every invocation. Even if the container is reused in a subsequent call, the filesystem is renewed.
Besides PaaS, serverless is frequently compared with Infrastructure as a Service (IaaS) and On-Premises solutions to expose its differences. IaaS is another strategy to deploy cloud solutions where you hire virtual machines and is allowed to connect to them to configure everything that you need in the guest operating system. It gives you greater flexibility, but it comes with more responsibilities. You need to apply security patches, handle occasional failures, and set up new servers to handle usage peaks. Also, you pay the same per hour whether you are using 5% or 100% of the machine s CPU.
On-Premises is the traditional kind of solution where you buy the physical computers and run them inside your company. You get total flexibility and control with this approach. Hosting your own solution can be cheaper, but it happens only when your traffic usage is extremely stable. Over or under provisioning computers is so frequent that it's hard to have real gains using this approach, even more when you add the risks and costs to hire a team to manage those machines. Cloud providers may look expensive, but several detailed use cases prove that the return of investment (ROI) is larger running on the cloud than On-Premises. When using the cloud, you benefit from the economy of scale of many gigantic data centers. Running on your own exposes your business to a wide range of risks and costs that you'll never be able to anticipate.
To define a service as serverless, it must have at least the following features:
Scale as you need
: There is no under or over-provisioning
Highly available
: It is fault tolerant and always online
Cost-efficient
: You will never pay for idle servers
With IaaS, you can achieve infinite scalability with any cloud service. You just need to hire new machines as your usage grows. You can also automate the process of starting and stopping servers as your demand changes. But this is not a fast way to scale. When you start a new machine, you usually need to wait for around 5 minutes before it can be usable to process new requests. Also, as starting and stopping machines is costly, you only do this after you are certain that you need. So, your automated process will wait some minutes to confirm that your demand has changed before taking any action.
IaaS is able to handle well-behaved usage changes, but it can't handle unexpected high peaks that happen after announcements or marketing campaigns. With serverless, your scalability is measured in milliseconds and not minutes. Besides being scalable, it's very fast to scale. Also, it scales per invocation without needing to provision capacity.
When you consider a high usage frequency in a scale of minutes, IaaS suffers to satisfy the needed capacity while serverless meets even higher usages in less time.
In the following graph, the left-hand side graph shows how scalability occurs with IaaS. The right-hand side graph shows how well the demand can be satisfied using a serverless solution:
With an On-Premises approach, this is a bigger problem. As the usage grows, new machines must be bought and prepared, but increasing the infrastructure requires purchase orders to be created and approved, you need to wait the new servers to arrive and you need to give time to your team to configure and test them. It can take weeks to grow, or even months if the company is very big and requests many steps and procedures to be filled in.
A highly available solution is the one that is fault tolerant to hardware failures. If one machine goes out, you must keep running the application with a satisfactory performance. If you lose an entire data center due to a power outage, you must have machines in another data center to keep the service online. Having high availability generally means to duplicate your entire infrastructure, placing each half in a different data center.
Highly available solutions are usually very expensive in IaaS and On-Premises. If you have multiple machines to handle your workload, placing them in different physical places and running a load balancing service can be enough. If one data center goes out, you keep the traffic in the remaining machines and scale to compensate. However, there are cases where you will pay extra without using those machines.
For example, if you have a huge relational database that is scaled vertically, you will end up paying for another expensive machine as a slave just to keep the availability. Even for NoSQL databases, if you set a MongoDB replica set in a consistent model, you will pay for instances that will act only as secondaries, without serving to alleviate read requests.
Instead of running idle machines, you can set them in a cold start state, meaning that the machine is prepared, but is off to reduce costs. However, if you run a website that sells products or services, you can lose customers even in small downtimes. A cold start for web servers can take a few minutes to recover, but needs several more minutes for databases.
Considering these scenarios, in serverless, you get high availability for free. The cost is already considered in what you pay to use.
Another aspect of availability is how to handle Distributed Denial of Service (DDoS) attacks. When you receive a huge load of requests in a very short time, how do you handle it? There are some tools and techniques that help mitigate the problem, for example, blacklisting IPs that go over a specific request rate, but before those tools start to work, you need to scale the solution, and it needs to scale really fast to prevent the availability from being compromised. In this, again, serverless has the best scaling speed.
It's impossible to match the traffic usage with what you have provisioned. With IaaS or On-Premises, as a rule of thumb, CPU and RAM usage must always be lower than 90% for the machine to be considered healthy, and ideally CPU should be using less than 20% of the capacity with normal traffic. In this case, you are paying for 80% of waste when the capacity is in an idle state. Paying for computer resources that you don't use is not efficient.
Many cloud vendors advertise that you just pay for what you use, but they usually offer significant discounts when you provision for 24 hours of uptime in a long term (one year or more). It means that you pay for machines that you will keep running even in very low traffic hours. Also, even if you want to shut down machines to reduce costs, you need to keep at least a minimum infrastructure 24/7 to keep your web server and databases always online. Regarding high availability, you need extra machines to add redundancy. Again, it's a waste of resources.
Another efficiency problem is related with the databases, especially relational ones. Scaling vertically is a very troublesome task, so relational databases are always provisioned considering max peaks. It means that you pay for an expensive machine when most of the time you don't need one.
In serverless, you shouldn't worry about provisioning or idle times. You should pay exactly the CPU and RAM time that is used, measured in fractions of seconds and not hours. If it's a serverless database, you need to store data permanently, so this represents a cost even if no one is using your system. However, storage is very cheap compared to CPU time. The higher cost, which is the CPU needed to run the database engine that runs queries, will be billed only by the amount of time used without considering idle times.
Running a serverless system continuously for one hour has a much higher cost than one hour in a traditional infra. However, the difference is that serverless is designed for applications with variable usage, where you will never keep one machine at 100% for one hour straight. The cost efficiency of serverless is not perceived in websites with flat traffic.
In this section, we will go through the various pros and cons associated with serverless computing.
We can list the following strengths:
Fast scalability
High availability
Efficient usage of resources
Reduced operational costs
Focus on business, not on infrastructure
System security is outsourced
Continuous delivery
Microservices friendly
Cost model is startup friendly
Let's skip the first three benefits, since they were already covered in the previous pages, and let's take a look at the others.
As the infrastructure is fully managed by the cloud vendor, it reduces the operational costs since you don't need to worry about hardware failures, applying security patches to the operating system, or fixing network issues. It effectively means that you need to spend less sysadmin hours to keep your application running.
Also, it helps to reduce risks. If you make an investment to deploy a new service and that ends up as a failure, you don't need to worry about selling machines or disposing the data center that you have built.
Lean software development states that you must spend time in what aggregates value to the final product. In a serverless project, the focus is on business. Infrastructure is a second-class citizen.
Configuring a large infrastructure is a costly and time-consuming task. If you want to validate an idea through a Minimum Viable Product (MVP) without losing time to market, consider using serverless to save time. There are tools that automate the deployment, which we will use throughout this book and see how they help the developer to launch a prototype with minimum effort. If the idea fails, infrastructure costs are minimized since there are no payments made in advance.
