Skip to content
This repository was archived by the owner on Feb 20, 2026. It is now read-only.
This repository was archived by the owner on Feb 20, 2026. It is now read-only.

Improve cold start of Cloud Datastore for Cloud Functions #9

Closed

Description

@stephenplusplus
Copied from original issue: googleapis/google-cloud-node#2374

@­richardowright
June 10, 2017 1:12 PM

Environment details

  • OS: Google Cloud Functions
  • Region: US Central
  • google-cloud-node version: 1.0.2

Steps to reproduce

I experience high latency (~1 to 2 seconds) with pretty much every action.

Simple example (runs through bable prior to deploy) -

static async addPerson() {
    try {
      const datastore = Datastore({
        projectId: projectId
      });
      const key = datastore.key('person');
      const person = {
        key: key,
        data: 
          [
            { name: 'last_name', value: 'Wright' },
			{ name: 'last_name_UPPER', value: 'WRIGHT' },
            { name: 'first_name', value: 'Richard' },
			{ name: 'first_name_UPPER', value: 'RICHARD' },
			{ name: 'email', value: '[email protected]' },
            { name: 'address_street', value: 'My Place', excludeFromIndexes: true },
            { name: 'address_city', value: 'City' },
            { name: 'address_state', value: 'State' },
            { name: 'address_zip', value: '12345' },
            { name: 'phone', value: '123.456.7890' },
            { name: 'date_of_birth', value: new Date(1901, 02, 03)},
            { name: 'create_time', value: new Date(Date.now()), excludeFromIndexes: true }
          ]
      };
      
      let saveResponse = await datastore.save(person);
      
      let person_id=saveResponse[0].mutationResults[0].key.path[0].id;
      return person_id;
    } catch (err) {
      console.log(err);
      return;
    }
  }

Activity

  1. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor
    June 10, 2017 1:26 PM

    Can you see if subsequent calls also have a lag? The first request has to sort out the authentication details, so it's known to be slower.

  2. added
    status: blocked
    on Dec 16, 2017
  3. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­richardowright
    June 10, 2017 2:20 PM

    If I call the datastore API within the same function call, I do see a reduction in subsequent call time -

    db_add_person: 1409.076ms
    5668753656250368
    db_add_person: 363.180ms
    5645784439586816
    db_add_person: 235.747ms
    5637489247125504
    

    I've also discovered that using a key file (i.e. creating a service account and specifying keyFilename) decreases the first call time from ~1.4 seconds to 0.85 s.

    So, it looks like your suggestion that it's related to the first request auth is correct, but, since when using cloud functions, the penalty is incurred on each http invocation the overhead is still very high (i.e. 0.8s per HTTP call).

  4. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor
    June 12, 2017 12:40 PM

    since when using cloud functions, the penalty is incurred on each http invocation the overhead is still very high (i.e. 0.8s per HTTP call).

    Yes, unfortunately. I'll close the issue, as we can't do anything within the client library. If any ideas come to mind for how this can be addressed, feel free to discuss.

  5. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­ro-savage
    August 7, 2017 10:45 AM

    @stephenplusplus - We are running into the same issue. Datastore and Functions seem like the perfect combination, paying only a per-request cost. However the latency is much too high to be usable in real-world.

    As was mentioned, it is related to the Auth.

    This problem must be solvable, as other similar systems such as Lambda + DynamoDB don't under into this issue.

    It seems unlikely to be implemented in node, but probably some setup on the function/lambda that is 'pre-authenticated' (AWS IAM roles?).

    Who would be the correct team/repo to work on this issue?

  6. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­reco
    August 28, 2017 3:36 PM

    @ro-savage we were/are using app engine with datastore. we also did run in to big issues with the latency of the datastore. would love to hear some updates @google-admin about this issue.

  7. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­ahume
    September 26, 2017 11:05 PM

    A few weeks into development, we're finding Datastore to not be a viable solution for use in Functions due to the consistently poor performance on even very simple queries. 4000ms on first (authenticating) request, and then 800-1200ms afterwards.

  8. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­ignaciovazquez
    October 3, 2017 4:44 AM

    We are also experiencing 60ms-200ms latencies on a lookup by key (runQuery is even worse) from GAE Flexible in node.

  9. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor
    November 6, 2017 5:07 PM

    Also reported in #2727

    @lukesneeringer this seems to be a common problem. The most recent report shows 10 seconds spent on a query that should take in the tens of milliseconds. Worth considering, our Datastore API uses the REST endpoint (correction: our Datastore API uses common-grpc / manual proto loading with gRPC). There is a GAPIC layer that we will likely convert to during our repo extraction.

  10. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­EJB3927
    November 6, 2017 5:08 PM

    Thank you @stephenplusplus. I can confirm I'm having this issue with the following environment:

    • OS: macOS Sierra
    • Node.js version: 7.10.0
    • npm version: 4.2.0
    • google-cloud/datastore version: 1.1.0

    Additionally, I'm noticing the issue on Cloud Functions with the same node and NPM versions.

  11. stephenplusplus commented on Dec 16, 2017

    @stephenplusplus
    ContributorAuthor

    @­lukesneeringer
    November 6, 2017 9:18 PM

    If this is something that is fixed by switching to the gRPC transport we use elsewhere, then this should be a reasonably (~week or so) quick fix.

  12. 66 remaining items

  13. JustinBeckwith commented on Jun 16, 2019

    @JustinBeckwith
    Contributor

    Greetings folks! I have some good news. I think we've solved most of the issues that have been contributing to these kinds of problems. Like any perf issue, it's rarely just one thing, so I want to tell y'all what we're measuring, and throw out a few best practices.

    For all of this - I am using Cloud Functions with node.js 10.x, and @google-cloud/datastore 4.x. It's very important you upgrade to the latest version of the module to pick up these improvements.

    First - the code I am using to do this benchmarking:

    console.log('COLD START');
    const startTime = Date.now();
    
    const startModuleLoadTime = Date.now();
    const {Datastore} = require('@google-cloud/datastore');
    const moduleLoadTime = Date.now() - startModuleLoadTime;
    
    const datastore = new Datastore();
    
    exports.main = async (req, res) => {
      const query = datastore.createQuery('Task').order('created');
      const [tasks] = await datastore.runQuery(query);
      const endTime = Date.now();
      const totalTime = endTime - startTime;
      const result = {
        tasks: tasks.length,
        moduleLoadTime,
        totalTime,
      };
      res.json(result);
      console.log('GOOD NIGHT');
      process.exit(0);
    }

    Tip 1

    The first thing to call out, and probably the most important: make sure to require the library and instantiate the Datastore object outside of the HTTP handler.

    const {Datastore} = require('@google-cloud/datastore');
    const datastore = new Datastore();
    
    exports.hello = async (req, res) => { 
      // do stuff ...
    };

    This is super important because the first function call in the Datastore instance will do lazy application default authentication, which can be a few networking calls in the path of your function call.

    What to expect

    Using this code, I am reliably seeing:

    • An average cold start time + query of ~1000ms
    • An average module load time of ~450ms
    • An average first time query latency of ~600ms
    • An average warm start query latency of ~150ms

    TL;DR - the worse case scenario, in the case of a cold start with just Datastore is about 1s. Subsequent calls to the warmed instance are around ~150ms.

    Reducing the load time of the module

    One of the biggest culprits for cold start times is going to be module load. We've been steadily working on improving that over the last year:
    image

    You can check out the trend here, and even try out other modules. We went from a time that was hovering around ~850ms down to ~250ms.

    Tip 2

    One of the biggest things you can do to reduce your cold start time is to require less stuff. Every module you require in your app maps to a synchronous set of calls to load files from the disk. No matter what environment you're in ... that's going to slow you down.

    What now

    For now - I just wanted to get this data out there, and get a little feedback. Do folks feel like this is getting better? Anything I'm missing here?

  14. added
    needs more info
    and removed
    status: blocked
    on Jun 16, 2019
  15. stephenplusplus commented on Oct 7, 2019

    @stephenplusplus
    ContributorAuthor

    Given the time without any reports of this issue persisting, I'm going to close as it sounds like this was fixed! If I'm wrong, please let me know so we can dig back in (in which case, the more reproduction details the better!).

  16. ollyde commented on Oct 8, 2019

    @ollyde

    I know this is closed but here is my 2 cents.

    I would pay to have an instance running in a selected area permanently that scales with extra requests just so some of those endpoints are instant that are not used a lot.

    The coldboot is really painful with demoing apps and new functionality and low-used endpoints.

    I'm considering abandoning cloud functions all together because of this.

  17. chadbr commented on Oct 8, 2019

    @chadbr

    It has kept me from trying cloud functions out...

  18. JustinBeckwith commented on Oct 8, 2019

    @JustinBeckwith
    Contributor

    @OllyDixon this exists! The min_instances settings in App Engine let you do this sort of thing, though I recognize it isn't specifically Cloud Functions.

  19. ollyde commented on Oct 8, 2019

    @ollyde

    @JustinBeckwith awesome! But how do I configure this with Firebase / GCP? There's no docs hehe.

    For example I don't see any options to apply min_instances to
    export const uploadUserProfilePhotoV1 = functions.https.onCall(async (data, context): Promise<UserV1> => {}

  20. added
    api: datastore
    on Jan 31, 2020
  21. bcjordan commented on Feb 27, 2022

    @bcjordan

    In my experiments increasing the minInstances argument did not help with the datastore cold starts. Increasing the CPU allocation (via increasing the memory parameter) helped quite a bit.

    • With memory: 256mb: 1500-2500ms (cold start), 100-120ms
    • With memory: 1gb: 620ms (cold start), 100-120ms
    • With memory: 2gb: 400-500ms (cold start), 60-120ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api: datastoreneeds more infoperftype: feature request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions