34,79 €
Serverless is a cloud computing execution model where the cloud provider dynamically manages the allocation and provisioning of servers. Many companies now use serverless architectures to cut costs and improve scalability. Thanks to its concise and expressive syntax and a smooth learning curve, Kotlin is a great fit for developing serverless applications.
With this book, you’ll be able to put your knowledge to work by implementing serverless technology in your applications and become productive in no time. Complete with detailed explanation of essential concepts and examples, this book will help you understand the serverless architecture fundamentals and how to design serverless architectures for your applications. You’ll also explore how AWS Lambda functions work. The book will guide you in designing, building, securing, and deploying your application to production, along with implementing non-functional requirements such as auditing and logging. Furthermore, you’ll discover how to scale up and orchestrate serverless applications using an open source framework and handle distributed serverless systems in production.
By the end of the book, you’ll be able to build scalable and cost-efficient Kotlin applications with a serverless framework.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 323
Veröffentlichungsjahr: 2018
Copyright © 2018 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Anugraha ArunagiriTechnical Editor: Bharat PatilCopy Editor: Muktikant GarimellaProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Tania DuttaProduction Coordinator: Shantanu Zagade
First published: September 2018
Production reference: 1280918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-370-8
www.packt.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.packt.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.packt.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.
Hardik Trivediis a self-taught computer programmer. He has worked on Android and Java since 2010 and has immersed himself in Kotlin and JavaScript. Apart from client projects, he loves contributing back to the development community by spending time on Stack Overflow and writing tech blogs. Hardik also mentors college students, professionals, and companies are interested in mobile app development. He is also an active community speaker.
Ameya Kulkarni has 8 years of work experience in the IT industry. He is adept with JVM technologies, Golang, designing microservice-based architectures, and DevOps. He has been working with Webonise for the past six years and as a Vice President, Engineering, for the last three years. He has a good grip at agile and lean product development. He likes designing solutions and consulting businesses to augment their core abilities with technology. He has experience of building scalable and distributed systems using JVM technologies.
Peter Sommerhoff is the founder of CodeAlong.tv and teaches more than 40,000 learners from around the globe how to code, combining the foundations of software development with plenty of hands-on practice. He holds a master's degree in Computer Science from RWTH Aachen University in Germany.
Peter is most passionate about Kotlin, and has distilled his knowledge about the language into his book, Kotlin for Android App Development—an in-depth and practical introduction to Kotlin that guides you through the language, interoperating with Java, and writing two Android apps purely in Kotlin.
When he's not teaching, he enjoys learning new things, cooking food, playing badminton, and going on biking tours.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Serverless Applications with Kotlin
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Introduction
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Basics of Serverless
What is serverless computing?
The evolution of serverless computing
On-premise
Colocation providers
Virtualization and IaaS
PaaS
BaaS
SaaS
FaaS
Serverless computing
Serverless – the time is now
Diving into serverless computing with a use case
A review of serverless computing
Comparing and contrasting traditional and serverless paradigms
The case study of an application
The architecture of the system using traditional methods
The architecture of the system using the serverless paradigm
Traditional versus serverless, in a nutshell
Pros and cons of serverless
Advantages of serverless systems
Reduced operational costs
Optimized resource utilization
Faster time to market
High-development velocity and laser-sharp focus on authoring code
Promoting a microservices architecture
The drawbacks of serverless systems
Nascent ecosystem
Yielding of control
Opinionated offerings
Provider limits
Standardized and provider-agnostic offerings
Tooling
Competition from containers
Rethinking serverless
An absence of local states
Applying modern software development practices
Time-boxed execution
Startup latency
Testability
Debugging
The serverless computing ecosystem
Serverless computers and infrastructure providers
AWS Lambda
IBM OpenWhisk
Microsoft Azure Cloud Functions
Google Cloud Functions
Auth0 Webtasks
Others
Serverless toolkits
Summary
AWS Serverless Offerings
AWS Lambda overview
Execution environment
Service limits
Invocation types
Custom invocation via AWS CLI or embedded AWS SDK in an application
Event sources from other AWS Services
Execution environments/runtimes
Handler
Context
Logging
Exceptions and error handling
Storing the state
JVM execution environment
Handlers in Java
Context object
Logging
Error handling
A case study of a simple Java Lambda function
Creating the Lambda function
Lambda dashboard
Basics of creation
Configuring the Lambda function
Writing a Lambda function
Deploying the Lambda function
Testing a Lambda function
Case study of a simple Kotlin Lambda function
Tooling
Anatomy of a Kotlin Lambda function
Project structure
build.gradle
Handler
Packaging and deploying
Testing the Kotlin function
Integrating a Lambda function with an upstream component
Types API Gateway and Lambda integrations
Lambda integration/ Lambda custom integration
Lambda proxy integration
Anatomy of the Lambda function when used in Lambda proxy integration
Creating an API Gateway
Integration testing
Deploying the API Gateway
End-to-end test
Basic monitoring of lambda functions
Versioning Lambda functions
Summary
Designing a Kotlin Serverless Application
The problem statement
Analyzing the problem statement
Functional specifications of the app
Designing the serverless API
Architectural and design decisions
AWS Cognito for login and registration
The Kotlin language
PostgresSQL 10 on Amazon RDS
API Gateway for proxy and edge engineering
API keys and usage plans
Authorization
Defining request and response models
API Gateway extensions to Swagger
Swagger 2.0 JSON documentation with API Gateway extensions
AWS Lambda as an FaaS platform
System design
Domain models
APIErrorResponseWithMessage
APISuccessResponseWithMessage
Poll
PollCreationRequest
RespondentDetails
PollResponseStatistics
PollDetails
API model
Registering a respondent
Fetching all Polls
Creating a Poll
Fetching a Poll
Deleting a Poll
Responding to a Poll
Persistence layer design
Connecting to the instance
Configuring an application user
Schema definition
Security and access control to the API
API key
Cognito authorizer for API
Note on the local development environment
Setting up
AWS Account
Installing IntellIj Idea CE
PostgreSQL
Third-party libraries
Liquibase
JOOQ
Build life cycle
Summary
Developing Your Serverless Application
Preparing the serverless environment
Configuring a Cognito pool
Swagger for the API
Implementing lambda functions
Writing your first lambda function in Kotlin
Choosing an IDE
Setting up a project
Writing a function that returns dummy static data
Data classes
Default parameters
Mutable list
Converting JSON into models using Jackson
The apply() function
Building a fat JAR
Deploying a JAR
Testing and executing
Implementing other lambda functions in Kotlin
Preparing the data classes
Registering respondents
Creating a poll
Getting a poll
Kotlin and the builder pattern
Implementation of the app
Setting up AWS Authentication using Cognito pool
Connecting to your backend
Object declaration
Integrating the API
Configuring the API client
Singleton
Lateinit versus lazy initialization
Lateinit
The lazy property
Interfaces
Rxify the API call
Lambda functions
Some interesting implementations
Returning data from a function
The destructuring declaration
Kotlin's approach to anonymous classes
Summary
Improving Your App with Firebase Service
About Firebase
Firebase authentication
Configuring authentication methods
Configuring the client app to use the authentication service
The when() expression
Improving the signIn() function using Lambda functions
Extension functions
Ditching the findViewById() method
View extensions
Firebase cloud functions
Prerequisites
Setting up the project
Creating a simple cloud function
Deploying the cloud function
Saving data into the real-time database
Structuring the request model
Structuring and saving the database object
Getting the list of polls
Interoperability with JavaScript
Monitoring crashes
Customizing the crash reports
Adding custom logs and keys
Monitoring the application's performance
How does it work?
Monitoring HTTP/s network requests
Using the SDK
Summary
Analyzing Your Application
What are non-functional requirements?
AWS CloudTrail
AWS CloudWatch
AWS CloudTrail
Concepts
Overview
Event packet structure
Integrations
AWS services supported for CloudTrail auditing
AWS services not supported for CloudTrail auditing
Example
Creating a simple audit trail for auditing Lambda configurations
Creating a trail
Advanced configuration of the trail
The created trail
Trail repository
AWS CloudWatch
Concepts
Metrics
Namespaces
Logs
Alarms
Dashboards
A practical walk-through
Visualization using CloudWatch dashboards
Creating a dashboard for Greeter metrics
Creating a dashboard
Adding widgets
Metrics selection for Lambda
Creating a widget for the API Gateway metrics
Dashboard preview
Test run
Integration of CloudTrail and CloudWatch
Configuring CloudWatch with CloudTrail
Creating an IAM role
Verifying the integration
Summary
Secure Your Application
AWS security concepts
Account access
Root credentials
Enabling Multifactor authentication
Need based account creation
IAM groups
Password policy
IAM roles and policies
Subject/principal
Resources
Permissions
Policies
Groups
Roles
Identities
Users
Best practices for creating IAM users
Creating individual users
The principle of least privilege
Leveraging predefined policies
Rotating passwords and keys
Using temporary credentials
IAM policy conditions
Continuous and exhaustive monitoring
AWS Virtual Private Cloud
Subnets
Private subnets
Public subnets
Security groups
Inbound
Outbound
Infrastructure hardening
Hardening AWS Cognito
Security measures for users
Allowing user signup
Expiring unused accounts
Setting password policies
Enabling MFA
User verification
Hardening AWS API Gateway
SSL/HTTPS
API key and usage plans
Resource policies
Authorizers
CORS support
Throttling
Hardening AWS Lambda
Using KMS to encrypt sensitive information
Execution role
Hardening AWS RDS
Moving RDS into a VPC's private subnet
Do not use master credentials
Practical walk–through
Setting up the test bed
Database access using JOOQ
The build.gradle file
Handler
Invocation
Database configuration as environment variables
Defining environment variables
Modifying the handler to source these environment variables
Building and deploying
Invoking the API
Encrypting the environment variables
Configuring KMS
Creating a Key
Supplying key details
Defining administrative permissions
Defining usage permissions
Key created
Configuring Lambda with KMS
Enabling encryption in transit
Decrypting in the handler
Boilerplate decryption
The handler class
The build.gradle file
Deploying and testing
Creating an RDS user
Creating a user
Granting privileges
VPC changes
Current setup
Creating the VPC
Creating security groups
Security groups for Lambda
Security groups for RDS
Modification of RDS
Modification of Lambda
Attaching security groups and specifying subnets
Modifying permissions of the IAM role
Conclusion of the walk–through
Summary
Scale Your Application
Infrastructure as code
Serverless Framework
Concepts
Providers
Services
Resources
Functions
Events
Practical walk-through
Getting started
Installation
Prerequisites for installation
Installing the framework
Configuring the CLI tool
Bootstrapping the project
Creating a service
Code organization and boilerplate
Workspace structure
The build.gradle file
The serverless.yaml file
Workflow
Building the package
Deploying the entire Service
Deploying a single function
Actual workflow
Environment variables
Provisioning the VPC
Creating a VPC
Creating and attaching the internet gateway
Public subnet
Private subnet
NAT gateway
Elastic IP allocation
Creation of NAT gateway and EIP Association
Route association
Creating a Route Table for the Public Subnet
Default Public Route
Association of a Public Route Table to a Public Subnet
Routing in the Private Subnet
Security groups
Provisioning IAM policies and roles for Lambda execution
Execution role creation
Basic execution policy
VPC execution policy
Provisioning a Cognito user pool
Provisioning the KMS key
Provisioning RDS
Provisioning lambda functions
Model definitions
API gateway Validation
Installing the request validator plugin
Usage of the plugin
Integration of the validators
Lambda to Register a Respondent
Lambda to fetch all polls
Lambda to create polls
Lambda to delete a poll
Lambda to fetch a poll
Lambda for responding to a poll
Lambda to migrate the database
Lambda to fix the database migrations
Caveats while scaling Serverless applications
Lambda execution life cycle
Workarounds for scaling lambda functions
Summary
Advanced AWS Services
AWS Cloud9
Introduction to Cloud9
How does it work?
Getting started
Prerequisites
Setting up an EC2 environment
Best practices
Usage patterns
Supported languages
Practical walk-through of authoring the lambda function in Cloud9
Use cases of Cloud9
AWS Alexa
Introduction to Alexa
Building blocks
Skills
Skills Kit
Interaction model
Invocations
Intents
Slot types
Interfaces
Functional endpoints
Account linking
Walkthrough of creating a simple custom Alexa Skill
Problem statement
Creating a skill
Registration on Amazon Developer Console
Naming a skill
Defining invocations
Defining intents and utterances
Linking the functional endpoint
Creating a Lambda function
A few tweaks
The build.gradle file
Entrypoint handler function
Technical architecture handler
The serverless.yaml file
Building the lambda function
Deploying the lambda function
Linking the Lambda to the Skill
Testing
Applying the finishing touches
Distribution and certification
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Serverless architecture allows you to build and run applications and services without having to manage the infrastructure. This book will be your companion and guide to designing serverless architectures for your applications with AWS and Kotlin. This book will help you build the client application and the backend functions serving it.
The book will begin with an explanation of the fundamentals of serverless architecture and the working of AWS lambda functions. You will then learn to build, release, and deploy your application to production. You will also learn to log and test your application and build a serverless API. You will then learn to troubleshoot and monitor your app and AWS lambda programming concepts with API references. Moving on, you will learn how to scale up serverless applications and handle distributed serverless systems in production. By the end of the book, you will be equipped with the knowledge needed to build scalable and cost-efficient Kotlin applications with the serverless framework.
This book is intended for technical practitioners who have some experience in building mobile applications with cloud-based API services using JVM technologies, such as Java, Groovy, and Kotlin. It is desirable that you have some knowledge about how such systems are managed and maintained from an infrastructural point of view. You are also expected to have some experience in developing REST APIs on traditional monolithic architectures.
This book is intended to be an introduction to serverless architecture and its associated tooling. The code accompanying this book was developed on macOS systems using IntelliJ Idea IDE Community Edition Kotlin and Gradle. You should set up the appropriate tools on your machines as per your platform choice (Linux or Windows).
By the end of this book, you will be familiar with the various AWS offerings that are required for building modern applications backed by serverless APIs, as well as the tooling that is required for developing, deploying, monitoring, and supporting such systems.
Chapter 1, Basics of Serverless, will enable you to understand serverless architectures, along with how to recognize them. You will gain insights into serverless applications by comparing them with traditional architectures. Lastly, you will have a brief overview of the Serverless ecosystem, consisting of providers and tooling.
Chapter 2, AWS Serverless Offerings, will introduce the concepts of AWS lambda and explain the concepts, intuition, and the components involved in the tool. It also explains the nuances involved in security, user controls, and versioning code inside AWS lambda.
Chapter 3, Designing a Kotlin Serverless Application, will analyze a case study of a serverless application entirely using Kotlin.
Chapter 4, Developing Your Serverless Application, will develop your serverless application using Kotlin and AWS by analyzing a case study.
Chapter 5, Improve Your App with Firebase Service, will improve your application using Firebase services.
Chapter 6, Analyzing Your Application, will cover how to log the important events of your application and best practices for logging your application behavior using AWS.
Chapter 7, Secure Your Application, will cover the hardening of your Kotlin AWS serverless application and best practices for granting secure access to your application.
Chapter 8, Scale Your Application, will discuss the practice of scaling up serverless architectures for large workloads using a number of third-party tools.
Chapter 9, Advanced AWS Services, will leverage advanced AWS services to extend the functionality of the application.
This book focuses more on practical aspects than it does on theoretical ones. In each chapter, you will see a perfect blend of theory and practice. This book will explain each and every necessary step and line of code with screen captures, code snippets, and other practical examples. By the end of the book, you will have a deployment-ready application written in Kotlin that uses a serverless approach. You will see how to use architectures and design patterns to write scalable code. You will also see how Firebase works with Kotlin.
You will need to have the following software installed on your local system:
Intellij IDEA CE IDE 2018.2
Gradle
Node.js and NPM
Docker
JDK1.8
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
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/-Hands-On-Serverless-with-Kotlin.In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
"x-amazon-apigateway-request-validators": {"Validate body": {"validateRequestParameters": false,"validateRequestBody": true}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
"parameters":[{"name":"
pollId
","in":"
path
",}
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Serverless computing is the latest advancement in the ever-changing technical landscape of the internet era. This advancement offers a new perspective on the development and deployment of modern production-grade systems, delivering cutting-edge user experiences. It is a constantly evolving realm, and, true to the nature of the software industry, it is improving its tooling and frameworks. It's worth looking over an introduction to the basics of serverless computing in order to better understand it.
This chapter will cover the following topics:
Understanding
serverless architectures
Why serverless, and why now?
Diving into serverless computing with a use case
The pros and cons of serverless
The serverless computing ecosystem
The official literature of Amazon Web Services (AWS), one of the de facto serverless providers, defines serverless computing as follows:
Producing software involves much more than just writing code. The code that the development team writes exists to solve a real-world problem, and needs to be available to the intended audience. For your code to serve the world, it (traditionally) has to exist on a server. The server itself has to be created (provisioned) and made capable of handling the workload that the business demands. The capabilities of a server are defined in many ways, like its processing power, memory capacity, and network throughput, just to name a few. These parameters are so vast and deep that they have spun up a vast market of jobs that businesses require. The jobs go by titles such as infrastructure management associate, operations associate, and, more recently, DevOps engineer.
It's the responsibility of these folks to evaluate and manage the hardware properties. That is what the definition highlights when it states, thinking about servers.
Serverless computing takes away the aforementioned need to think about the servers and other hardware resources.
As a paradigm, serverless computing can be applied to any solution that requires a backend or a piece of architecture and code that is not (or cannot) be exposed to the general public (loosely termed clients).
In the serverless paradigm, there are computational hardware assets, like servers, the management of these computational assets is not the developer's concern.This turnkey management is offered on a pay-as-you-use models keeping the costs as high or as low as the utilisation of the assets necessitate.
So, serverless computing itself is a misleading term, or misnomer. There are computational hardware assets serving your code, but their management is the cloud providers' problem.
This frees the companies adopting this paradigm from the overhead of the mundane, but equally important, tasks of tending and managing systems that behave well in production. It allows them to have a laser-sharp focus on their most valuable task - that is, writing code.
To better explain serverless computing, we will take a trip down memory lane and revisit the various paradigms used to host software, and the impact they have had on software design.
On-premise servers were one of the earliest paradigms, where the companies producing software had to not only deal with designing, architecting, and writing the code, but also had to execute and create a rainbow of auxiliary activities and elements, as follows:
Budgeting, purchasing, and arranging for real estate to host servers
Budgeting and purchasing of bare metal computational and networking hardware
Installation of computational assets
Equilibrium of environment
Authoring code
Configuration and provisioning of servers
Deployment strategies
Designing and implementing strategies for high
availability of the applications.
Backup and restore mechanisms
Performance and scalability
Patch management and uptime
The typical makeup of such a company had a less-than-optimal ratio of the development team to the overall headcount, vastly slowing down the delivery of its most valuable proposition, which was designing and shipping software.
It is obvious, looking at the scope of the preceding work, that such a setup and work environment posed a lot of hurdles to the growth of the organizations, and had a direct impact on their bottom-line.
Next, colocation providers came on the scene, with a business model to take away some of the responsibilities and provide services for a fee. They took away the need for companies to purchase real estate and other peripheral assets, like HVAC, by renting out such services for a fee.
They offered a turnkey solution for customers to house their own computational, networking assets for a charge. The customers still had to budget, purchase assets, and forecast their capacity requirements, even while renting out real estate.
Things got slightly better and the organizations grew leaner, but there were still a lot of activities to be done and elements to be created while supporting software development. These included the following:
Budgeting and purchasing of bare metal computational and networking hardware
Configuration and provisioning of servers
Authoring code
Deployment strategies
Designing and implementing strategies for high availability of the applications.
Backup and restore mechanisms
Performance and scalability
Patch management and uptime
The colocation model worked well until the early 2000s. Organizations had to deal with managing a bare metal infrastructure, including things like server racks and network switches. Due to the sporadic nature of the internet traffic, most of the assets and bandwidth were not utilized in an optimum fashion.
While all of this was considered business as usual, innovation gifted the world with platform virtualization. This enabled the bare metal racks to host more than one server instance in a shared hardware fashion, without compromising security and performance. This was a primary step toward the inception of cloud computing, spawning the pay-as-you-use paradigm, which was very attractive to organizations looking to bump up their bottom-lines.
Amazon launched Elastic Compute Cloud (EC2), which rented out virtualized computational hardware in the cloud, with bare minimum OS configurations and the flexibility to consume as many hardware and network resources as required. This took away the need for organizations to perform approximated capacity planning, and made sure that the infrastructure costs were a function of traction that a business was breaking. This paradigm is called Infrastructure as a Service(IaaS). It was widely adopted, and at a fast pace. The reduction in operational costs was the biggest driver behind its adoption.
At the same time, there were some activities that the company still had to undertake, as follows:
Authoring code
Configuration and provisioning of servers
Deployment strategies
Design of high availability
Backup and restore mechanisms
Performance and scalability
Patch management and uptime
The adoption of IaaS and cloud computing pushed innovation and churned out a paradigm called PaaS, or Platform as a Service. Leveraging the foundation set by IaaS, cloud providers started to abstract away services like load balancing, continuous integration and deployment, edge and traffic engineering, HA, and failover, into opinionated turnkey offerings. PaaS further reduced the responsibility spectrum of a company producing code to the following responsibilities:
Architecting and designing systems
Authoring code
Maintenance and patch management
PaaS enabled companies to focus solely on the backend and client application development. During this phase, applications and systems started to take a common shape. For example, almost every application requires a login, sign up, email, notifications, reporting, and so on.
Cloud providers leveraged this trend and started offering such common services as part of Backend as a Service, or BaaS. This enabled the companies to avoid reinventing the wheel, purchasing off-the-shelf products for common components. The management and uptime of such services are guaranteed as a part of Service Level Agreements (SLAs) by cloud providers.
Such an approach freed BaaS adopters up so that they could deliver rich and engaging user experiences, contributing to faster growth.
Software as a Service (SaaS) is a special type of Software as a Service model, where companies purchase entire systems, whitelist them, and offer them as a part of the solution that they provide. For example, Intercom.io provides an in-app messaging solution that drives up customer support.
Adopters and customers offload parts of their systems to specialized providers, who excel at offering such solutions to build it in-house.
For all of the benefits that BaaS and SaaS provide, companies still have to incorporate bespoke feedback into products, and they often feel the need to retain control of some of the business logic that comprises the backend.
This control and flexibility doesn't have to be achieved at the cost of the benefits of BaaS, SaaS, and PaaS. Companies, having tasted the benefits of such big strides in infrastructure management don't want to add costs to managing and maintaining hardware, whether bare metal or in the cloud.
This is where a new paradigm, Function as a Service (FaaS), has evolved to fill the gap.
Function as a Service is a paradigm wherein a function is a computation unit and building block of backend services. Formally, a function is a computation that takes some input and produces some output. At times, it produces side effects and modifies state out of its memory, and at times, it doesn't.
What's true in both of the cases is that a function should be called, its temporal execution boundary should be defined (that is, it should run in a time-boxed manner), and it should produce output that is consumable by downstream components, or available for perusal at a later time.
If one was to architect their backend service code along these lines, they would end up with an ephemeral computational unit that gets called or triggered to do its job by an upstream stimulus, performs the computation/processing, and returns or stores the output. In all of this execution, one is not worried about the environment that the function runs in. All one needs, in such a scenario, is code (or a function) that is guaranteed to perform the desired calculation in a determined time.
The runtime for the code, the upstream stimulus, and the downstream chaining, should be taken care of by the entity that provides such an environment. Such an entity is called a serverless computing provider, and the paradigm is called Function as a Service, or Serverless Computing.
The advantages of such an architecture, along with the benefits of BaaS and SaaS, are as follows:
Flexibility and control
The ability to deliver the discrete and atomic components of the system
Faster time to market
Serverless paradigms started as FaaS, but have grown, and are beginning to encompass BaaS offerings as well. As described previously, this is an ever-changing landscape, and the two concepts of FaaS and BaaS are coalescing into one, called serverless computing. As it stands today, the distinction is blurring, and it's difficult to say that serverless is pure FaaS. This is an important point to note.
To create modern serverless apps, FaaS is necessary, but not sufficient.
For example, a production-grade service that can crunch numbers in isolation can be created by using only FaaS. But a system that has user-facing components requires much more than a simple, ephemeral computational component.
In the past decade or so, investments in hardware and innovations in the tools that optimize hardware have paid off. Hardware has become a commodity. The era of expensive computational assets is long gone. With the advent and adoption of virtualization, renting hardware is a walk in the park, and is often the only option for companies that do not have the resources or inclination to bootstrap an on-premise infrastructure.
With the sky being the limit for current hardware capabilities, the onus is on software to catch up and leverage this. Serverless is the latest checkpoint in this evolution. Commoditized hardware and rapidly commoditizing allied software tooling enables companies to further reduce their operational costs and make a direct impact on their bottom-line. The question is not really whether companies will adopt the serverless paradigm, but when.
This revolution is happening now, and it is here to stay. The time is now for serverless!
