How to pass in stateful client to lambda function?

I am working on a simple Lambda function and I was wondering if I could pass in client (dynamodb this time) to the handler, so we do not re-connect for every request.

The macro is defined here:

My function so far:

fn main() -> Result<(), Box<dyn Error>> {
    info!("Starting up...");
    let dynamodb_client = DynamoDbClient::new(Region::EuCentral1);
    return Ok(());

Is it possible to extend this macro to have a second option so I can add the client all the way down to the functions which are actually talking to the database.

Let me answer my own question here. I found lazy_static to be a great solution for this problem.

extern crate lazy_static;

lazy_static! {
    static ref DYNAMODB_CLIENT: DynamoDbClient = DynamoDbClient::new(Region::EuCentral1);

If you use a closure instead of router in the macro, you can move the client into the closure.

1 Like

Thanks @alice, not sure how that would work. The client is needed later on by the actual handler functions. Would that work?

I'm not familiar with lambda_http. By moving it into the closure, you can have it available inside the router function. If you can pass it on from there, yes.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.