THINKING SERVERLESS

pedrocosta.eu

pedrocosta.eu/shameless-promotion
πŸ‘‰ Last year of MIEIC at FEUP and currently at UPM in Madrid

πŸ‘‰ Technical Researcher Internship, Amazon Web Services, Summer 2018

πŸ‘‰ AWS Certified Solutions Architect - Associate

πŸ‘‰ Software Developer Internship, Bitmaker, Summer 2017 

πŸ‘‰ Member of NIAEFEUP and treasurer of ENEI 2018

πŸ‘‰ Member of the Board of Regents of FEUP

Agenda

  1. RoadmapΒ 
  2. What's Serverless
  3. How It Works
  4. Best Practices
  5. Pros & Cons
  6. Use Cases

ROADMAP

Should we order more servers?

~ 1996

❓ How many servers do we need

❓ How much memory would we need

❓ How much network bandwith do we need

❓ What type and how much processing power

❓ What happens if my servers fails

❓ Who has access to the servers

Let's move infrastructure to the cloud

- 2006

Let's ship it in containers

- 2013

Maybe this microservice can be a function?


- 2014

What is serverless

The essence of the serverless trend is the absence of the server concept during software development

Β 

- AUTH0

Focus on code, not servers

... but there are still servers of course
Serverless = FaaS + BaaS

Key properties of FaaS

πŸ”‘ Independent, server-side, logical functions

πŸ”‘ Stateless

πŸ”‘ Ephemeral

πŸ”‘ Event-triggered

πŸ”‘ Scalable by default

πŸ”‘ Fully managed by a Cloud vendor

How it Works

event β†’ 𝑓

"IF this THEN that" model

If   __________________________
then __________________________

A new CSV file is saved in the object storage

Β 

Β  Β  Β  Process it and save it in the DB

HTTP request: GET /posts

Β 

Retrieve posts from DB and return a JSON

It's 2 AM

Β 

Scrape weather forecast for next days

Example of events on aws

Anatomy of a Node.js lambda on AWS

exports.handler = async (event, context) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!')
    };
    return response;
};
from chalice import Chalice, Response
import boto3
import os

dynamodb = boto3.resource('dynamodb')
sid = shortid.ShortId()
app = Chalice(app_name='url-shortener')

@app.route('/{code}', cors = True)
def get_original_url(code):
    table = dynamodb.Table('url-shortener')
    try:
        response = table.get_item(
            Key={
                'code': code
            }
        )
        item = response['Item']
    except Exception as e:
        return Response(
            body='',
            status_code=302,
            headers={
                'Location': os.environ['BASE_URL']
            }
        )
    
    return Response(
        body='',
        status_code=302,
        headers={
            'Location': response['Item']['originalUrl']
        }
    )
Serverless URL shortner: pedrocosta.eu/sinf

Serverless is not just lambda!

Best Practices & Tips

Monitor your APIs...

...AND UNDERSTAND THE MOST COST EFFECTIVE RELATION

Each function should do only one thing

Use messages and queuesΒ 

dealing with Cold Starts

πŸ”„ Instantiate AWS clients and database clients outside the scope of the handler to take advantage of container re-use


⏰ Schedule with CloudWatch Events for warmth

import sys 
import logging 
import rds_config 
import pymysql 

rds_host = "rds-instance" 
db_name = rds_config.db_name 
try: 
    conn = pymysql.connect(...)
except: 
    logger.error("ERROR: ..")

def handler(event, context): 
    with conn.cursor() as cur:

cold start

Pros & Cons

πŸ‘ Pros

πŸ‘¨β€πŸ’» Focus on business logic, not on infrastructure

🐎 Scales with usage, auto-scaling

πŸ’° Never pay for idle, pay as you go model

πŸ†™ Built-in High-Availability and Disaster Recovery

πŸ‘Ž CONS

🧐 No live debbuging

πŸ›  Lacking local development & testing tools

β›“ Service/Functions orchestration

❄️ Cold starts

Use Cases

data processing

REAL-TIME FILE PROCESSING

The Seattle Times uses AWS Lambda to resize images for viewing on different devices such as desktop computers, tablets, and smartphones.

REAL-TIME STREAM PROCESSING

Localytics processes billions of data points in real-time, and uses Lambda to process historical and live data stored in S3 or streamed from Kinesis.

EXTRACT, TRANSFORM, LOAD

Zillow uses Lambda and Kinesis to track a subset of mobile metrics in realtime. With Kinesis and Lambda, we were able to develop and deploy a cost effective solution in two weeks.

backends

IOT BACKENDS

You can build serverless backends using AWS Lambda to handle web, mobile, Internet of Things (IoT), and 3rd party API requests.

Mobile BACKENDS

Bustle runs a serverless backend for its Bustle iOS app and websites using AWS Lambda and Amazon API Gateway. Serverless architectures allow Bustle to never have to deal with infrastructure management, so every engineer can focus on building out new features and innovating. 

Web BACKENDS

By combining AWS Lambda with other AWS services, developers can build powerful web applications that automatically scale up and down and run in a highly available configuration across multiple data centers – with zero administrative effort required for scalability, back-ups or multi-data center redundancy.

Text-to-Speech APp

OBRIGADO πŸ‘‹

me@pedrocosta.eu
Made with Slides.com