|
| 1 | +# Streaming Lambda function |
| 2 | + |
| 3 | +You can configure your Lambda function to stream response payloads back to clients. Response streaming can benefit latency sensitive applications by improving time to first byte (TTFB) performance. This is because you can send partial responses back to the client as they become available. Additionally, you can use response streaming to build functions that return larger payloads. Response stream payloads have a soft limit of 20 MB as compared to the 6 MB limit for buffered responses. Streaming a response also means that your function doesn’t need to fit the entire response in memory. For very large responses, this can reduce the amount of memory you need to configure for your function. |
| 4 | + |
| 5 | +Streaming responses incurs a cost. For more information, see [AWS Lambda Pricing](https://aws.amazon.com/lambda/pricing/). |
| 6 | + |
| 7 | +You can stream responses through [Lambda function URLs](https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html), the AWS SDK, or using the Lambda [InvokeWithResponseStream](https://docs.aws.amazon.com/lambda/latest/dg/API_InvokeWithResponseStream.html) API. In this example, we create an authenticated Lambda function URL. |
| 8 | + |
| 9 | + |
| 10 | +## Code |
| 11 | + |
| 12 | +The sample code creates a `SendNumbersWithPause` struct that conforms to the `StreamingLambdaHandler` protocol provided by the Swift AWS Lambda Runtime. |
| 13 | + |
| 14 | +The `handle(...)` method of this protocol receives incoming events as a Swift NIO `ByteBuffer` and returns the output as a `ByteBuffer`. |
| 15 | + |
| 16 | +The response is streamed through the `LambdaResponseStreamWriter`, which is passed as an argument in the `handle` function. The code calls the `write(_:)` function of the `LambdaResponseStreamWriter` with partial data repeatedly written before |
| 17 | +finally closing the response stream by calling `finish()`. Developers can also choose to return the entire output and not |
| 18 | +stream the response by calling `writeAndFinish(_:)`. |
| 19 | + |
| 20 | +An error is thrown if `finish()` is called multiple times or if it is called after having called `writeAndFinish(_:)`. |
| 21 | + |
| 22 | +The `handle(...)` method is marked as `mutating` to allow handlers to be implemented with a `struct`. |
| 23 | + |
| 24 | +Once the struct is created and the `handle(...)` method is defined, the sample code creates a `LambdaRuntime` struct and initializes it with the handler just created. Then, the code calls `run()` to start the interaction with the AWS Lambda control plane. |
| 25 | + |
| 26 | +## Build & Package |
| 27 | + |
| 28 | +To build & archive the package, type the following commands. |
| 29 | + |
| 30 | +```bash |
| 31 | +swift package archive --allow-network-connections docker |
| 32 | +``` |
| 33 | + |
| 34 | +If there is no error, there is a ZIP file ready to deploy. |
| 35 | +The ZIP file is located at `.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/StreamingNumbers/StreamingNumbers.zip` |
| 36 | + |
| 37 | +## Deploy with the AWS CLI |
| 38 | + |
| 39 | +Here is how to deploy using the `aws` command line. |
| 40 | + |
| 41 | +### Step 1: Create the function |
| 42 | + |
| 43 | +```bash |
| 44 | +# Replace with your AWS Account ID |
| 45 | +AWS_ACCOUNT_ID=012345678901 |
| 46 | +aws lambda create-function \ |
| 47 | +--function-name StreamingNumbers \ |
| 48 | +--zip-file fileb://.build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/StreamingNumbers/StreamingNumbers.zip \ |
| 49 | +--runtime provided.al2 \ |
| 50 | +--handler provided \ |
| 51 | +--architectures arm64 \ |
| 52 | +--role arn:aws:iam::${AWS_ACCOUNT_ID}:role/lambda_basic_execution \ |
| 53 | +--timeout 15 |
| 54 | +``` |
| 55 | + |
| 56 | +> [!IMPORTANT] |
| 57 | +> The timeout value must be bigger than the time it takes for your function to stream its output. Otherwise, the Lambda control plane will terminate the execution environment before your code has a chance to finish writing the stream. Here, the sample function stream responses during 10 seconds and we set the timeout for 15 seconds. |
| 58 | +
|
| 59 | +The `--architectures` flag is only required when you build the binary on an Apple Silicon machine (Apple M1 or more recent). It defaults to `x64`. |
| 60 | + |
| 61 | +Be sure to set `AWS_ACCOUNT_ID` with your actual AWS account ID (for example: 012345678901). |
| 62 | + |
| 63 | +### Step2: Give permission to invoke that function through an URL |
| 64 | + |
| 65 | +Anyone with a valid signature from your AWS account will have permission to invoke the function through its URL. |
| 66 | + |
| 67 | +```bash |
| 68 | +aws lambda add-permission \ |
| 69 | + --function-name StreamingNumbers \ |
| 70 | + --action lambda:InvokeFunctionUrl \ |
| 71 | + --principal ${AWS_ACCOUNT_ID} \ |
| 72 | + --function-url-auth-type AWS_IAM \ |
| 73 | + --statement-id allowURL |
| 74 | +``` |
| 75 | + |
| 76 | +### Step3: Create the URL |
| 77 | + |
| 78 | +This creates [a URL with IAM authentication](https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html). Only calls with a valid signature will be authorized. |
| 79 | + |
| 80 | +```bash |
| 81 | +aws lambda create-function-url-config \ |
| 82 | + --function-name StreamingNumbers \ |
| 83 | + --auth-type AWS_IAM \ |
| 84 | + --invoke-mode RESPONSE_STREAM |
| 85 | +``` |
| 86 | +This calls return various information, including the URL to invoke your function. |
| 87 | + |
| 88 | +```json |
| 89 | +{ |
| 90 | + "FunctionUrl": "https://ul3nf4dogmgyr7ffl5r5rs22640fwocc.lambda-url.us-east-1.on.aws/", |
| 91 | + "FunctionArn": "arn:aws:lambda:us-east-1:012345678901:function:StreamingNumbers", |
| 92 | + "AuthType": "AWS_IAM", |
| 93 | + "CreationTime": "2024-10-22T07:57:23.112599Z", |
| 94 | + "InvokeMode": "RESPONSE_STREAM" |
| 95 | +} |
| 96 | +``` |
| 97 | + |
| 98 | +### Invoke your Lambda function |
| 99 | + |
| 100 | +To invoke the Lambda function, use `curl` with the AWS Sigv4 option to generate the signature. |
| 101 | + |
| 102 | +Read the [AWS Credentials and Signature](../README.md/#AWS-Credentials-and-Signature) section for more details about the AWS Sigv4 protocol and how to obtain AWS credentials. |
| 103 | + |
| 104 | +When you have the `aws` command line installed and configured, you will find the credentials in the `~/.aws/credentials` file. |
| 105 | + |
| 106 | +```bash |
| 107 | +URL=https://ul3nf4dogmgyr7ffl5r5rs22640fwocc.lambda-url.us-east-1.on.aws/ |
| 108 | +REGION=us-east-1 |
| 109 | +ACCESS_KEY=AK... |
| 110 | +SECRET_KEY=... |
| 111 | +AWS_SESSION_TOKEN=... |
| 112 | + |
| 113 | +curl "$URL" \ |
| 114 | + --user "${ACCESS_KEY}":"${SECRET_KEY}" \ |
| 115 | + --aws-sigv4 "aws:amz:${REGION}:lambda" \ |
| 116 | + -H "x-amz-security-token: ${AWS_SESSION_TOKEN}" \ |
| 117 | + --no-buffer |
| 118 | +``` |
| 119 | + |
| 120 | +Note that there is no payload required for this example. |
| 121 | + |
| 122 | +This should output the following result, with a one-second delay between each numbers. |
| 123 | + |
| 124 | +``` |
| 125 | +1 |
| 126 | +2 |
| 127 | +3 |
| 128 | +4 |
| 129 | +5 |
| 130 | +6 |
| 131 | +7 |
| 132 | +8 |
| 133 | +9 |
| 134 | +10 |
| 135 | +``` |
| 136 | + |
| 137 | +### Undeploy |
| 138 | + |
| 139 | +When done testing, you can delete the Lambda function with this command. |
| 140 | + |
| 141 | +```bash |
| 142 | +aws lambda delete-function --function-name StreamingNumbers |
| 143 | +``` |
| 144 | + |
| 145 | +## Deploy with AWS SAM |
| 146 | + |
| 147 | +Alternatively, you can use [AWS SAM](https://aws.amazon.com/serverless/sam/) to deploy the Lambda function. |
| 148 | + |
| 149 | +**Prerequisites** : Install the [SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) |
| 150 | + |
| 151 | +### SAM Template |
| 152 | + |
| 153 | +The template file is provided as part of the example in the `template.yaml` file. It defines a Lambda function based on the binary ZIP file. It creates the function url with IAM authentication and sets the function timeout to 15 seconds. |
| 154 | + |
| 155 | +```yaml |
| 156 | +AWSTemplateFormatVersion: '2010-09-09' |
| 157 | +Transform: AWS::Serverless-2016-10-31 |
| 158 | +Description: SAM Template for StreamingLambda Example |
| 159 | + |
| 160 | +Resources: |
| 161 | + # Lambda function |
| 162 | + StreamingNumbers: |
| 163 | + Type: AWS::Serverless::Function |
| 164 | + Properties: |
| 165 | + CodeUri: .build/plugins/AWSLambdaPackager/outputs/AWSLambdaPackager/StreamingNumbers/StreamingNumbers.zip |
| 166 | + Timeout: 15 |
| 167 | + Handler: swift.bootstrap # ignored by the Swift runtime |
| 168 | + Runtime: provided.al2 |
| 169 | + MemorySize: 128 |
| 170 | + Architectures: |
| 171 | + - arm64 |
| 172 | + FunctionUrlConfig: |
| 173 | + AuthType: AWS_IAM |
| 174 | + InvokeMode: RESPONSE_STREAM |
| 175 | + |
| 176 | +Outputs: |
| 177 | + # print Lambda function URL |
| 178 | + LambdaURL: |
| 179 | + Description: Lambda URL |
| 180 | + Value: !GetAtt StreamingNumbersUrl.FunctionUrl |
| 181 | +``` |
| 182 | +
|
| 183 | +### Deploy with SAM |
| 184 | +
|
| 185 | +```bash |
| 186 | +sam deploy \ |
| 187 | +--resolve-s3 \ |
| 188 | +--template-file template.yaml \ |
| 189 | +--stack-name StreamingNumbers \ |
| 190 | +--capabilities CAPABILITY_IAM |
| 191 | +``` |
| 192 | + |
| 193 | +The URL of the function is provided as part of the output. |
| 194 | + |
| 195 | +``` |
| 196 | +CloudFormation outputs from deployed stack |
| 197 | +----------------------------------------------------------------------------------------------------------------------------- |
| 198 | +Outputs |
| 199 | +----------------------------------------------------------------------------------------------------------------------------- |
| 200 | +Key LambdaURL |
| 201 | +Description Lambda URL |
| 202 | +Value https://gaudpin2zjqizfujfnqxstnv6u0czrfu.lambda-url.us-east-1.on.aws/ |
| 203 | +----------------------------------------------------------------------------------------------------------------------------- |
| 204 | +``` |
| 205 | + |
| 206 | +Once the function is deployed, you can invoke it with `curl`, similarly to what you did when deploying with the AWS CLI. |
| 207 | + |
| 208 | +```bash |
| 209 | +curl "$URL" \ |
| 210 | + --user "$ACCESS_KEY":"$SECRET_KEY" \ |
| 211 | + --aws-sigv4 "aws:amz:${REGION}:lambda" \ |
| 212 | + -H "x-amz-security-token: $AWS_SESSION_TOKEN" \ |
| 213 | + --no-buffer |
| 214 | +``` |
| 215 | + |
| 216 | +### Undeploy with SAM |
| 217 | + |
| 218 | +When done testing, you can delete the infrastructure with this command. |
| 219 | + |
| 220 | +```bash |
| 221 | +sam delete |
| 222 | +``` |
0 commit comments