skip to Main Content

I am using golang in a lambda function to connect to redis. When I first call the lambda a new connection pool is created and further calls the lambda seems to use the pool to get connections. However when I added the con.close() line, the second call to the lambda crashes and the third call will recreate the pool. Is there any risk if I don’t close the connection? Or can I close the connection some other way?

The error I get on cloud watch logs is “runtime error, invalid memory address or nil pointer” on the line pool.Get() seems like the pool variable is nil?

func newPool(addr string) *redis.Pool {
  return &redis.Pool{
    MaxIdle: 3,
    IdleTimeout: 240 * time.Second,
    // Dial or DialContext must be set. When both are set, DialContext takes precedence over Dial.
    Dial: func () (redis.Conn, error) { return redis.Dial("tcp", addr) },
  }
}

var pool *redis.Pool

func init(){
   pool = newPool()
}



func Handle(ctx context.context, req events.APIGatewayWebsocketProxyRequest)(interface{},error){

  //make new redis connection

  con:= pool.get()

   con.close()

}

2

Answers


  1. It looks like you are closing the connection as soon as you open the connection, so yes the Lambda will kill itself.

    You could keep the connection alive with a loop of some sort, process your messages then exit the loop to close the connection. Which would then in turn kill the Lambda again.

    You could set your lambda to be long-lived which would just keep incurring costs.

    Once your Handle method is complete lambdas kill themselves.

    Login or Signup to reply.
  2. How about adding defer con.close() in Handle function? because after Handle function is called it will close the con.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search