Skip to content

Commit 71472ce

Browse files
committed
add background task section in the main readme
1 parent 199b427 commit 71472ce

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

readme.md

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,51 @@ tbd + link to docc
160160
161161
tbd + link to docc
162162
163-
### Background Tasks
163+
### Use Lambda Background Tasks
164164
165-
tbd + link to docc
165+
Background tasks allow code to execute asynchronously after the main response has been returned, enabling additional processing without affecting response latency. This approach is ideal for scenarios like logging, data updates, or notifications that can be deferred. The code leverages Lambda's "Response Streaming" feature, which is effective for balancing real-time user responsiveness with the ability to perform extended tasks post-response. For more information about Lambda background tasks, see [this AWS blog post](https://aws.amazon.com/blogs/compute/running-code-after-returning-a-response-from-an-aws-lambda-function/).
166+
167+
168+
Here is an example of a minimal function that waits 10 seconds after it returned a response but before the handler returns.
169+
```swift
170+
import AWSLambdaRuntime
171+
import Foundation
172+
173+
struct BackgroundProcessingHandler: LambdaWithBackgroundProcessingHandler {
174+
struct Input: Decodable {
175+
let message: String
176+
}
177+
178+
struct Greeting: Encodable {
179+
let echoedMessage: String
180+
}
181+
182+
typealias Event = Input
183+
typealias Output = Greeting
184+
185+
func handle(
186+
_ event: Event,
187+
outputWriter: some LambdaResponseWriter<Output>,
188+
context: LambdaContext
189+
) async throws {
190+
// Return result to the Lambda control plane
191+
context.logger.debug("BackgroundProcessingHandler - message received")
192+
try await outputWriter.write(Greeting(echoedMessage: event.message))
193+
194+
// Perform some background work, e.g:
195+
context.logger.debug("BackgroundProcessingHandler - response sent. Performing background tasks.")
196+
try await Task.sleep(for: .seconds(10))
197+
198+
// Exit the function. All asynchronous work has been executed before exiting the scope of this function.
199+
// Follows structured concurrency principles.
200+
context.logger.debug("BackgroundProcessingHandler - Background tasks completed. Returning")
201+
return
202+
}
203+
}
204+
205+
let adapter = LambdaCodableAdapter(handler: BackgroundProcessingHandler())
206+
let runtime = LambdaRuntime.init(handler: adapter)
207+
try await runtime.run()
208+
```
209+
210+
You can learn how to deploy and invoke this function in [the example README file](Examples/BackgroundTasks/README.md).

0 commit comments

Comments
 (0)