vs
Server maintenance is responsibility of user
Server maintenance is responsibility of provider
Serverless is about focusing your efforts on what provides value to users. Upgrading your Linux distro does not provide value to users. Managing your RabbitMQ servers does not provide value to users. Shipping product provides value to users.
That is the serverless maxim: focus on business logic, not servers.
serverless.com
Control
Abstraction
Run code without thinking about servers. Pay only for the compute time you consume.
AWS Lambda
Triggers
Function
Result
File Upload
Database Update
New Message in a Queue
New Commit to Repo
Scheduled Events
HTTP API Call
Your Code
Lambda Runtime
Sandbox
Guest OS
Hypervisor
Host OS
Hardware
Amazon Linux
Node, Python...
Lambda Function
AWS EC2 Metal
Container
const AWS = require('aws-sdk'),
const uuid = require('uuid'),
const documentClient = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback){
const params = {
Item: {
id: uuid.v1(),
firstName: event.firstName,
lastName: event.lastName,
},
TableName: 'people'
};
documentClient.put(params, function(err, data){
callback(err, data);
});
}
Use permanent data stores like databases to store state
exports.handler = function(event, context, callback) {
const foo = event.foo;
const bar = event.bar;
const result = myLambdaFunction (foo, bar);
callback(null, result);
}
function myLambdaFunction (foo, bar) {
// your logic here
}
Separate your business logic from vendor-specific handler
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
database : 'my_db'
});
connection.on('error', function(err) { connection.connect(); });
exports.handler = function(event, context, callback){
connection.query('SELECT * FROM people', function (error, results, fields) {
if (error) {
connection.destroy();
callback(error, null);
}
callback(null, results);
});
}
Reuse connections between calls to the same function
A higher memory tier may be more expensive, but the execution time may be shorter
$ npm install -g serverless
$ mkdir serverless-hello-world
$ cd serverless-hello-world
$ sls create --template aws-nodejs
$ npm install serverless-offline --save-dev
## serverless.yml
service: aws-nodejs
## Add these two lines
plugins:
- serverless-offline
provider:
## serverless.yml
functions:
hello:
handler: handler.hello
events: ## Add these four lines to setup the HTTP route
- http:
path: /
method: get
$ sls offline start
Serverless: Starting Offline: dev/us-east-1.
Serverless: Routes for hello:
Serverless: GET /
Serverless: Offline listening on http://localhost:3000
Should be able to:
Endpoint /store should be able to:
Endpoint /diff should be able to: