简体   繁体   中英

What happens with goroutines in aws-lambda when your handler function exits?

The question originates in: how much work can I do in the background, when the response has already been sent. For instance: I just want to receive data, tell the client 'ok', and proceed with some database operations that may take some time.

package main

import (
        "fmt"
        "context"
        "github.com/aws/aws-lambda-go/lambda"
)

type MyEvent struct {
        Name string `json:"name"`
}

func HandleRequest(ctx context.Context, name MyEvent) (string, error) {
        go RecordQuery(name)
        return fmt.Sprintf("Hello %s!", name.Name ), nil
}

func RecordQuery(name MyEvent) {
        // insert stuff in the database, mark user active,
        // log activity, etc..
}

func main() {
        lambda.Start(HandleRequest)
}

Can we count on the goroutine to be able to do its work?

It turns out we can't assume the code will run.

Example implementation:

var alreadyLogging bool

func RecordQuery(name MyEvent) {
    if alreadyLogging {
        return
    }
    alreadyLogging = true
    for i := 0; ; i++ {
        time.Sleep(time.Second)
        log.Print("Still here ", i)
    }
}

Behaviour: as long as the container where the lambda is running is receiving requests, the goroutine will be executed. But all code will stop when the container is no longer receiving requests.

Possible output (in cloudwatch):

2018/05/16 08:50:46 Still here 70
2018/05/16 08:50:47 Still here 71
2018/05/16 08:50:48 Still here 72
2018/05/16 08:50:49 Still here 73
2018/05/16 08:51:36 Still here 74
2018/05/16 08:51:37 Still here 75
2018/05/16 08:51:38 Still here 76

Note that in the Node.js Programming Model, you can request AWS Lambda to freeze the process soon after the callback is called, even if there are events in the event loop: The Context Object Properties .

It would be interesting to see some use cases for this API.

Update: in Node.js, as soon as you connect to databases, you'll have a non-empty event queue. That's why this setting is available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM