Un evento può essere rifiutato per diversi motivi. Ad esempio, il servizio di ricezione eventi potrebbe non essere temporaneamente disponibile a causa di un'interruzione; il servizio potrebbe riscontrare un errore durante l'elaborazione di un evento oppure le risorse del servizio potrebbero esaurirsi. Gli errori temporanei come questo possono essere ritentati.
Un evento potrebbe anche non essere recapitato al destinatario. Ad esempio, l'evento potrebbe non corrispondere allo schema previsto configurato oppure la mediazione dell'evento potrebbe non riuscire prima che il messaggio evento possa essere indirizzato alla sua destinazione finale. Questi casi generano errori persistenti.
Errori temporanei
Eventarc Advanced ti offre la possibilità di gestire
gli errori temporanei. Questi errori temporanei possono essere ritentati e includono quelli con
i seguenti codici di errore:
HTTP 408 Request Timeout
HTTP 409 Conflict
HTTP 429 Too Many Requests
HTTP 500 Internal Server Error
HTTP 502 Bad Gateway
HTTP 503 Service Unavailable
HTTP 504 Gateway Time-out
Errori permanenti
A differenza degli errori temporanei, gli errori permanenti includono quanto segue:
Errori che si verificano quando il numero di tentativi configurati è esaurito
Errori che si verificano quando un evento non va a buon fine prima di poter essere indirizzato alla sua
destinazione
Errori che generano un codice di errore considerato non riproducibile. Ad esempio, codici di errore diversi da quelli elencati per gli errori temporanei.
Eventarc Advanced utilizza un ritardo di backoff esponenziale per gestire
gli errori che possono essere riprovati. Il criterio di ripetizione predefinito inizia con un ritardo di un secondo e il ritardo viene raddoppiato dopo ogni tentativo non riuscito (fino a un massimo di 60 secondi e cinque tentativi).
Puoi modificare il criterio di ripetizione predefinito utilizzando la console Google Cloud o il comando
gcloud eventarc pipelines update.
Tieni presente che il fattore di backoff predefinito di 2 non può essere modificato.
Console
Nella console Google Cloud , vai alla pagina Eventarc>Pipeline.
Nella pagina Dettagli pipeline, fai clic su Modifica.
Nella pagina Modifica pipeline, nella sezione Criterio di ripetizione, modifica
i seguenti campi:
Tentativi massimi: il numero di tentativi; il valore predefinito è 5 tentativi. Può essere
qualsiasi numero reale positivo. Se impostato su 1, non viene applicata alcuna policy per i nuovi tentativi e viene eseguito un solo tentativo di invio di un messaggio.
Ritardo minimo (secondi): il ritardo iniziale in secondi; il valore predefinito è 1
secondi. Il valore deve essere compreso tra 1 e 600.
Ritardo massimo (secondi): il ritardo massimo in secondi; il valore predefinito è 60
secondi. Il valore deve essere compreso tra 1 e 600.
Puoi configurare un backoff lineare impostando i ritardi minimo e massimo
sullo stesso valore.
PIPELINE_NAME: l'ID o l'identificatore completo
della pipeline.
MIN_DELAY: il ritardo iniziale in secondi; il valore predefinito
è 1 secondo. Il valore deve essere compreso tra 1 e 600.
MAX_DELAY: il ritardo massimo in secondi; il valore predefinito
è 60 secondi. Il valore deve essere compreso tra 1 e 600.
MAX_ATTEMPTS: il numero di tentativi; il valore predefinito è
5 tentativi. Può essere qualsiasi numero reale positivo. Se impostato su 1, non viene applicata alcuna policy per i nuovi tentativi e viene eseguito un solo tentativo di invio di un messaggio.
L'esempio seguente configura un backoff lineare impostando i ritardi minimo e
massimo sullo stesso valore:
Archiviare i messaggi per gestire gli errori persistenti
Puoi scrivere i messaggi in una tabella BigQuery non appena vengono ricevuti. In questo modo
puoi identificare manualmente gli errori persistenti e gestirli in modo appropriato.
Di seguito è riportata una panoramica dei passaggi necessari per archiviare i messaggi degli eventi, identificare gli errori persistenti e riprovare a inviare gli eventi interessati.
Crea un argomento Pub/Sub. Questo
argomento Pub/Sub sarà la destinazione di destinazione della pipeline.
Crea una sottoscrizione BigQuery per l'argomento Pub/Sub. Una sottoscrizione BigQuery è un tipo di sottoscrizione dell'esportazione che scrive i messaggi in una tabella BigQuery esistente alla ricezione. In alternativa, puoi
creare la tabella quando crei l'abbonamento BigQuery.
Crea una pipeline e una registrazione
che indirizza ogni messaggio ricevuto dal bus (utilizzando --cel-match="true") all'argomento Pub/Sub. Configura un criterio di ripetizione per la pipeline.
Ad esempio, i seguenti comandi creano una pipeline e una registrazione:
Ora dovresti avere due set di dati BigQuery separati: uno che
memorizza ogni messaggio ricevuto dal bus Eventarc Advanced e uno
che memorizza i log della pipeline.
Per identificare i messaggi non riusciti, utilizza un'istruzione di query per unire entrambi i set di dati BigQuery nel campo message_uid.
I gestori di eventi che possono essere riprovati devono essere idempotenti e seguire le seguenti
linee guida generali:
Molte API esterne ti consentono di fornire una chiave di idempotenza come parametro. Se utilizzi un'API di questo tipo, devi utilizzare l'origine e l'ID evento come chiave di idempotenza. (I produttori devono assicurarsi che
source + id sia
univoco per ogni evento distinto.)
Inoltre, puoi utilizzare un attributo CloudEvents, xgooglemessageuid, per
fornire l'idempotenza. Il valore di questo attributo è uguale al
campo message_uid nei messaggi Eventarc Advanced. Identifica in modo univoco
l'azione di pubblicazione di un evento. Ad esempio, se lo stesso evento
viene pubblicato due volte in un bus, ogni evento avrà un valore
xgooglemessageuid diverso quando viene inviato a un gestore di eventi.
L'idempotenza funziona bene con la consegna "at-least-once", perché rende sicuro
il nuovo tentativo. Pertanto, una best practice generale per scrivere codice affidabile è combinare
l'idempotenza con i tentativi.
Assicurati che il codice sia idempotente internamente. Ad esempio:
Assicurati che le mutazioni possano verificarsi più di una volta senza modificare il
risultato.
Esegui query sullo stato del database in una transazione prima di modificarlo.
Assicurati che tutti gli effetti collaterali siano idempotenti.
Imponi un controllo transazionale al di fuori del tuo servizio, indipendentemente dal codice.
Ad esempio, mantieni lo stato in un punto in cui viene registrato che un determinato ID evento è
già stato elaborato.
Gestisci le chiamate duplicate fuori banda. Ad esempio, esegui un processo di pulizia
separato che pulisce dopo le chiamate duplicate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-10 UTC."],[[["\u003cp\u003eEventarc Advanced handles transient errors, such as temporary service unavailability, by automatically retrying them using an exponential backoff delay, with default settings of up to 5 attempts and a maximum 60-second delay, starting from a 1-second delay.\u003c/p\u003e\n"],["\u003cp\u003ePersistent errors, including those where retries are exhausted or events fail before routing, require manual identification and handling, and these errors can be found through error codes that are considered non-retryable.\u003c/p\u003e\n"],["\u003cp\u003eUsers can customize the retry policy for transient errors in Eventarc Advanced by adjusting the maximum attempts, minimum delay, and maximum delay through the Google Cloud console or the gcloud command-line tool.\u003c/p\u003e\n"],["\u003cp\u003eTo manage persistent errors, Eventarc Advanced allows for the archiving of event messages to a BigQuery table, where users can then identify and re-publish failed messages using the Eventarc Publishing API.\u003c/p\u003e\n"],["\u003cp\u003eEvent handlers should be designed to be idempotent, ensuring that multiple executions of the same event do not lead to unintended changes, often achievable through the use of idempotency keys or attributes like \u003ccode\u003exgooglemessageuid\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,["# Retry events\n\n[Advanced](/eventarc/advanced/docs/overview)\n\nAn event can be rejected for multiple reasons. For example, the event receiver\nservice might be temporarily unavailable due to an outage; an error might be\nencountered by the service when processing an event; or service resources\nmight become exhausted. *Transient errors* like this can be retried.\n\nAn event can also fail to be delivered to the event receiver. For example, the\nevent might not match the expected schema that is configured, or the mediation\nof the event might fail before the event message can be routed to its final\ndestination. Such cases result in *persistent errors*.\n\nTransient errors\n----------------\n\nEventarc Advanced provides you with the capability to handle\ntransient errors. These transient errors can be retried and include those with\nthe following error codes:\n\n- HTTP `408 Request Timeout`\n- HTTP `409 Conflict`\n- HTTP `429 Too Many Requests`\n- HTTP `500 Internal Server Error`\n- HTTP `502 Bad Gateway`\n- HTTP `503 Service Unavailable`\n- HTTP `504 Gateway Time-out`\n\nPersistent errors\n-----------------\n\nIn contrast to transient errors, persistent errors include the following:\n\n- Errors that occur when the number of configured retries is exhausted\n- Errors that occur when an event fails before it can be routed to its destination\n- Errors that result in an error code that is considered non-retryable; for example, error codes other than those listed for transient errors\n\nYou can [manually identify persistent errors and handle them](#handle-persistent)\nappropriately.\n\nRetry transient errors\n----------------------\n\nEventarc Advanced uses an exponential backoff delay to handle\nerrors that can be retried. The default retry policy starts with a one-second\ndelay, and the delay is doubled after each failed attempt (up to a maximum of 60\nseconds and five attempts).\n\nYou can change the default retry policy using the Google Cloud console or the\n[`gcloud eventarc pipelines update`](/sdk/gcloud/reference/eventarc/pipelines/update)\ncommand.\n\nNote that the default backoff factor of `2` can't be changed. \n\n### Console\n\n1. In the Google Cloud console, go to the **Eventarc**\n \\\u003e **Pipelines** page.\n\n\n [Go to Pipelines](https://console.cloud.google.com/eventarc/pipelines)\n\n \u003cbr /\u003e\n\n2. Click the name of the pipeline.\n\n3. In the **Pipeline details** page, click **Edit**.\n\n4. On the **Edit pipeline** page, in the **Retry policy** section, modify\n the following fields:\n\n - **Max attempts** : the number of retries; default is `5` attempts. Can be any positive real number. If set to `1`, no retry policy is applied and only one attempt is made to deliver a message.\n - **Min delay (seconds)** : the initial delay in seconds; default is `1` second. Must be between `1` and `600`.\n - **Max delay (seconds)** : the maximum delay in seconds; default is `60` seconds. Must be between `1` and `600`.\n\n You can configure a linear backoff by setting the minimum and maximum\n delays to the same value.\n5. Click **Save**.\n\n### gcloud\n\n gcloud eventarc pipelines update \u003cvar translate=\"no\"\u003ePIPELINE_NAME\u003c/var\u003e \\\n --min-retry-delay=\u003cvar translate=\"no\"\u003eMIN_DELAY\u003c/var\u003e \\\n --max-retry-delay=\u003cvar translate=\"no\"\u003eMAX_DELAY\u003c/var\u003e \\\n --max-retry-attempts=\u003cvar translate=\"no\"\u003eMAX_ATTEMPTS\u003c/var\u003e\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003ePIPELINE_NAME\u003c/var\u003e: the ID or fully qualified identifier of the pipeline.\n- \u003cvar translate=\"no\"\u003eMIN_DELAY\u003c/var\u003e: the initial delay in seconds; default is `1` second. Must be between `1` and `600`.\n- \u003cvar translate=\"no\"\u003eMAX_DELAY\u003c/var\u003e: the maximum delay in seconds; default is `60` seconds. Must be between `1` and `600`.\n- \u003cvar translate=\"no\"\u003eMAX_ATTEMPTS\u003c/var\u003e: the number of retries; default is `5` attempts. Can be any positive real number. If set to `1`, no retry policy is applied and only one attempt is made to deliver a message.\n\nThe following example configures a linear backoff by setting the minimum and\nmaximum delays to the same value: \n\n gcloud eventarc pipelines update my-pipeline \\\n --min-retry-delay=4 \\\n --max-retry-delay=4 \\\n --max-retry-attempts=5\n\nArchive messages to handle persistent errors\n--------------------------------------------\n\nYou can write messages to a BigQuery table as they are received. This\nlets you manually identify persistent errors and handle them appropriately.\n\nThe following provides an overview of the steps required to archive your event\nmessages, identify persistent errors, and retry the affected events.\n\n1. [Create a bus](/eventarc/advanced/docs/publish-events/create-bus). Configure the bus appropriately; for example, to [publish events from Google sources](/eventarc/advanced/docs/publish-events/publish-events-google-sources).\n2. [Create a Pub/Sub topic](/pubsub/docs/create-topic). This Pub/Sub topic will be the target destination for your pipeline.\n3. [Create a BigQuery subscription](/pubsub/docs/bigquery) for the Pub/Sub topic. A BigQuery subscription is a type of export subscription that writes messages to an existing BigQuery table as they are received. Alternatively, you can create the table when you create the BigQuery subscription.\n4. [Create a pipeline and enrollment](/eventarc/advanced/docs/receive-events/create-enrollment)\n that routes every message received by the bus (using `--cel-match=\"true\"`) to\n the Pub/Sub topic. Configure a retry policy for the pipeline.\n\n For example, the following commands create a pipeline and an enrollment: \n\n gcloud eventarc pipelines create my-archive-pipeline \\\n --destinations=pubsub_topic='my-archive-topic' \\\n --min-retry-delay=1 \\\n --max-retry-delay=20 \\\n --max-retry-attempts=6 \\\n --location=us-central1\n\n gcloud eventarc enrollments create my-archive-enrollment \\\n --cel-match=\"true\" \\\n --destination-pipeline=my-archive-pipeline \\\n --message-bus=my-message-bus \\\n --message-bus-project=my-google-cloud-project \\\n --location=us-central1\n\n5. [Route your pipeline logs](/logging/docs/export/configure_export_v2) to\n another BigQuery dataset.\n\n You should now have two separate BigQuery datasets: one that\n stores every message received by your Eventarc Advanced bus and one\n that stores your pipeline logs.\n6. To identify messages that have failed, use a\n [query statement to join](/bigquery/docs/reference/standard-sql/query-syntax#join_types)\n both BigQuery datasets on the `message_uid` field.\n\n7. After identifying any failed messages, you can publish them to your bus again\n using the [Eventarc Publishing API](/eventarc/docs/reference/publishing/rest).\n For example, you can\n [deploy a Cloud Run service or job](/run/docs/overview/what-is-cloud-run)\n to read the messages from BigQuery and\n [publish them directly](/eventarc/advanced/docs/publish-events/publish-events-direct-format)\n to the Eventarc Advanced bus.\n\nMake event handlers idempotent\n------------------------------\n\nEvent handlers that can be retried should be idempotent, using the following\ngeneral guidelines:\n\n- Many external APIs let you supply an idempotency key as a parameter. If you are using such an API, you should use the event source and ID as the idempotency key. (Producers must ensure that [source + id](/eventarc/advanced/docs/receive-events/use-cel#attributes) is unique for each distinct event.)\n- Additionally, you can use a CloudEvents attribute, `xgooglemessageuid`, to provide idempotency. The value of this attribute is the same as the `message_uid` field in Eventarc Advanced messages. It uniquely identifies the action of publishing an event. For example, if the same event is published twice to a bus, each event will have a different `xgooglemessageuid` value when sent to an event handler.\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 your service, independent of the code. For example, persist state somewhere recording that a given event ID has already been processed.\n- Deal with duplicate calls out-of-band. For example, have a separate clean up process that cleans up after duplicate calls.\n\nWhat's next\n-----------\n\n- [Troubleshoot issues](/eventarc/advanced/docs/troubleshoot)\n- [View audit logs](/eventarc/advanced/docs/audit-logs)"]]