[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-03 (世界標準時間)。"],[],[],null,["\u003cbr /\u003e\n\nThis document describes how you can request asynchronous (non-HTTPS)\nbackground functions to retry on failure.\n\nWhy event-driven functions fail to complete\n\nOn rare occasions, a function might exit prematurely due to an internal error,\nand by default the function might or might not be automatically retried.\n\nMore typically, an event-driven function might fail to successfully complete due\nto errors thrown in the function code itself. The reasons this might\nhappen include:\n\n- The function contains a bug and the runtime throws an exception.\n- The function cannot reach a service endpoint, or times out while trying to do so.\n- The function intentionally throws an exception (for example, when a parameter fails validation).\n- A Node.js function returns a rejected promise, or passes a non-`null` value to a callback.\n\nIn any of the above cases, the function will stop executing and return an error.\nEvent triggers producing the messages have retry policies that you can customize\nto meet the needs of your function.\n\nSemantics of retry\n\nCloud Functions provides at-least-once execution of an event-driven function\nfor each event emitted by an event source.\n\nBy default, if a function\ninvocation terminates with an error, the function is not invoked again and the\nevent is dropped. When you enable retries on an event-driven function,\nCloud Functions retries a failed function invocation until it completes\nsuccessfully or the retry window expires.\n| **Warning:** Setting \"retry on failure\" causes your function to be retried repeatedly until it either successfully executes or the maximum retry period has elapsed, which can be multiple days. If the failure is due to a bug or any other sort of permanent error, your function can get stuck in a retry loop. You should only use this setting when dealing with transient failures (such as an unreliable endpoint or intermittent timeouts), and only after pressure-testing your code without this property set. If your function does become stuck in a retry loop, you must either redeploy it or delete it to end execution.\n\nWhen retries are not enabled for a function, which is the default, the function\nalways reports that it executed successfully, and `200 OK` response codes might\nappear in its logs. This occurs even if the function encountered an error. To\nmake it clear when your function encounters an error, be sure to\n\n[report errors](/docs/functions/reporting-errors)\n\nappropriately.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nConfigure retries from your function code\n\nWith Cloud Functions for Firebase, you can enable retries in the code for a\nfunction. To do this for a background event such as the creation of a new\nFirestore document, set the [`failurePolicy`](https://firebase.google.com/docs/reference/functions/firebase-functions.runtimeoptions.md#runtimeoptionsfailurepolicy) (1st gen) or [`retry`](https://firebase.google.com/docs/reference/functions/2nd-gen/node/firebase-functions.eventhandleroptions.md#eventhandleroptionsretry)\npolicy (2nd gen) option to `true`:\n\n1st gen \n\n exports.docCreated = functions\n .runWith({\n // retry on failure\n failurePolicy: true,\n })\n .firestore.document(\"my-collection/{docId}\")\n .onCreate((change, context) =\u003e {\n /* ... */\n });\n\n2nd gen \n\n const { onDocumentCreated } = require(\"firebase-functions/firestore\");\n\n exports.docCreated = onDocumentCreated(\n {\n // retry on failure\n retry: true,\n },\n \"my-collection/{docId}\",\n (event) =\u003e {\n /* ... */\n },\n );\n\nSetting `true` as shown configures a function to retry on failure.\n\n\u003cbr /\u003e\n\nRetry window For 2nd gen functions, this retry window expires after 24 hours. For 1st gen functions, it expires after 7 days. Cloud Functions retries newly created event-driven functions using an exponential backoff strategy, with an increasing backoff of between 10 and 600 seconds. This policy is applied to new functions the first time you deploy them. It is not retroactively applied to existing functions that were first deployed before the changes described in [this release note](//cloud.google.com/functions/docs/release-notes#April_20_2023) took effect, even if you redeploy the functions.\n\n\u003cbr /\u003e\n\nBest practices\n\nThis section describes best practices for using retries.\n\nUse retry to handle transient errors\n\nBecause your function is retried continuously until successful execution,\npermanent errors like bugs should be eliminated from your code through testing\nbefore enabling retries. Retries are best used to handle intermittent or transient\nfailures that have a high likelihood of resolution upon retrying, such as a\nflaky service endpoint or timeout.\n\nSet an end condition to avoid infinite retry loops\n\nIt is best practice to protect your function against continuous looping when\nusing retries. You can do this by including a well-defined end condition,\n*before* the function begins processing. Note that this technique only works if\nyour function starts successfully and is able to evaluate the end condition.\n\nA simple yet effective approach is to discard events with timestamps older than\na certain time. This helps to avoid excessive executions when failures are\neither persistent or longer-lived than expected.\n\nFor example, this code snippet discards all events older than 10 seconds: \n\n const eventAgeMs = Date.now() - Date.parse(event.timestamp);\n const eventMaxAgeMs = 10000;\n if (eventAgeMs \u003e eventMaxAgeMs) {\n console.log(`Dropping event ${event} with age[ms]: ${eventAgeMs}`);\n callback();\n return;\n }\n\nUse `catch` with Promises\n\nIf your function has retries enabled, any unhandled error will trigger a retry.\nMake sure that your code captures any errors that shouldn't result in a retry.\n\nHere is an example of what you should do: \n\n return doFooAsync().catch((err) =\u003e {\n if (isFatal(err)) {\n console.error(`Fatal error ${err}`);\n }\n return Promise.reject(err);\n });\n\nMake retryable event-driven functions idempotent\n\nEvent-driven functions that can be retried must be idempotent. Here are some\ngeneral guidelines for making such a function idempotent:\n\n- Many external APIs (such as Stripe) let you supply an idempotency key as a parameter. If you are using such an API, you should use the event ID as the idempotency key.\n- Idempotency works well with at-least-once delivery, because it makes it safe to retry. So a general best practice for writing reliable code is to combine idempotency with retries.\n- Make sure that your code is internally idempotent. For example:\n - Make sure that mutations can happen more than once without changing the outcome.\n - Query database state in a transaction before mutating the state.\n - Make sure that all side effects are themselves idempotent.\n- Impose a transactional check outside the function, independent of the code. For example, persist state somewhere recording that a given event ID has already been processed.\n- Deal with duplicate function calls out-of-band. For example, have a separate clean up process that cleans up after duplicate function calls.\n\nConfigure the retry policy\n\nDepending on the needs of your function, you may want to configure the\nretry policy directly. This would allow you to set up any combination of the\nfollowing:\n\n- Shorten the retry window from 7 days to as little as 10 minutes.\n- Change the minimum and maximum backoff time for the exponential backoff retry strategy.\n- Change the retry strategy to retry immediately.\n- Configure a [dead-letter topic](//cloud.google.com/pubsub/docs/handling-failures#dead_letter_topic).\n- Set a maximum and minimum number of delivery attempts.\n\nTo configure the retry policy:\n\n1. Write an HTTP function.\n2. Use the Pub/Sub API to create a Pub/Sub subscription, specifying the URL of the function as the target.\n\nSee [Pub/Sub documentation on handling failures](//cloud.google.com/pubsub/docs/handling-failures)\nfor a more information on configuring Pub/Sub directly."]]