Home > Software engineering >  How to call cloud function nearest to the user
How to call cloud function nearest to the user

Time:01-15

I have a cloud function like this which has been set to run in multiple regions.

export const cloudFunction = functions
    .region(["asia-south1", "us-central1", "europe-west1", "southamerica-east1"])
    .https.onCall(async (data, context) => {});

How can I call the cloud function region nearest to the user? From any client side framework?

CodePudding user response:

The best solution is to use an HTTPS Load Balancer and to create a serverless NEG with your Cloud Functions. The HTTPS Load Balancer will deploy a unicast IP, I mean an IP known in different PoP (Point of Presence) of Google, and will route the request to the closest location (from the PoP). It's native and out of the box, nothing to code.

CodePudding user response:

You'll have to find the closet region based on user's timezone/location yourself and specify the region on client side for routing based on region w/o a balancer as each Cloud Function has it's own URL containing the region. For example, one way would be like:

const getClosestGcpRegion = () => {
  const regions = ['asia-south1', 'us-central1', 'europe-west1']
  const regionOffsets = {
    'asia-south1': ' 05:30',
    'us-central1': '-06:00',
    'europe-west1': ' 01:00',
  }

  let closestRegion = ''
  let closestOffset = Number.MAX_SAFE_INTEGER

  for (const region of regions) {
    const offset = regionOffsets[region].split(':')
    const offsetMinutes = Number(offset[0]) * 60   Number(offset[1])
    const offsetDiff = Math.abs(DateTime.local().offset - offsetMinutes) 

    if (offsetDiff < closestOffset) {
      closestOffset = offsetDiff
      closestRegion = region
    }
  }

  console.log({ closestRegion })
  return closestRegion;
}

export const functions = getFunctions(app, getClosestGcpRegion())

Alternatively, also checkout Global external HTTP(S) load balancer with Cloud Functions that can help you achieve the same goal.

  • Related