Un evento se puede rechazar por varios motivos. Por ejemplo, es posible que el servicio de receptor de eventos no esté disponible temporalmente debido a una interrupción, que el servicio encuentre un error al procesar un evento o que se agoten los recursos del servicio. Se puede volver a intentar solucionar los errores transitorios como este.
Un evento también puede no entregarse al receptor de eventos. Por ejemplo, es posible que el evento no coincida con el esquema esperado que se configuró, o que la mediación del evento falle antes de que el mensaje del evento pueda enrutarse a su destino final. Estos casos generan errores persistentes.
Errores transitorios
Eventarc Advanced te brinda la capacidad de controlar errores transitorios. Estos errores transitorios se pueden volver a intentar y se incluyen aquellos con los siguientes códigos de error:
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
Errores persistentes
A diferencia de los errores transitorios, los errores persistentes incluyen los siguientes:
Errores que se producen cuando se agota la cantidad de reintentos configurados
Errores que se producen cuando falla un evento antes de que se pueda enrutar a su destino
Errores que generan un código de error que se considera que no se puede reintentar; por ejemplo, códigos de error que no sean los que se enumeran para los errores transitorios
Eventarc Advanced usa un retraso con retirada exponencial para manejar errores que se pueden reintentar. La política de reintentos predeterminada comienza con una demora de un segundo, y la demora se duplica después de cada intento fallido (hasta un máximo de 60 segundos y cinco intentos).
Puedes cambiar la política de reintentos predeterminada con la consola de Google Cloud o el comandogcloud eventarc pipelines update.
Ten en cuenta que no se puede cambiar el factor de espera predeterminado de 2.
Console
En la consola de Google Cloud , ve a la página Eventarc>Canalizaciones.
En la página Detalles de la canalización, haz clic en Editar.
En la página Editar canalización, en la sección Política de reintentos, modifica los siguientes campos:
Cantidad máxima de intentos: Es la cantidad de reintentos. El valor predeterminado es 5 intentos. Puede ser cualquier número real positivo. Si se establece en 1, no se aplica ninguna política de reintentos y solo se realiza un intento para entregar un mensaje.
Retraso mín. (segundos): Es el retraso inicial en segundos. El valor predeterminado es 1 segundos. Debe estar entre 1 y 600.
Retraso máx. (segundos): Es el retraso máximo en segundos. El valor predeterminado es 60 segundos. Debe estar entre 1 y 600.
Puedes configurar una espera exponencial lineal estableciendo los retrasos mínimo y máximo en el mismo valor.
PIPELINE_NAME: Es el ID o el identificador completamente calificado de la canalización.
MIN_DELAY: Es la demora inicial en segundos. El valor predeterminado es 1 segundo. Debe estar entre 1 y 600.
MAX_DELAY: Es la demora máxima en segundos. El valor predeterminado es 60 segundos. Debe estar entre 1 y 600.
MAX_ATTEMPTS: Es la cantidad de reintentos. El valor predeterminado es 5 intentos. Puede ser cualquier número real positivo. Si se establece en 1, no se aplica ninguna política de reintentos y solo se realiza un intento para entregar un mensaje.
En el siguiente ejemplo, se configura una retirada lineal estableciendo los retrasos mínimo y máximo en el mismo valor:
Archiva mensajes para controlar errores persistentes
Puedes escribir mensajes en una tabla de BigQuery a medida que se reciben. Esto te permite identificar manualmente los errores persistentes y controlarlos de forma adecuada.
A continuación, se proporciona una descripción general de los pasos necesarios para archivar los mensajes de eventos, identificar los errores persistentes y volver a intentar los eventos afectados.
Crea una suscripción a BigQuery para el tema de Pub/Sub. Una suscripción a BigQuery es un tipo de suscripción de exportación que escribe los mensajes en una tabla de BigQuery existente a medida que se reciben. También puedes crear la tabla cuando crees la suscripción a BigQuery.
Crea una canalización y una inscripción que enrute cada mensaje que recibe el bus (con --cel-match="true") al tema de Pub/Sub. Configura una política de reintentos para la canalización.
Por ejemplo, los siguientes comandos crean una canalización y una inscripción:
Ahora deberías tener dos conjuntos de datos de BigQuery separados: uno que almacena cada mensaje que recibe tu bus avanzado de Eventarc y otro que almacena los registros de tu canalización.
Para identificar los mensajes que fallaron, usa una instrucción de consulta para unir ambos conjuntos de datos de BigQuery en el campo message_uid.
Haz que los controladores de eventos sean idempotentes
Los controladores de eventos que se pueden reintentar deben ser idempotentes con los siguientes
lineamientos generales:
Muchas APIs externas te permiten proporcionar una clave de idempotencia como parámetro. Si usas una API de este tipo, debes usar la fuente y el ID del evento como la clave de idempotencia. (Los productores deben asegurarse de que source + id sea único para cada evento distinto).
Además, puedes usar un atributo de CloudEvents, xgooglemessageuid, para proporcionar idempotencia. El valor de este atributo es el mismo que el del campo message_uid en los mensajes avanzados de Eventarc. Identifica de forma única la acción de publicar un evento. Por ejemplo, si el mismo evento se publica dos veces en un bus, cada evento tendrá un valor de xgooglemessageuid diferente cuando se envíe a un controlador de eventos.
La idempotencia funciona bien con la entrega "al menos una vez", ya que permite que los reintentos
sean seguros. Por lo tanto, una recomendación general para escribir un código confiable es combinar la idempotencia con los intentos reiterados.
Asegúrate de que tu código sea idempotente de forma interna. Por ejemplo:
Asegúrate de que puedan ocurrir mutaciones más de una vez sin que cambie el resultado.
Consulta el estado de la base de datos en una transacción antes de mutar el estado.
Asegúrate de que todos los efectos secundarios sean idempotentes en sí.
Debes imponer una verificación transaccional fuera del servicio, sin importar el código.
Por ejemplo, conserva el estado en algún lugar que registre si ya se procesó un ID de evento determinado.
Administra las llamadas duplicadas fuera de banda. Por ejemplo, implementa un proceso de limpieza
independiente que borre las llamadas duplicadas.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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)"]]