cloud-sql-proxy icon indicating copy to clipboard operation
cloud-sql-proxy copied to clipboard

Occasionally getting error "Could not connect to server: Connection refused"

Open Tech2pr opened this issue 3 years ago • 3 comments

We are occasionally getting the connection refused error in production. We get this error 2-3 times a day. Our app is deployed in App Engine. I couldn't find anything helpful in the logs. We are using psycopg2 v 2.8.5 binary as postgresql engine.

could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/xxxxxxxx:us-central1:xxxxx-production-1/.s.PGSQL.5432"?

Tech2pr avatar Aug 10 '22 08:08 Tech2pr

Are you using connection pooling as part of your setup? Mind sharing the application code that shows how you're creating connections?

enocom avatar Aug 10 '22 15:08 enocom

No. We aren't using connection pools. We are using Django framework.

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path="schemaname"' }, 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'xxxxxxx', 'HOST': f'/cloudsql/xxxxxxxx:us-central1:xxxx-production-1', 'PORT': '5432', } }

Tech2pr avatar Aug 12 '22 01:08 Tech2pr

Hi @Tech2pr,

Opening and closing connections can have some additional overhead, your application may be experiencing the error when it is seeing higher database traffic, hitting Django's limit for number of connections.

One thing you can try is setting the CONN_MAX_AGE param in your config. This will allow persistent database connections (similar to connection pooling) so that connections can be re-used. This might help reduce the burden of opening and closing each connection since the default for CONN_MAX_AGE is 0.

Example:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'CONN_MAX_AGE': 60, 
'OPTIONS': {
'options': '-c search_path="schemaname"'
},
# ...

Let me know if the above helps at all, thanks for raising this question!

Have a great day.

jackwotherspoon avatar Aug 12 '22 18:08 jackwotherspoon

Thank you @jackwotherspoon. We have implemented the suggestion and we will monitor for the same error in the upcoming days.

Tech2pr avatar Aug 20 '22 03:08 Tech2pr

How's the updated deployment looking @Tech2pr?

enocom avatar Aug 29 '22 20:08 enocom

I’m going to close this since it’s been awhile now. Feel free to add additional info here and re-open if necessary.

enocom avatar Sep 14 '22 14:09 enocom