Address https://github.com/awslabs/swift-aws-lambda-runtime/issues/605
NEW Lambda Tenant isolation capability:
https://docs.aws.amazon.com/lambda/latest/dg/tenant-isolation.html
# Add Support for Lambda Tenant Isolation Mode
## Summary
This PR adds support for AWS Lambda's tenant isolation mode to the Swift
AWS Lambda Runtime, enabling developers to build multi-tenant
applications with strict execution environment isolation per tenant.
## Changes
### Runtime Support
- Added `tenantID` property to `LambdaContext` to expose the tenant
identifier
- Extended `InvocationMetadata` to capture the
`Lambda-Runtime-Aws-Tenant-Id` header
- Added `AmazonHeaders.tenantID` constant for the tenant ID header
- Added trace logging for invocation headers to aid debugging
### New Example: MultiTenant
A complete working example demonstrating tenant isolation mode:
- **Request tracking system** that maintains separate counters and
histories per tenant
- **Actor-based storage** (`TenantDataStore`) for thread-safe tenant
data management
- **Immutable data structures** (`TenantData`) following Swift best
practices
- **API Gateway integration** with tenant ID passed via query parameter
- **SAM template** configured with `TenancyConfig.TenantIsolationMode:
PER_TENANT`
- **Comprehensive documentation** covering architecture, deployment,
testing, and best practices
### Testing
- Added unit test for tenant ID extraction from invocation headers
- Integrated MultiTenant example into CI/CD pipeline
### Documentation
The example includes detailed documentation on:
- When to use tenant isolation (user code execution, sensitive data
processing)
- How tenant isolation works (dedicated environments, no cross-tenant
reuse)
- Concurrency limits and scaling considerations
- Pricing implications
- Security best practices
- CloudWatch monitoring with tenant dimensions
## Files Changed
- `Sources/AWSLambdaRuntime/LambdaContext.swift` - Added tenantID
property
- `Sources/AWSLambdaRuntime/ControlPlaneRequest.swift` - Capture tenant
ID from headers
- `Sources/AWSLambdaRuntime/Utils.swift` - Added tenantID header
constant
- `Sources/AWSLambdaRuntime/Lambda.swift` - Pass tenant ID to context
- `Sources/AWSLambdaRuntime/LambdaRuntimeClient+ChannelHandler.swift` -
Added trace logging
- `Tests/AWSLambdaRuntimeTests/InvocationTests.swift` - Added tenant ID
test
- `Examples/MultiTenant/*` - New complete example with SAM template
- `.github/workflows/pull_request.yml` - Added MultiTenant to CI
pipeline
## Testing Instructions
1. Build and deploy the example:
bash
cd Examples/MultiTenant
swift package archive --allow-network-connections docker
sam deploy --guided
2. Test with different tenants:
bash
curl
"https://<api-id>.execute-api.<region>.amazonaws.com/Prod?tenant-id=
alice"
curl
"https://<api-id>.execute-api.<region>.amazonaws.com/Prod?tenant-id=
bob"
3. Verify isolation by checking that each tenant maintains separate
request counts
## Related Documentation
- [AWS Lambda Tenant
Isolation](https://docs.aws.amazon.com/lambda/latest/dg/tenant-isolation.html)
- [AWS Blog: Streamlined Multi-Tenant Application
Development](https://aws.amazon.com/blogs/aws/streamlined-multi-tenant-application-development-with-tenant-isolation-mode-in-aws-lambda/)
---------
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
This PR adds a new example demonstrating how to build a Lambda function
that handles requests from multiple sources (Application Load Balancer
and API Gateway V2) using a single handler.
### What's New
**New Example: `Examples/MultiSourceAPI`**
A Lambda function that:
- Implements `StreamingLambdaHandler` to accept raw `ByteBuffer` events
- Dynamically decodes events as either `ALBTargetGroupRequest` or
`APIGatewayV2Request`
- Returns appropriate responses based on the detected event source
- Demonstrates handling multiple AWS service integrations with a single
function
### Key Features
- **Type-safe event detection**: Uses Swift's `Decodable` to identify
the event source at runtime
- **Streaming response**: Implements `StreamingLambdaHandler` for
efficient response handling
- **Complete deployment**: Includes SAM template with both ALB and API
Gateway V2 infrastructure
- **Production-ready**: Full VPC setup with subnets, security groups,
and load balancer configuration
### Files Added
- `Examples/MultiSourceAPI/Sources/main.swift` - Lambda handler
implementation
- `Examples/MultiSourceAPI/Package.swift` - Swift package configuration
- `Examples/MultiSourceAPI/template.yaml` - SAM deployment template with
ALB and API Gateway V2
- `Examples/MultiSourceAPI/README.md` - Documentation with build,
deploy, and test instructions
- Updated CI to include the new example
### Use Case
This pattern is useful when you want to:
- Expose the same Lambda function through multiple AWS services
- Reduce code duplication by handling similar requests from different
sources
- Maintain a single codebase for multi-channel APIs
---------
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Co-authored-by: Josh Elkins <jbelkins@users.noreply.github.com>
Closing
https://github.com/swift-server/swift-aws-lambda-runtime/issues/584
The LocalServer now queues concurrent `POST /invoke` requests from
testing client applications and ensures that the requests are delivered
to the Lambda Runtime one by one, just like the AWS Lambda Runtime
environment does.
The `Pool` has now two modes : pure FIFO (one element get exactly one
`next()`) and one mode where multiple elements can get pushed and
multiple `next(for requestId:String)` can be called concurrently.
The two modes are needed because invocations are 1:1 (one `POST /invoke`
is always by one matching `GET /next`) but responses are n:n (a response
can have multiple chunks and concurrent invocations can trigger multiple
`next(for requestId: String)`
I made a couple of additional changes while working on this PR
- I moved the `Pool` code in a separate file for improved readability
- I removed an instance of `DispatchTime` that was hiding in the code,
unnoticed until today
- I removed the `async` requirement on `Pool.push(_)` function. This was
not required (thank you @t089 for having reported this)
- I removed the `fatalError()` that was in the `Pool` implementation.
The pool now throws an error when `next()` is invoked concurrently,
making it easier to test.
- I added extensive unit tests to validate the Pool behavior
- I added a test to verify that a rapid succession of client invocations
are correctly queued and return no error
- I moved a `continuation(resume:)` outside of a lock. Generally
speaking, it's a bad idea to resume continuation while owning a lock. I
suspect this is causing a error during test execution when we spawn and
tear down mutliple `Task` very quickly. In some rare occasions, the test
was failing with an invalid assertion in NIO :
`NIOCore/NIOAsyncWriter.swift:177: Fatal error: Deinited NIOAsyncWriter
without calling finish()`
---------
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
- Adjust notice, security reporting, code of conduct, contribution
process to the standard AWS documents
- Adjust GitHub issue templates to AWS standard ones.
- Adjust the license header in all source files
---------
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Apply recommendations in code and documentation
- [CI] restrict permissions to read-all instead of the default write-all
- All examples README.md : add a note about Lambda functions
configuration with improved security and scalability changes for
production environment
- Swift docc documentation: add a note about Lambda functions
configuration with improved security and scalability changes for
production environment
---------
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
This PR adds an APIGateway V1 example, which differs slightly from the
existing [V2
example](https://github.com/swift-server/swift-aws-lambda-runtime/tree/main/Examples/APIGateway).
### Motivation:
While APIGatewayV2 has existed for a while, there are still some
scenarios where V1 is preferable (see [Choose between REST APIs and HTTP
APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html)
for more details). This PR adds a working example for the `Api` endpoint
type.
### Modifications:
Sources/main.swift
- Swapped APIGatewayRequestV2 and APIGatewayResponseV2 for their
unversioned counterparts (aka V1).
template.yaml
- Changed the Events name and corresponding `Type: Api` values.
- Added necessary additional properties to define a `GET` endpoint for
an `Api` endpoint.
Readme.md
- Updated the request and response example outputs.
### Result:
Now, an APIGateway and APIGatewayV1 example exist.
> [!NOTE]
> It is the author's opinion that this new example should technically be
called `APIGateway` and the existing one should be renamed to
`APIGatewayV2` to keep consistent with the request and response type
naming conventions, but this is omitted from this request to be less
disruptive.
All the examples using SAM have a default Lambda runtime environment
memory size of 512Mb.
Lambda functions run in a microVM defined by its memory size. The memory
size influences the CPU power.
(see
https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)
Increasing memory size increases runtime performance but also increase
costs.
As most of our examples are very simple and small functions, 512Mb
memory is not required. This PR reduces Lambda runtime execution
environment to 128Mb to reduce AWS costs.
Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
In preparation for the 2.0.0 GA release,
- Update `.swift-version`, `Package.swift` and all examples'
`package.swift` to Swift 6.2
- Update all references to `2.0.0-beta.3` to `2.0.0`. This includes the
doc and readme, but also the dependencies in the examples
`Package.swift`. This will temporary break the build of the examples,
until we tag v2.0.0. Note the CI will not be affected as its consumes
the local version of the library
- [CI] Use Swift-6.2-noble for all testing tasks
- Reinstate the script to generate the contributors list and update the
list
Make required changed to ensure the library compiles when no traits are
enabled (fix:
https://github.com/swift-server/swift-aws-lambda-runtime/issues/562)
Add an example project that serves as test in the CI
### Motivation:
Recent changes introduced compilation errors when no traits are enabled.
### Modifications:
- `LambdaResponseStreamWriter.writeStatusAndHeaders()` moved to the
`FoundationSupport` directory where all classes and struct depending on
`Encodable` and `Decodable` are located, protected by `#if
FoundationJSONSupport`
- `LambdaRuntime.run()` method when ServiceLifeCycle is disabled in now
public (and therefore can not be `@inlinable` anymore)
- Add an example that disables all traits.
- Add this example to the CI
### Result:
The Library now compiles when no default traits are enabled.
This is flagged `semver/major` because we change the public API
`LambdaRuntime.run()`
Revert streaming codable handler change and propose it as an example
instead of an handler API.
**Motivation:**
I made a mistake when submitting this PR
https://github.com/swift-server/swift-aws-lambda-runtime/pull/532
It provides a Streaming+Codable handler that conveniently allows
developers to write handlers with `Codable` events for streaming
functions.
This is a mistake for three reasons:
- This is the only handler that assumes a Lamba Event structure as
input. I added a minimal `FunctionUrlRequest` and `FunctionURLResponse`
to avoid importing the AWS Lambda Events library. It is the first
handler to be event-specific. I don't think the runtime should introduce
event specific code.
- The handler only works when Lambda functions are exposed through
Function URLs. Streaming functions can also be invoke by API or CLI.
- The handler hides `FunctionURLRequest` details (HTTP headers, query
parameters, etc.) from developers
Developers were unaware they were trading flexibility for convenience
The lack of clear documentation about these limitations led to incorrect
usage patterns and frustrated developers who needed full request control
or were using other invocation methods.
**Modifications:**
- Removed the Streaming+Codable API from the library
- Moved the Streaming+Codable code to an example
- Added prominent warning section in the example README explaining the
limitations
- Clarified when to use Streaming+Codable vs ByteBuffer approaches
- Added decision rule framework to help developers choose the right
approach
**Result:**
The only API provided by the library to use Streaming Lambda functions
is exposing the raw `ByteBuffer` as input, there is no more `Codable`
handler for Streaming functions available in the API. I kept the
`Streaming+Codable` code an example.
After this change, developers have clear guidance on when to use each
streaming approach:
- Use streaming codable for Function URL + JSON payload + no request
details needed
- Use ByteBuffer StreamingLambdaHandler for full control, other
invocation methods, or request metadata access
This prevents misuse of the API and sets proper expectations about the
handler's capabilities and limitations, leading to better developer
experience and fewer integration issues.
### Motivation:
AWS Lambda response streaming now supports a default maximum response
payload size of 200 MB (increased from 20 MB). This update aligns the
documentation with the new AWS limits.
### Modifications:
- Updated readme.md: Changed "soft limit of 20 MB" to "default maximum
response payload size of 200 MB"
- Updated Examples/Streaming/README.md: Same change as above
- Updated terminology to match AWS official documentation
### Result:
Documentation now accurately reflects the current AWS Lambda streaming
response limits, enabling users to understand they can stream up to 200
MB payloads.
Reference:
https://aws.amazon.com/about-aws/whats-new/2025/07/aws-lambda-response-streaming-200-mb-payloads/
Add Hummingbird web framework integration example for AWS Lambda
**Motivation:**
Developers using the Hummingbird web framework need a clear example of
how to integrate it with AWS Lambda. The existing examples focus on
basic Lambda handlers, but don't demonstrate how to use popular Swift
web frameworks like Hummingbird in a serverless context.
**Modifications:**
Added a complete Hummingbird Lambda example in Examples/Hummingbird/
including Package.swift with Hummingbird Lambda dependencies, main.swift
demonstrating router setup with API Gateway V2 integration, SAM template
for deployment, and comprehensive README documentation with build,
deploy, and usage instructions.
**Result:**
Developers can now easily create AWS Lambda functions using the
Hummingbird web framework, with a working example that shows router
configuration, API Gateway integration, and complete deployment workflow
using familiar Hummingbird syntax.
Add user-facing API for Streaming Lambda functions that receives JSON
events
### Motivation:
Streaming Lambda functions developed by developers had no choice but to
implement a handler that receives incoming data as a `ByteBuffer`. While
this is useful for low-level development, I assume most developers will
want to receive a JSON event to trigger their streaming Lambda function.
Going efficiently from a `ByteBuffer` to a Swift struct requires some
code implemented in the `JSON+ByteBuffer.swift` file of the librray. We
propose to further help developers by providing them with a new
`handler()` function that directly receives their `Decodable` type.
### Modifications:
This PR adds a public facing API (+ unit test + updated README) allowing
developers to write a handler method accepting any `Decodable` struct as
input.
```swift
import AWSLambdaRuntime
import NIOCore
// Define your input event structure
struct StreamingRequest: Decodable {
let count: Int
let message: String
let delayMs: Int?
}
// Use the new streaming handler with JSON decoding
let runtime = LambdaRuntime { (event: StreamingRequest, responseWriter, context: LambdaContext) in
context.logger.info("Received request to send \(event.count) messages")
// Stream the messages
for i in 1...event.count {
let response = "Message \(i)/\(event.count): \(event.message)\n"
try await responseWriter.write(ByteBuffer(string: response))
// Optional delay between messages
if let delay = event.delayMs, delay > 0 {
try await Task.sleep(for: .milliseconds(delay))
}
}
// Finish the stream
try await responseWriter.finish()
// Optional: Execute background work after response is sent
context.logger.info("Background work: processing completed")
}
try await runtime.run()
```
This interface provides:
- **Type-safe JSON input**: Automatic decoding of JSON events into Swift
structs
- **Streaming responses**: Full control over when and how to stream data
back to clients
- **Background work support**: Ability to execute code after the
response stream is finished
- **Familiar API**: Uses the same closure-based pattern as regular
Lambda handlers
Because streaming Lambda functions can be invoked either directly
through the API or through Lambda Function URL, this PR adds the
decoding logic to support both types, shielding developers from working
with Function URL requests and base64 encoding.
We understand these choice will have an impact on the raw performance
for event handling. Those advanced users that want to get the maximum
might use the existing `handler(_ event: ByteBuffer, writer:
LambaStreamingWriter)` function to implement their own custom decoding
logic.
This PR provides a balance between ease of use for 80% of the users vs
ultimate performance, without closing the door for the 20% who need it.
### Result:
Lambda function developers can now use arbitrary `Decodable` Swift
struct or Lambda events to trigger their streaming functions. 🎉
---------
Co-authored-by: Tim Condon <0xTim@users.noreply.github.com>
This is a proposal to fix issue #507
**changes**
- `LambdaRuntime.init()` uses a `Mutex<Bool>` to make sure only one
instance is created
- `LambdaRuntime.init()` can now throw an error in case an instance
already exists (I did not use `fatalError()` to make it easier to test)
- All `convenience init()` methods catch possible errors instead of
re-throwing it to a void breaking the user-facing API
- Renamed existing `LambdaRuntimeError` to `LambdaRuntimeClientError`
- Introduced a new type `LambdaRuntimeError` to represent the double
initialization error
---------
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Co-authored-by: Adam Fowler <adamfowler71@gmail.com>
Add `S3EventNotifier` example
### Motivation:
There is currently no example regarding an AWS event triggered lambda,
such as a lambda that gets invoked on an S3 object upload. I've had to
look for a while to figure out that the `AWSLambdaEvents` exists and
that it can be used for that (had to find out via a Java example! 😜) so
I think this could be useful and a somewhat common use case
### Modifications:
Added an example of a lambda that gets triggered when an object gets
uploaded to an S3 bucket.
I have not described how to set up the actual S3 event in AWS because I
figured if you needed such a lambda you'd know, but I can describe that
too in the README if needed
---------
Co-authored-by: Sébastien Stormacq <sebastien.stormacq@gmail.com>
The local testing instruction are missing from the hello world example.
The format of the payload is not intuitive or trivial to guess. We need
to make it explicit
When including resources in the package and packaging on Ubuntu,
`FileManager` throws a FilePermission error. The docker daemon runs as
root and files to be copied are owned by `root` while the archiver runs
as the current user (`ubuntu` on EC2 Ubuntu). The `FileManager` manages
to copy the files but throws an error after the copy. We suspect the
`FileManager` to perform some kind of operation after the copy and it
fails because of the `root` permission of the files.
See
https://github.com/swift-server/swift-aws-lambda-runtime/issues/449#issuecomment-2595978246
for a description of the problem.
This PR contains code to reproduce the problem, a very simple
workaround, and an integration test.
The workaround consists of
- trapping all errors
- verify if the error is the permission error (Code = 513)
- verify if the files have been copied or not
- if the two above conditions are met, ignore the error, otherwise
re-throw it
I would rather prefer a solution that solves the root cause rather than
just ignoring the error.
We're still investigating the root cause (see [this
thread](https://forums.swift.org/t/filemanager-copyitem-on-linux-fails-after-copying-the-files/77282)
on the Swift Forum and this issue on Swift Foundation
https://github.com/swiftlang/swift-foundation/issues/1125
Add an example of an APIGateway Lambda Authorizer
### Motivation:
Lambda Authorizers allow developers to write custom logic to validate
HTTP REST requests.
This example shows how to write a Lambda Authorizer in Swift and how to
configure an API Gateway to use a Lambda Authorizer.
This example use a SAM template to deploy the resources.
### Modifications:
- Add `Examples/APIGateway+LambdaAuthorizer` directory with the source
code, a `template.yaml`, and a `README` file.
- Add a reference to the new example in `Examples/README`
- Modify CI to build the new example
### Result:
There is a new example showing how to develop a Lambda authorizer in
Swift and how to attach it to an APIGateway with SAM
As discussed with @0xTim
This PR
- adds a minimal example of deployment using SAM in the README
- adds a `Deployment.md` Swift Docc file to cover deployment with the
AWS console, CLI, SAM, and CDK. It mentions and contains a call to
contributions to further examples for third-party tools such as the
Serverless Framework, Terraform, or Pulumi.
This new example project show four testing strategies for Swift Lambda
function
- Unit testing the business logic (not specific to Swift Lambda)
- Integration testing the handler method
- Local invocation with the Swift Lambda Runtime
- Local invocation with SAM
**[IMPORTANT]**
To allow testing the handler, I had to change visibility of a method in
the Runtime project. This method is clearly marked for testing only, so
it should not be a problem. Happy to read feedback and discuss however.
All the `Package.swift` files from the examples use `path: "."` instead
of `path: "Sources"` which triggers error messages when users add a
`Tests` directory.
We want that the runtime only depends on `FoundationEssentials` where
available (ie. on linux) to ensure small binary size.
### Motivation:
Smaller binary size is good for lambda deployment and cold-start times.
The runtime should only depend on `FoundationEssentials`.
### Modifications:
- replace `import Foundation` with `import FoundationEssentials` if
`FoundationEssentials` is available.
- I also applied the same treatment to tests to ensure that catch error
where tests run on linux and we use API that is only available in
`Foundation` which easily happens when you develop on macOS (where
always full `Foundation` is available).
### Result:
This should allow builds without linking full `Foundation`.
* add aws sdk example
* add soto example
* use amazonlinux docker image instead of ubuntu
* dynamically add runtime dependency based on env var
* remove import of Foundation.ProcessInfo
* workaround https://github.com/actions/checkout/issues/1487