Notes On Serverless Architecture

Table of Contents

References

Synopsis

  • Backend as a Service (BaaS) services. (E.g: Google Firebase Database)
  • Functions as a Service (FaaS) platform. Runs custom code in managed, ephemeral containers. (E.g: AWS Lambda)
  • Reduced operational cost.
  • Cons: Increased reliance on vendor dependencies and comparatively immature supporting services.
  • Cloud accessible Databases: Parse, Firebase
  • Authentication Services: Auth0, AWS Cognito
  • Rich client e.g. single-page applications and Mobile Apps. Thick client handles session data what traditional middle layer used to do.
  • AWS Lambda is one implementation of such FaaS services. It supports both Java and Javascript.
  • Google’s Firebase BaaS database has explicit FaaS support through Google Cloud Functions for Firebase.
  • FaaS is about running backend code without managing your own server systems or your own long-lived server applications
  • AWS Cloudwatch is metrics monitoring framework which records lambda metrics (number of calls, duration, etc).
  • Lambda can be triggered in response to S3, Dynamo Db, Kinesis (mesg stream), SNS (pub/sub simple notification service), Cloudwatch events.
  • Lambda can be configured as scheduled event in place of cron job.
  • AWS Code commit trigger supports Lambda functions.
  • NOTE A serverless function runs only when triggered, and you pay only for its execution time. After execution, the serverless provider shuts the function down, while keeping its trigger active.
  • Vendor lock-in is a problem with serverless programming. This is where Claudia helps which helps to write platform independent FaaS functions. (AWS, Azure, Google Cloud Functions)

Traditional 3 Layer Architecture vs Serverless

Browser (Thin Client)  => Middle Layer => Database  (3 Tier Architecture)


Browser => API-Gate Way => Many FaaS Services => Database
   ||
   ======> Database
   ||
   ======> Authentication Service
  • Actually serverless may involve "many temporary mini-servers".
  • The API-Gateway acts more like Middle-Layer.
  • Browser may tend to become more thick client (by handling more data), but may decide to use FaaS service if it becomes too much. (E.g. Search Service).
  • Direct access to (some) Databases may be allowed.
  • Authentication Service exists as independent service.
  • Serverless does not imply microservices, but share many concepts such as separation of concerns, flexibility for changes.
  • FaaS offerings do not require coding to a specific framework or library.
  • Functions in FaaS are typically triggered by event types defined by the provider. With Amazon AWS such stimuli include :
    • S3 (file/object) updates,
    • time (scheduled tasks), and
    • messages added to a message bus (e.g., Kinesis).
  • Most providers also allow functions to be triggered as a response to inbound HTTP requests; in AWS one typically enables this by way of using an API gateway.
  • State-oriented functions will typically make use of a database, a cross-application cache (like Redis), or network file/object store (like S3) to store state across requests, or to provide further input necessary to handle a request.
  • FaaS functions are typically have timeouts: e.g. AWS Lambda function has timeout of five minutes. Microsoft Azure and Google Cloud Functions have similar limits.
  • You pay 20 cents per million executions of your AWS Lambda function.

Tools for Serverless

Serverless Framework – Build web, mobile and IoT applications with serverless architectures using AWS Lambda, Azure Functions, Google CloudFunctions & more!

The Serverless Framework – Build applications comprised of microservices that run in response to events, auto-scale for you, and only charge you when they run. This lowers the total cost of maintaining your apps, enabling you to build more logic, faster.

AWS Security

  • IAM - Identity and Access Management Roles is better option to using basic global aws credentials keys.
  • OAuth 2.0 and OpenID Connect are 2 industry standard identity management protocols.
  • OpenID Connect is a standard for transporting end user identity and in its implementation, it is based on the OAuth2 framework.
  • See https://docs.aws.amazon.com/cognito/latest/developerguide/open-id.html
  • OpenID Connect providers (are identity providers) :
    • accounts.google.com
    • login.salesforce.com
  • Amazon Cognito lets you add user sign-up, sign-in, and access control to your web and mobile apps quickly and easily. Amazon Cognito scales to millions of users and supports sign-in with social identity providers, such as Facebook, Google, and Amazon, and enterprise identity providers (e.g. Microsoft Active Directoy) via SAML 2.0.
  • Amazon Cognito User Pools provide a secure user directory that scales to hundreds of millions of users.
  • You can associate multiple OpenID Connect providers to a single cognito identity pool.
  • JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. http://jwt.io allows you to decode, verify and generate JWT.
  • The AWS Security Token Service (STS) is a web service that enables you to request temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) users or for users that you authenticate (federated users).
  • Free tier limits for AWS Cognito and Okta are fairly good.
  • Amazon Cognito Identity SDK for JavaScript: https://github.com/amazon-archives/amazon-cognito-identity-js This SDK was discontinued around 2018, and aws-amplify is the latest SDK.

AWS SDK

AWS php SDK

require 'vendor/autoload.php';

use Aws\Common\Aws;
use Aws\S3\Exception\S3Exception;

// Instantiate an S3 client
$aws = Aws::factory('/path/to/config.php');
$s3 = $aws->get('s3');


try {
    $s3->upload('my-bucket', 'my-object', fopen('/path/to/file', 'r'),
          'public-read');
} catch (S3Exception $e) {
    echo "There was an error uploading the file.\n";
}

Javascript AWS SDK

npm install aws-sdk@2.0.6

Serverless Frameworks

There are many abstractions built on top of cloud providers to make this easier :

  • the Serverless Framework
  • Terraform
  • Serverless Application Model (SAM)
  • AWS Amplify

AWS Serverless Express

Run serverless applications and REST APIs using your existing Node.js application framework, on top of AWS Lambda and Amazon API Gateway. The sample provided allows you to easily build serverless web applications/services and RESTful APIs using the Express framework.

AWS Amplify

AWS Amplify is a JavaScript library for frontend and mobile developers building cloud-enabled applications.

Our default implementation works with Amazon Web Services (AWS), but AWS Amplify is designed to be open and pluggable for any custom backend or service.

Synopsis:

npm install aws-amplify --save

npm install @aws-amplify/auth --save   # Only if you want only specific module.

# If you are developing a React app ...
npm install aws-amplify-react --save
# npx - Execute command from npm modules.
npx create-react-app amplify-web-app

cd amplify-web-app

yarn add aws-amplify aws-amplify-react
# or
npm install aws-amplify aws-amplify-react

npm install -g @aws-amplify/cli

# Setup a new AWS user. ????

amplify configure

# Initializing a New AWS Amplify Project
amplify init

# Note the .amplifyrc file and ./ampify/ dir created in the root directory
# of our React project. These files hold configuration info about our Amplify
# project, and we don't need to touch them at all for now.

amplify add auth

# Run amplify push to create the new service in our account:
amplify push


# Once the service has been created, you can see this at 
# https://console.aws.amazon.com/cognito/users/ 

# Also view all enabled services by  ...
amplify status

# Notice a new file that was created: aws-exports.js in the root folder 
# of the React app. You will not need to edit this file.

# Prepare your App to set up authentication shortly later ...
# Modify your react app index.js to call Amplify.configure()

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

# Using the withAuthenticator Higher-Order Component

# In App.js, import the withAuthenticator HOC at the top of the file:
import { withAuthenticator } from 'aws-amplify-react'
....
# And, at the bottom, update the export statement  ...
export default withAuthenticator(App)

# Testing the Authentication Flow
# Now, we can run the app and should see a sign-in screen:

# To include Sign out option ....
export default withAuthenticator(App, { includeGreetings: true })

# Note that we can also use the Auth class directly to sign users out:
import { Auth } from 'aws-amplify'

// Sign the user out
await Auth.signOut()

# Using the Auth Class
# We can also use the Auth class to manually manage users. Auth has over 30
# available methods including signUp, signIn, confirmSignUp, confirmSignIn,
# forgotPassword, and resendSignUp.

# Storage With Amazon S3

amplify add storage

# Next, you'll be prompted to supply some configuration details.

# Run amplify push to create the new resources (S3, etc) in our account:
amplify push

# Store javascript code in S3 bucket.

import { Storage } from 'aws-amplify'

// create function to work with Storage
addToStorage = () => {
  Storage.put('javascript/MyReactComponent.js', `
    import React from 'react'
    const App = () => (
      <p>Hello World</p>
    )
    export default App
  `)
    .then (result => {
      console.log('result: ', result)
    })
    .catch(err => console.log('error: ', err));
}

# To deploy and host your app on AWS, we can use the hosting category.

amplify add hosting

# Again, you'll be prompted to supply some configuration options.

# Now, everything is set up, and we can publish the app:

amplify publish
amplify remove auth
amplify push

amplify status

FAQ

AWS Cloudformation

You create a template that describes all the AWS resources that you want (like Amazon EC2 instances or Amazon RDS DB instances), and AWS CloudFormation takes care of provisioning and configuring those resources for you.

Authentication Services

  • Authentication Services: Auth0, AWS Cognito
  • Auth0 http://auth0.com started with a BaaS product that implemented many facets of user management, and subsequently created the companion FaaS service Webtask http://webtask.io

Case Study: Pizzeria Online

Serverless with Claudia, a Manning publication book deals with this case study.

  • After an API request is routed, it is passed to another container with the business layer service to be processed.

  • For your Pizza API, a sensible solution is to have one unit for processing pizzas and orders, one for handling payments, one for handling chatbot functionality, and one for processing images and files.

  • The size of each unit depends on your preferences. A unit can be as small as a single function or as large as a monolithic application.

  • The most complex parts of a serverless application in AWS are deployment and function configuration. Claudia helps with that. The serverless.com is another alternative to Claudia.

  • Claudia acts as a command-line tool, and it allows you to create and update your functions from the terminal. But the Claudia ecosystem comes with two other useful Node.js libraries: Claudia API Builder allows you to create the API on API Gateway, and Claudia Bot Builder allows you to create chatbots for many messaging platforms.

  • As opposed to Claudia, which is a client-side tool never deployed to AWS, API Builder and Bot Builder are always deployed to AWS Lambda.

  • Here is the list of features we cover for the initial API:

    Listing all pizzas
    Retrieving the pizza orders
    Creating a pizza order
    Updating a pizza order
    Canceling a pizza order
    

These features are all small and simple; therefore, you will implement them in a single Lambda function.