Search code examples
google-cloud-platformgoogle-cloud-functionsgoogle-cloud-spanner

Cloud Spanner session handling in Cloud Functions


I'm using Cloud Functions with nodeJS client library to insert data into Spanner. The function is invoked by Pub/sub about 2 times/sec, and inserts data using a transaction.

When reading the documentation it clearly says you have to close the session by calling: database.close(); When I do, it throws an error:

Error: Database is closed. at SessionPool.<anonymous>   
(/srv/node_modules/@google-cloud/spanner/build/src/session-   
pool.js:264:23)
at Generator.next (<anonymous>) at /srv/node_modules/@google-
cloud/spanner/build/src/session-pool.js:22:71 at new Promise
(<anonymous>) at __awaiter (/srv/node_modules/@google-
cloud/spanner/build/src/session-pool.js:18:12) at SessionPool._acquire 
(/srv/node_modules/@google-cloud/spanner/build/src/session-
pool.js:262:16) at SessionPool.getReadSession 
(/srv/node_modules/@google-cloud/spanner/build/src/session-
pool.js:204:14) at Database.runStream (/srv/node_modules/@google-
cloud/spanner/build/src/database.js:1157:20) at Database.run 
(/srv/node_modules/@google-cloud/spanner/build/src/database.js:988:14) 
at PromiseCtor (/srv/node_modules/@google-
cloud/promisify/build/src/index.js:71:28)

So my question is: Are Spanner sessions handled differently in Cloud functions? Does it cache the sessions for next invocation? What am I doing wrong, should I not call database.close() in cloud functions?

I call database.close() after returning the transaction.commit() and after calling transaction.end();

Thanks!


Solution

  • As you mentioned on the comments, a new session is created each time, this is mentioned on the docs.

    Also the tutorial you mentioned has no database.close() ran correctly on my side, so i took a look at the docs on Cloud Functions and Cloud SQL, here it states :

    we recommend that you not close connections at the end of the function call. If you do not use a pool in global scope, and/or if you create individual connections in function-scope, then you should close these connections before the function returns.

    So this should apply to any connection, including spanner