Search code examples
.netamazon-web-servicesf#aws-lambdanpgsql

Npgsql with netcoreapp2.0 on AWS Lambda is unable to connect (has timeout) - how can I resolve?


I'm trying to deploy a netcoreapp2.0 application to AWS Lambda that connects to Postgres on RDS. The following code fails:

    let testConn = "Host=hostNameHere;Username=userNameHere;Password=passwordHere;Database=postgres";
    let conn = new NpgsqlConnection(testConn)
    try
        printfn "Trying to open a connection"
        conn.Open()
    with ex ->
        printfn "Exception trying to open conn:\n%O" ex

I get the following stack trace:

System.TimeoutException: The operation has timed out.
at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
at Npgsql.NpgsqlConnector.<RawOpen>d__153.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Npgsql.NpgsqlConnector.<Open>d__149.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Npgsql.ConnectorPool.<AllocateLong>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Npgsql.NpgsqlConnection.Open()
at Masse.Common.SQL.query[T](String connectString, SqlQuery q) in /home/nat/Projects/shopmasse-backend/fsharp/src/Masse.Common/Sql.fs:line 40

Does anyone know why this might fail with deployed to AWS lambda, but work locally on my machine?

Here are some GitHub issues that may provide additional context:

Some additional details: - DB Engine: PostgreSQL 9.6.6 - Npgsql version: 4.0 - .NET version: netcoreapp2.0

Please let me know if I can provide any additional information. Thank you!


Solution

  • A connection timeout usually indicates a firewall problem.

    Your connection request is blocked by the security group of your RDS instance.

    When you've created the instance, the IP of the computer running the AWS console is automatically whitelisted.

    Any other external or internal resource accessing PostgreSQL must be whitelisted as well.

    I hope you'll enjoy AWS RDS running PostgreSQL, I find it awesome.