|
| 1 | +--- |
| 2 | +layout: pattern |
| 3 | +title: serverless |
| 4 | +folder: serverless |
| 5 | +permalink: /patterns/serverless/ |
| 6 | +categories: Architectural |
| 7 | +tags: |
| 8 | + - Java |
| 9 | + - Difficulty-Intermediate |
| 10 | +--- |
| 11 | + |
| 12 | +## Serverless |
| 13 | + |
| 14 | +Serverless eliminates the need to plan for infrastructure and let's you focus on your |
| 15 | +application. |
| 16 | + |
| 17 | +Following are optimization katas you should be aware of while building a serverless |
| 18 | +applications |
| 19 | + |
| 20 | +* The Lean function |
| 21 | + * Concise logic - Use functions to transform, not transport (utilize some of the |
| 22 | + integration available from the provider to transport), and make sure you read only |
| 23 | + what you need |
| 24 | + * Efficient/single purpose code - avoid conditional/routing logic and break down |
| 25 | + into individual functions, avoid "fat"/monolithic functions and control the |
| 26 | + dependencies in the function deployment package to reduce the load time for your |
| 27 | + function |
| 28 | + * ephemeral environment - Utilize container start for expensive initializations |
| 29 | +* Eventful Invocations |
| 30 | + * Succinct payloads - Scrutinize the event as much as possible, and watch for |
| 31 | + payload constraints (async - 128K) |
| 32 | + * resilient routing - Understand retry policies and leverage dead letter queues |
| 33 | + (SQS or SNS for replays) and remember retries count as invocations |
| 34 | + * concurrent execution - lambda thinks of it's scale in terms of concurrency and |
| 35 | + its not request based/duration based. Lambda will spin up the number of instances |
| 36 | + based on the request. |
| 37 | +* Coordinated calls |
| 38 | + * Decoupled via APIs - best practice to setup your application is to have API's as |
| 39 | + contracts that ensures separation of concerns |
| 40 | + * scale-matched downstream - make sure when Lambda is calling downstream |
| 41 | + components, you are matching scale configuration to it (by specifying max |
| 42 | + concurrency based on downstream services) |
| 43 | + * secured - Always ask a question, do I need a VPC? |
| 44 | +* Serviceful operations |
| 45 | + * Automated - use automated tools to manage and maintain the stack |
| 46 | + * monitored applications - use monitoring services to get holistic view of your |
| 47 | + serverless applications |
| 48 | + |
| 49 | +## Intent |
| 50 | + |
| 51 | +Whether to reduce your infrastructure costs, shrink the time you spend on ops tasks, |
| 52 | +simplify your deployment processes, reach infinite scalability, serverless cuts time |
| 53 | +to market in half. |
| 54 | + |
| 55 | +## Explanation |
| 56 | + |
| 57 | +Serverless computing is a cloud computing execution model in which the cloud provider |
| 58 | +dynamically manages the allocation of machine resources. Pricing is based on the |
| 59 | +actual amount of resources consumed by an application, rather than on pre-purchased |
| 60 | +units of capacity. |
| 61 | + |
| 62 | +## Serverless framework |
| 63 | + |
| 64 | +[Serverless](https://serverless.com/) is a toolkit for deploying and operating serverless architectures. |
| 65 | + |
| 66 | +## (Function as a Service or "FaaS") |
| 67 | + |
| 68 | +The term ‘Serverless’ is confusing since with such applications there are both server |
| 69 | +hardware and server processes running somewhere, but the difference to normal |
| 70 | +approaches is that the organization building and supporting a ‘Serverless’ application |
| 71 | + is not looking after the hardware or the processes - they are outsourcing this to a vendor. |
| 72 | + |
| 73 | +Some of the Serverless Cloud Providers are |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | +... |
| 83 | + |
| 84 | +Anything that triggers an Lambda Function to execute is regarded by the Framework as |
| 85 | +an Event. Most of the Serverless Cloud Providers support following Events |
| 86 | +- Http |
| 87 | +- PubSub Events |
| 88 | +- scheduled |
| 89 | + |
| 90 | +AWS supports processing event generated from AWS Services (S3/Cloudwatch/etc) and |
| 91 | +using aws as a compute engine is our first choice. |
| 92 | + |
| 93 | +## (Backend as a Service or "BaaS") |
| 94 | +This example creates a backend for ‘persons’ collection which uses DynamoDB NoSQL |
| 95 | +database service also provided by Amazon. |
| 96 | + |
| 97 | +## AWS lambda function implementation |
| 98 | + |
| 99 | +[AWS Lambda SDK](https://aws.amazon.com/sdk-for-java/) provides pre-defined interface |
| 100 | +`com.amazonaws.services.lambda.runtime |
| 101 | +.RequestHandler` to implement our lambda function. |
| 102 | + |
| 103 | +```java |
| 104 | +public class LambdaInfoApiHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> { |
| 105 | + |
| 106 | + private static final Logger LOG = Logger.getLogger(LambdaInfoApiHandler.class); |
| 107 | + private static final Integer SUCCESS_STATUS_CODE = 200; |
| 108 | + |
| 109 | + |
| 110 | + @Override |
| 111 | + public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) { |
| 112 | + |
| 113 | + } |
| 114 | +} |
| 115 | +``` |
| 116 | +handleRequest method is where the function code is implemented. Context provides |
| 117 | +useful information about Lambda execution environment. AWS Lambda function needs a |
| 118 | +deployment package. This package is either a .zip or .jar file that contains all the |
| 119 | +dependencies of the function. |
| 120 | + |
| 121 | +`serverless.yml` contains configuration to manage deployments for your functions. |
| 122 | + |
| 123 | +## Run example in local |
| 124 | + |
| 125 | +# Pre-requisites |
| 126 | +* Node.js v6.5.0 or later. |
| 127 | +* Serverless CLI v1.9.0 or later. You can run npm install -g serverless to install it. |
| 128 | +* An AWS account. If you don't already have one, you can sign up for a free trial that includes 1 million free Lambda requests per month. |
| 129 | +* [Set-up](https://serverless.com/framework/docs/providers/aws/guide/credentials/) your Provider Credentials. Watch the video on setting up credentials |
| 130 | + |
| 131 | +# build and deploy |
| 132 | + |
| 133 | +* `cd serverless` |
| 134 | +* `mvn clean package` |
| 135 | +* `serverless deploy --stage=dev --verbose` |
| 136 | + |
| 137 | +Based on the configuration in `serverless.yml` serverless framework creates following |
| 138 | +resources |
| 139 | +* CloudFormation stack for S3 (ServerlessDeploymentBucket) |
| 140 | +* IAM Role (IamRoleLambdaExecution) |
| 141 | +* CloudWatch (log groups) |
| 142 | +* API Gateway (ApiGatewayRestApi) |
| 143 | +* Lambda function |
| 144 | +* DynamoDB collection |
| 145 | + |
| 146 | +The command will print out Stack Outputs which looks something like this |
| 147 | + |
| 148 | +```yaml |
| 149 | +endpoints: |
| 150 | + GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/info |
| 151 | + POST - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person |
| 152 | + GET - https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person/{id} |
| 153 | + |
| 154 | +``` |
| 155 | +
|
| 156 | +```yaml |
| 157 | +CurrentTimeLambdaFunctionQualifiedArn: arn:aws:lambda:us-east-1:xxxxxxxxxxx:function:lambda-info-http-endpoint-dev-currentTime:4 |
| 158 | +ServiceEndpoint: https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev |
| 159 | +ServerlessDeploymentBucketName: lambda-info-http-endpoin-serverlessdeploymentbuck-2u8uz2i7cap2 |
| 160 | +``` |
| 161 | +access the endpoint to invoke the function. |
| 162 | +
|
| 163 | +Use the following cURL commands to test the endpoints |
| 164 | +
|
| 165 | +```cURL |
| 166 | +curl -X GET \ |
| 167 | + https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/info \ |
| 168 | + -H 'cache-control: no-cache' |
| 169 | +``` |
| 170 | +
|
| 171 | +```cURL |
| 172 | +curl -X POST \ |
| 173 | + https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person \ |
| 174 | + -H 'cache-control: no-cache' \ |
| 175 | + -H 'content-type: application/json' \ |
| 176 | + -d '{ |
| 177 | + "firstName": "Thor", |
| 178 | + "lastName": "Odinson", |
| 179 | + "address": { |
| 180 | + "addressLineOne": "1 Odin ln", |
| 181 | + "addressLineTwo": "100", |
| 182 | + "city": "Asgard", |
| 183 | + "state": "country of the Gods", |
| 184 | + "zipCode": "00001" |
| 185 | + } |
| 186 | +}' |
| 187 | +``` |
| 188 | + |
| 189 | +```cURL |
| 190 | +curl -X GET \ |
| 191 | + https://xxxxxxxxx.execute-api.us-east-1.amazonaws.com/dev/api/person/{id} \ |
| 192 | + -H 'cache-control: no-cache' |
| 193 | +``` |
| 194 | + |
| 195 | +## Credits |
| 196 | + |
| 197 | +* [serverless docs](https://serverless.com/framework/docs/) |
| 198 | +* [Serverless Architectures](https://martinfowler.com/articles/serverless.html) |
| 199 | +* [Serverless Black Belt](https://youtu.be/oQFORsso2go) |
0 commit comments