go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

Connect Postgresql failed in AWS Lambda #7139

Closed rts-gordon closed 3 months ago

rts-gordon commented 3 months ago

Your Question

Hi there, I have a Golang program that use gorm to connect to Postgresql and run in AWS lambda, sometimes there are connection errors when it cold start up in AWS Lambda, I have done a lot of tests including upgrade/downgrade gorm version, aws-lambda-go version and so on, but this errors still exist.

Does someone have the same errors and can have a look at this? Thank you very much.

Connect code:

if _dbIns, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
    DisableForeignKeyConstraintWhenMigrating: true, 
    SkipDefaultTransaction:                   true, 
    Logger: gormLogger, // Logger
}

Error message:

{
    "time": "2024-08-03T02:10:50.605460192Z",
    "level": "ERROR",
    "msg": "failed to initialize database, got error failed to connect to `host=DBurl user=username database=DBname`: dial error (timeout: dial tcp 12.34.56.78:5432: connect: connection timed out)"
}

Golang: v1.22 Gorm: v1.25.10 driver/postgres: v1.5.9 aws-lambda-go: v1.47.0 aws-lambda-go-api-proxy: v0.16.2

The document you expected this should be explained

Expected answer

Gorm can connect DB successful in AWS Lambda.

cbaker commented 3 months ago

This is not a problem with Gorm, if it only happens on cold starts have you considered writing some code to retry the connection?

rts-gordon commented 3 months ago

Thanks for your reply, I will update my code.