Connecting to Cloud SQL from Cloud Functions

This page contains information and examples for connecting to a Cloud SQL instance from a service running in Cloud Functions.

Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, manage, and administer your relational PostgreSQL and MySQL databases in the cloud.

Cloud Functions is a lightweight compute solution for developers to create single-purpose, stand-alone functions that respond to Cloud events without the need to manage a server or runtime environment.

Setting up a Cloud SQL instance

  1. Create a Cloud SQL for MySQL instance.

  2. Find the INSTANCE_CONNECTION_NAME for the instance on the Instance details page. It uses the format PROJECT_ID:REGION:INSTANCE_ID, and is used to identify the Cloud SQL instance you are connecting to.

  3. Enable the Cloud SQL Admin API, if you haven't already done so:

    Enable the API

Configuring Cloud Functions

Cloud Functions does not require any special configuration beyond making sure the service account used has the correct permissions.

Cloud Functions uses a service account to authorize your connections to Cloud SQL. This service account must have the correct IAM permissions to successfully connect. Unless otherwise configured, the default service account is in the format service-YOUR_PROJECT_NUMBER@gcf-admin-robot.iam.gserviceaccount.com.

When connecting resources in two different projects, make sure that both projects have enabled the correct IAM roles and have given the service account the correct permissions.

Ensure that the service account for your service has one of the following IAM roles:

  • Cloud SQL Client (preferred)
  • Cloud SQL Editor
  • Cloud SQL Admin

Or, you can manually assign the following IAM permissions:

  • cloudsql.instances.connect
  • cloudsql.instances.get

For detailed instructions on adding IAM roles to a service account, see Granting Roles to Service Accounts.

Connecting to Cloud SQL

Once correctly configured, you can connect your service to your Cloud SQL instance using the Unix domain socket located at /cloudsql/INSTANCE_CONNECTION_NAME. These connections are automatically encrypted without any additional configuration.

Python

# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool of connections to your database
db = sqlalchemy.create_engine(
    # Equivalent URL:
    # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>
    sqlalchemy.engine.url.URL(
        drivername='mysql+pymysql',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_socket': '/cloudsql/{}'.format(cloud_sql_connection_name)
        }
    ),
    # ... Specify additional properties here.
    # ...
)
To see this snippet in the context of a web application, view the source code on GitHub.

Node.js

let pool;
const createPool = async () => {
  pool = await mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
    // If connecting via TCP, enter the IP and port instead
    // host: 'localhost',
    // port: 3306,

    //...
  });
};
createPool();
To see this snippet in the context of a web application, view the source code on GitHub.

Best Practices & Other Information

You can use the Cloud SQL proxy when testing your application locally. See the quickstart for using the proxy for local testing for detailed instructions.

Connection Pools

Connections to underlying databases may be dropped, either by the database server itself, or by the infrastructure underlying Cloud Functions. To mitigate this, we recommend that you use a client library that supports connection pools that automatically reconnect broken client connections.

Additionally, we recommend using a globally scoped connection pool as this improves the likelihood that your function reuses the same connection for subsequent invocations of the function, and closes the connection naturally when the instance is evicted (auto-scaled down).

For more detailed examples on how to use connection pools, see Managing database connections.

Connection Limits

Cloud SQL imposes a maximum limit on concurrent connections, and these limits may vary depending on the database engine chosen (see Cloud SQL Quotas and Limits).

When using a connection pool, it is important to set the maximum connections to 1. This may seem counter-intuitive, however, Cloud Functions limits concurrent executions to 1 per instance. This means you never have a situation where two requests are being processed by a single function instance at the same time. This means in most situations only a single database connection is needed.

Where possible, you should take care to only initialize a connection pool for functions that need to use it. If a deployed function initializes a connection pool it doesn't need, it could create unused connections that count towards your quota. For more details on dealing with global variables in Cloud Functions, see Tips & Tricks.

For more detailed examples on how to limit the number of connections, see Managing database connections.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud SQL for MySQL