Местоположение облачных функций

Cloud Functions is regional , which means the infrastructure that runs your function is located in specific regions and is managed by Google to be redundantly available across all the zones within those regions.

When selecting what regions to run your functions in, your primary considerations should be latency and availability. You can generally select regions close to your users, but you should also consider the location of the other products and services that your app uses. Using services across multiple regions can affect your app's latency, as well as pricing .

By default, the Firebase CLI deploys functions to a region based on your project's configuration. For event-driven functions, it typically deploys to a region in the triggering data source's region (like a Cloud Firestore database or Cloud Storage bucket), and as a fallback deploys to us-central1 .

После развертывания вы можете проверить регион в консоли Firebase или выполнив команду firebase functions:list . Если вы хотите, чтобы ваша функция работала в другом регионе, вы можете изменить его регион .

Поддерживаемые регионы

In the lists in this section, the energy_savings_leaf icon indicates that the electricity for this region is produced with low carbon emissions. For more information, see Carbon free energy for Google Cloud regions .

Ценообразование первого уровня

Cloud Functions доступен в следующих регионах по тарифам уровня 1 :

Область Расположение Поддерживаемые версии продукта Выбросы CO₂
africa-south1 Йоханнесбург Только для 2-го поколения
asia-east1 Тайвань 1-е поколение, 2-е поколение
asia-east2 Гонконг Только для первого поколения
asia-northeast1 Токио 1-е поколение, 2-е поколение
asia-northeast2 Осака 1-е поколение, 2-е поколение
europe-north1 Финляндия Только для 2-го поколения энергосбережение_лист
europe-southwest1 Мадрид Только для 2-го поколения
europe-west1 Бельгия 1-е поколение, 2-е поколение энергосбережение_лист
europe-west4 Нидерланды Только для 2-го поколения
europe-west8 Милан Только для 2-го поколения
europe-west9 Париж Только для 2-го поколения энергосбережение_лист
me-west1 Тель-Авив Только для 2-го поколения
europe-west2 Лондон Только для первого поколения
us-central1 Айова 1-е поколение, 2-е поколение энергосбережение_лист
us-east1 Южная Каролина 1-е поколение, 2-е поколение
us-east4 Северная Вирджиния 1-е поколение, 2-е поколение
us-east5 Колумб Только для 2-го поколения
us-south1 Даллас Только для 2-го поколения
us-west1 Орегон 1-е поколение, 2-е поколение энергосбережение_лист

Ценообразование второго уровня

Cloud Functions доступен в следующих регионах по тарифам уровня 2 :

Область Расположение Поддерживаемые версии продукта Выбросы CO₂
asia-east2 Гонконг Только для 2-го поколения
asia-northeast3 Сеул 1-е поколение, 2-е поколение
asia-southeast1 Сингапур 1-е поколение, 2-е поколение
asia-southeast2 Джакарта 1-е поколение, 2-е поколение
asia-south1 Мумбаи Только для 2-го поколения
asia-south2 Дели, Индия Только для 2-го поколения
australia-southeast1 Сидней 1-е поколение, 2-е поколение
australia-southeast2 Мельбурн Только для 2-го поколения
europe-central2 Варшава 1-е поколение, 2-е поколение
europe-west2 Лондон Только для 2-го поколения
europe-west3 Франкфурт 1-е поколение, 2-е поколение энергосбережение_лист
europe-west6 Цюрих 1-е поколение, 2-е поколение энергосбережение_лист
europe-west10 Берлин Только для 2-го поколения
europe-west12 Турин Только для 2-го поколения
me-central1 Доха Только для 2-го поколения
me-central2 Даммам Только для 2-го поколения
northamerica-northeast1 Монреаль 1-е поколение, 2-е поколение энергосбережение_лист
northamerica-northeast2 Торонто Только для 2-го поколения энергосбережение_лист
southamerica-east1 Сан-Паулу 1-е поколение, 2-е поколение энергосбережение_лист
southamerica-west1 Сантьяго, Чили Только для 2-го поколения
us-west2 Лос-Анджелес 1-е поколение, 2-е поколение
us-west3 Солт-Лейк-Сити 1-е поколение, 2-е поколение
us-west4 Лас-Вегас 1-е поколение, 2-е поколение

Функции в рамках одного региона и одного проекта должны иметь уникальные (регистронечувствительные) имена, однако функции в разных регионах или проектах могут иметь одно и то же имя.

Рекомендации по указанию региона

By default, the Firebase CLI deploys functions to a region based on your project's configuration. For event-driven functions, it typically deploys to a region in the triggering data source's region (like a Cloud Firestore database or Cloud Storage bucket), and as a fallback deploys to us-central1 .

You are encouraged to set specific regions instead of relying on Firebase defaults, which might change over time. When setting regions, follow the recommendations in this section for each trigger type

Чтобы задать область выполнения функции, укажите параметр region в определении функции, как показано ниже:

Node.js

exports.firestoreAsia = onDocumentCreated(
  {
    document: "my-collection/{docId}",
    region: "asia-northeast1",
  },
  (event) => {},
);

Python

# Before
@firestore_fn.on_document_created("my-collection/{docId}")
def firestore_trigger(event):
    pass

# After
@firestore_fn.on_document_created("my-collection/{docId}",
                                  region="asia-northeast1")
def firestore_trigger_asia(event):
    pass

You can specify multiple regions by passing multiple comma-separated region strings in region . Also note that, when specifying a region for many background trigger types, you'll need to specify the correct event filter along with the region. In the example above, this is the Cloud Firestore document that emits the event. For a Cloud Storage trigger the event filter could be bucket ; for a Pub/Sub trigger it would be topic , and so on.

Дополнительную информацию об изменении региона для функции, обрабатывающей производственный трафик, см. в разделе «Изменение региона функции».

HTTP-функции и функции, вызываемые клиентом

For HTTP and callable functions, we recommend that you first set your function to the destination region, or closest to where most expected customers are located, and then alter your original function to redirect its HTTP request to the new function (they can have the same name). If clients of your HTTP function support redirects, you can simply change your original function to return an HTTP redirect status (301) along with the URL of your new function. If your clients do not handle redirects well, you can proxy the request from the original function to the new function by initiating a new request from the original function to the new function. The final step is to ensure that all clients are calling the new function.

Выбор местоположения вызываемых функций на стороне клиента

Regarding the callable function, client callable setups should follow the same guidelines as HTTP functions. The client can also specify a region, and should do so if the function runs in a region other than the project's default.

Для задания регионов на стороне клиента укажите желаемый регион при инициализации:

Быстрый

lazy var functions = Functions.functions(region:"europe-west1")

Objective-C

@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functionsWithRegion:@"europe-west1"];

Веб


var functions = firebase.app().functions('europe-west1');

Android

private FirebaseFunctions mFunctions;
// ...
mFunctions = FirebaseFunctions.getInstance("europe-west1");

C++

firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance("europe-west1");

Единство

firebase.Functions.FirebaseFunctions functions;

functions = Firebase.Functions.FirebaseFunctions.GetInstance("europe-west1");

Фоновые функции

Background functions adopt an at-least-once event delivery semantic, which means that under some circumstances they may receive duplicate events. So, you should implement functions to be idempotent . If your function is already idempotent, then you can redeploy the function in the new region with the same event trigger and remove the old function after you verify that the new function is correctly receiving traffic. During this transition, both functions will receive events. See change a function's region for the recommended sequence of commands to change regions for functions.

Если ваша функция в данный момент не является идемпотентной или её идемпотентность не распространяется за пределы указанного региона, мы рекомендуем сначала реализовать идемпотентность, прежде чем перемещать функцию.

Рекомендации по оптимальному региону различаются в зависимости от типа триггера события:

Тип триггера Рекомендации по региону
Cloud Firestore Ближайший регион к местоположению экземпляра Cloud Firestore (см. следующий раздел)
Realtime Database Тот же регион, что и экземпляр Realtime Database
Cloud Storage Ближайший регион к местоположению Cloud Storage (см. следующий раздел)
Другие If you are interacting with a Realtime Database instance, a Cloud Firestore instance, or a Cloud Storage bucket inside of the function, then the recommended region is the same as if you had a function triggered by one of those resources. Functions connected to Firebase Hosting can be in any region, but see the hosting serverless overview for recommendations.

Выбор регионов на основе расположения Cloud Firestore и Cloud Storage

Доступные регионы для функций не всегда точно совпадают с регионами, доступными для вашей базы данных Cloud Firestore и ваших сегментов Cloud Storage .

Обратите внимание, что если ваша функция и ваш ресурс (экземпляр базы данных или хранилище Cloud Storage ) находятся в разных местах, то вы можете столкнуться с увеличением задержки и затрат на оплату .

Ниже приведено сопоставление ближайших регионов, поддерживающих функции Cloud Firestore и Cloud Storage , на случай, если тот же регион не поддерживается:

Региональная/многорегиональная поддержка для Cloud Firestore и Cloud Storage Ближайший регион для проведения мероприятий
nam5 или us-central (многорегиональный) us-central1
eur3 или europe-west (мультирегиональная) europe-west1
europe-west4 (Нидерланды) europe-west1
asia-south1 (Мумбаи) asia-east2
asia-south2 (Дели) asia-east2
australia-southeast2 (Мельбурн) australia-southeast1