Chapter 1. Running functions in the cloud
- Understanding why functions can be the primitives of your application
- Getting an overview of AWS Lambda
- Using functions for the back end of your application
- Building event-driven applications with functions
- Calling functions from a client
Dropbox changed the way we use digital storage and share files with each other,
Spotify changed the way we buy and listen to music.
advantages of cloud computing is that it frees developers from spending their time on tasks that
don’t add real value to their work
don’t add real value to their work
managing and scaling the infrastructure, patching the operating system (OS),
or maintaining the software stack used
or maintaining the software stack used
cloud computing to provide the infrastructure for your application, in the form of virtual servers,
storage, network, load balancers
storage, network, load balancers
use cloud computing services that abstract from the underlying infrastructure implementation,
acting like a platform on top of which you deploy your own customizations.
acting like a platform on top of which you deploy your own customizations.
you can have services that provide you with a database
AWS Lambda, the abstraction layer is set higher, allowing developers to upload their code
grouped in functions, and letting those functions be executed by the platform
grouped in functions, and letting those functions be executed by the platform
you don’t have to manage the programming framework, the OS, or the availability and scalability.
functions can be invoked directly or can subscribe to events generated by other resources
subscribe a function to a resource such as a file repository or a database,
the function is automatically executed when something happens in that resource
the function is automatically executed when something happens in that resource
file has been uploaded or a database item has been modified, an AWS Lambda function
can react to those changes and do something with the new file or the updated data
can react to those changes and do something with the new file or the updated data
Using multiple functions together, some of them called directly from a user device,
such as a smartphone, and other functions subscribed to multiple repositories,
such as a file share and a database, you can build a complete event-driven application
such as a file share and a database, you can build a complete event-driven application
the AWS software development kits (SDKs), which are available for multiple platforms.
1.1. Introducing AWS Lambda
AWS Lambda give your logic, grouped in functions, and the service executes the functions,
Functions are executed in containers.
Containers are a server virtualization method where the kernel of the OS implements multiple
isolated environments.
isolated environments.
A container is a standard unit of software that packages up code and all its
dependencies so the application runs quickly and reliably from one computing
environment to another.
dependencies so the application runs quickly and reliably from one computing
environment to another.
AWS Lambda, physical servers still execute the code,
don’t need to spend time managing them, it’s common to define this kind of approach as serverless.
new function with AWS Lambda, you choose a function name, create your code,
and specify the configuration of the execution environment
and specify the configuration of the execution environment
- maximum memory size that can be used by the function
- A timeout after which the function is terminate
- A role that describes what the function can do
Lambda implements the execution of those functions with an efficient use of the underlying compute
resources
resources
efficient use of the underlying compute resources that allows for an interesting and innovative cost
model.
model.
- the number of invocations
- The hundreds of milliseconds of execution time of all invocations
execution time costs grow linearly with the memory: if you double the memory and
keep the execution time the same, you double that part of the cost.
- The first one million invocations
- The first 400,000 seconds of execution time with 1 GB of memory
call a function with AWS Lambda, you provide an event and a context in the input
event is the way to send input parameters for your function and is expressed using JSON syntax.
JavaScript Object Notation (JSON) (/ˈdʒeɪsən/ "jay-son", /dʒeɪˈsɒn/)[1] is
an open-standard file format that uses human-readable text to transmit data objects
consisting of attribute–value pairs and array data types
an open-standard file format that uses human-readable text to transmit data objects
consisting of attribute–value pairs and array data types
context is used by the service to describe the execution environment and how the event is received
and processed.
and processed.
Functions can be called synchronously and return a result
exports.handler = (event, context, callback) => {
var result = event.value1 + event.value2;
callback(null, result);
};
Giving as input to those functions an event with the following JSON payload would
give back a result of 30:
{
"value1": 10,
"value2": 20
}
"value1": 10,
"value2": 20
}
synchronously. In this case the call returns immediately and no result is given back,
while the function is continuing its work (figure 1.3). I use the term “asynchronous”
to indicate this kind of invocation in the book,
When a Lambda function terminates, no session information is retained by the AWS Lambda service
. This kind of interaction with a server is usually defined as stateless.
. This kind of interaction with a server is usually defined as stateless.
exports.handler = function(event, context) {
console.log(event.message);
context.done();
};
{
"message": "This message is being logged!"
}
console.log(event.message);
context.done();
};
{
"message": "This message is being logged!"
}
integration of AWS Lambda with Amazon CloudWatch Logs. Functions are executed without
a default output device (in what is usually called a headless environment) and a default logging
capability is given for each AWS Lambda runtime to ship the logs to CloudWatch.
capability is given for each AWS Lambda runtime to ship the logs to CloudWatch.
mobile application uploads a new high-resolution picture to a file store, a function can be triggered
with the location of the new file in its input as part of the event.
with the location of the new file in its input as part of the event.
Functions as your back end
mobile app running on the client device of the end user, but you’d probably keep
part of the logic and status outside of the mobile app.
online multiplayer game wouldn’t allow a player to go to the next level without validating
that the player has completed the current level.
that the player has completed the current level.
developing client/server applications
keep part of the logic outside of the clients
- sharing, because the information must be used by multiple users of the application
- Security, because the data can be changed if specific requirements are satisfied
- Access to computing resources or storage capacity not available on a client device
External logic required by a front end application as the back end
can have your web page or your mobile application call one or more
AWS Lambda functions that implement the logic you need
AWS Lambda functions that implement the logic you need
check the authentication and authorization of end users accessing your back end.
control what a function can do, and on which resources.
AWS Identity and Access Management policies and roles.
tailor security permissions specifically for each function
A single back end for everything
Lambda functions to expose the back end logic of our applications
flow and interactions of an application that can be used via a web browser or a mobile app
users of your application can use different devices, depending on what you decide to support
multiple ways to interact with your application,
- web interface,
- mobile app,
- public application programming interfaces (APIs)
interfaces used by those different devices to communicate with the back end,
we discover that they aren’t always the same:
we discover that they aren’t always the same:
split the back end data between structured content that can go in one or more databases and
unstructured content, such as files
unstructured content, such as files
1. Adding a web interface to file repository it becomes a standalone resource that
clients can directly access
clients can directly access
2. Moving part of the logic into the web browser using a JavaScript client application
and bringing it on par with the logic of the mobile app
and bringing it on par with the logic of the mobile app
back end logic, we now have a single architecture for all clients and the same interactions
and data flows for all the consuming applications.
and data flows for all the consuming applications.
decoupled the front end implementations, which could be different depending on the supported client devices, from the back end architecture
API calls takes input parameters, does something in the back end, and returns a result.
Each API call is a function exposed by the back end that you can implement using AWS Lambda.
Event-driven applications
calling them as back end APIs from the client application
subscribe a function to receive events from another resource
subscriptions, you can change the internal behavior of the back end so that it can react not only
direct requests from client applications
direct requests from client applications
interaction is described by the relationship between the resources involved.
back end becomes a distributed application
Applications designed to react to internal and external events without a centralized workflow to
coordinate processing on the resources are event-driven applications.
coordinate processing on the resources are event-driven applications.
media-sharing application, where the users can upload pictures from their client, a web browser
or a mobile app,
or a mobile app,
database to handle user profiles
low users to upload new multimedia content
Metadata is "data [information] that provides information about other data".[1]
Many distinct types of metadata exist, among these descriptive metadata,
structural metadata, administrative metadata[2], reference metadata and statistical metadata[3]
Many distinct types of metadata exist, among these descriptive metadata,
structural metadata, administrative metadata[2], reference metadata and statistical metadata[3]
basic functionalities:
upload new multimedia content (pictures) with its own metadata
users to get specific content (pictures) shared by other users
index of the content a specific user can see
Update content metadata.
Get content metadata to be shown on the client together with the picture thumbnails
owner of the content, a date, a location, and a caption.
- What happens if a user uploads a new piece of content?
- What happens to the index if the user changes the metadata?
- build thumbnails for the pictures to show them as a preview to end users.
- file (picture) is added or updated, you build the new thumbnail and add it back to
- the file repository.If a file (picture) is added or updated, you extract the new metadata
- and update the database (in the content table).
- Whenever the database is updated (user, friendship, or content table), you rebuild the dependent
- precomputed indexes, changing what a user can see.
function is activated when the database is changed directly by end users
when an update is made by another function
both managed by the same subscription, a subscription that describes the relationship among the
resources and the action you need to do when something changes.
resources and the action you need to do when something changes.
mobile push notification service such as the Amazon Simple Notification Service (SNS).
Think about the best way to use that in the back end to notify end users if new or updated content
is available for them.
Think about the best way to use that in the back end to notify end users if new or updated content
is available for them.
1.5. Calling functions from a client
client application interacts with the AWS Lambda functions
function can be invoked synchronously or asynchronously,
Invoke API, AWS applies the standard security checks and requires that the client application
has the right permissions to invoke the function.
has the right permissions to invoke the function.
you need AWS credentials to authenticate, and based on that authentication,
AWS verifies whether those credentials have the right authorization to execute that API call
AWS verifies whether those credentials have the right authorization to execute that API call
use a specific service to manage authentication and authorization in an easy way:
Amazon Cognito.
Amazon Cognito.
Cognito, the client can authenticate using an external social or custom authentication
(such as Facebook or Amazon) and get temporary AWS credentials to invoke the AWS
Lambda functions
(such as Facebook or Amazon) and get temporary AWS credentials to invoke the AWS
Lambda functions
Replace the direct use of the AWS Lambda Invoke API by clients with your own web APIs
that you can build by mapping the access to AWS Lambda functions to more generic
HTTP URLs and verbs.
that you can build by mapping the access to AWS Lambda functions to more generic
HTTP URLs and verbs.
Amazon API Gateway, you can map the access to a specific resource
(the URL of the bookstore or a specific book) with an HTTP verb
(GET, POST, PUT, DELETE, and so on) to the invocation of an AWS Lambda function.
See table 1.1 for a sample configuration.
(the URL of the bookstore or a specific book) with an HTTP verb
(GET, POST, PUT, DELETE, and so on) to the invocation of an AWS Lambda function.
See table 1.1 for a sample configuration.
A sample web API for a bookstore (view table figure)
Resource
|
+
|
HTTP verb
|
→
|
Method (function)
|
/books
|
+
|
GET
|
→
|
GetAllBooksByRange
|
/books
|
+
|
POST
|
→
|
CreateNewBook
|
/books/{id}
|
+
|
GET
|
→
|
GetBookById
|
/books/{id}
|
+
|
PUT
|
→
|
CreateOrUpdateBookById
|
/books/{id}
|
+
|
DELETE
|
→
|
DeleteBookById
|
HTTP GET on the /books resource, you execute a Lambda function (GetAllBooksByRange)
return a list of books.
HTTP POST on the URL, create a book (CreateNewBook function)get the ID of the book
HTTP GET on /books/ID, execute a function (GetBookById) a description
(a representation, according to the REST architecture style) of the book with that specific ID.
Hypertext Transfer Protocol (HTTP) is an application protocol for distributed,
collaborative, hypermedia information systems.[1] HTTP is the foundation of
data communication for the World Wide Web, where hypertext documents include
hyperlinks to other resources that the user can easily access, for example by a mouse click
or by tapping the screen. HTTP was developed to facilitate hypertext and the World Wide Web.
collaborative, hypermedia information systems.[1] HTTP is the foundation of
data communication for the World Wide Web, where hypertext documents include
hyperlinks to other resources that the user can easily access, for example by a mouse click
or by tapping the screen. HTTP was developed to facilitate hypertext and the World Wide Web.
GET
The GET method requests a representation of the specified resource.
Requests using GET should only retrieve data and should have no other effect.
(This is also true of some other HTTP methods.)[1]
The W3C has published guidance principles on this distinction, saying,
"Web application design should be informed by the above principles, but also by the relevant
limitations."[17] See safe methods below.
POST
The POST method requests that the server accept the entity enclosed in the request as a new
subordinate of the web resource identified by the URI. The data POSTed might be, for example,
an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or
comment thread; a block of data that is the result of submitting a web form to a data-handling
process; or an item to add to a database.[18]
PUT
The PUT method requests that the enclosed entity be stored under the supplied URI.
If the URI refers to an already existing resource, it is modified; if the URI does not point to
an existing resource, then the server can create the resource with that URI.[19]
DELETE
The DELETE method deletes the specified resource.
The GET method requests a representation of the specified resource.
Requests using GET should only retrieve data and should have no other effect.
(This is also true of some other HTTP methods.)[1]
The W3C has published guidance principles on this distinction, saying,
"Web application design should be informed by the above principles, but also by the relevant
limitations."[17] See safe methods below.
POST
The POST method requests that the server accept the entity enclosed in the request as a new
subordinate of the web resource identified by the URI. The data POSTed might be, for example,
an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or
comment thread; a block of data that is the result of submitting a web form to a data-handling
process; or an item to add to a database.[18]
PUT
The PUT method requests that the enclosed entity be stored under the supplied URI.
If the URI refers to an already existing resource, it is modified; if the URI does not point to
an existing resource, then the server can create the resource with that URI.[19]
DELETE
The DELETE method deletes the specified resource.
Amazon API Gateway we’re decoupling the client from directly using AWS Lambda, exposing
a clean web API that can be consumed by external services
a clean web API that can be consumed by external services
Amazon API Gateway, we can also give public access to some of our web APIs.
By public access I mean that no credentials are required to access those web APIs.
Because one of the possible HTTP verbs that we can use in configuring an API is GET, and
GET is the default that is used when you type a URL in a web browser, we can use this configuration
to create public websites whose URLs are dynamically served by AWS Lambda functions (figure 1.15).
By public access I mean that no credentials are required to access those web APIs.
Because one of the possible HTTP verbs that we can use in configuring an API is GET, and
GET is the default that is used when you type a URL in a web browser, we can use this configuration
to create public websites whose URLs are dynamically served by AWS Lambda functions (figure 1.15).
No comments:
Post a Comment