Firebase RTDB load balancing with cloud functions

Viewed 215

In my app, I'm using RTDB multiple instances, together with RTDB management APIs, to try to dynamically balance the load.

So my point is, because I don't know future load, I will just start with one RTDB instance, and create multiple ones if a specified threshold of usage is exceeded.

In my case, this requires the following:

  1. create new RTDB instance through management API
  2. apply rules to that RTDB instance
  3. apply cloud functions to that RTDB instance

1 and 2 could be programmatically done inside a cloud function, but I'm having troubles with 3.

Is this possible? Are there any workaround or future plans to support 3?

I'm thinking about two options: deploy a function from a function, or allow RTDB triggers to apply to every instances.

1 Answers

As you can check here in the management API documentation, the response body of the create method returns a DatabaseInstance object which has the following structure:

{
  "name": string,
  "project": string,
  "databaseUrl": string,
  "type": enum (DatabaseInstanceType),
  "state": enum (State)
}

So, you can get the databaseUrl value, store it somewhere in your code and send it to your cloud function as a parameter later, assuming it is a http function. In the function all you have to do is use the following code to access it:

let app = admin.app();
let ref = app.database('YOUR_SECOND_INSTANCE_URL_HERE').ref();

EDIT

For triggered functions this is not possible, since you would need to know the instances names or URL when deploying to function to apply the trigger to them. If you already have the instances names you could try doing something like this community answer, although I am not sure it will suit your app's needs.

Related