Todos los productos
Search
Centro de documentos

API Gateway:Plugins de circuit breaker (solo para instancias dedicadas)

Última actualización: Sep 03, 2026

Los circuit breakers protegen su sistema cuando el rendimiento del backend se degrada. Configure las condiciones de activación, la duración del estado abierto y los backends alternativos para instancias dedicadas.

Límites

  • Solo para instancias dedicadas.

  • Máximo 512 caracteres por expresión.

  • Tamaño máximo de configuración del plugin: 50 KB.

1. Descripción general

De forma predeterminada, si ocurren 1,000 tiempos de espera en un backend de API dentro de 30 segundos, el circuit breaker se activa y entra en estado abierto durante 90 segundos. Durante este periodo, todas las solicitudes devuelven Status=503 con el código de error X-Ca-Error-Code=D503CB. Después de 90 segundos, el circuit breaker entra en estado semiabierto y permite el paso de un número reducido de solicitudes. Si el backend se recupera, el circuit breaker se cierra y las solicitudes continúan con normalidad.

En una instancia dedicada, el plugin de circuit breaker le permite personalizar la siguiente configuración del circuit breaker:

  • Condición de activación: el circuit breaker se activa cuando los tiempos de espera del backend o los errores especificados superan un umbral dentro de una ventana de tiempo.

  • Ventana de tiempo para evaluar las condiciones de activación.

  • Duración del estado abierto después de que se activa el circuit breaker.

  • Backend alternativo para las solicitudes mientras el circuit breaker está abierto.

2. Configuraciones

Las configuraciones del plugin de circuit breaker solo aplican a las API en instancias dedicadas. En instancias serverless, se utiliza la configuración predeterminada del circuit breaker incluso si hay un plugin vinculado a la API.

2.1 Configurar directivas de degradación basadas en tiempos de espera del backend

Configure una directiva de degradación basada en los tiempos de espera del backend. Una solicitud cuenta como tiempo de espera si el backend no responde dentro del periodo de tiempo de espera definido por la API.

timeoutThreshold: 15         # The threshold of the number of occurrences of timeout at the backend.
windowInSeconds: 30          # The time window during which the number of occurrences of timeout at the backend is checked by the circuit breaker to determine whether to trip.
openTimeoutSeconds: 15       # The period of time during which the circuit breaker stays open after it trips.
downgradeBackend:            # The backend to which API requests are directed when the circuit breaker is open.
  type: mock
  statusCode: 418

Campos:

  • timeoutThreshold: la cantidad de tiempos de espera del backend que activa el circuit breaker. Valor máximo: 5000. Un valor demasiado pequeño provoca activaciones frecuentes.

  • windowInSeconds: la ventana de tiempo de evaluación. Valores válidos: de 10 a 90. Unidad: segundos.

  • openTimeoutSeconds: la duración durante la cual el circuit breaker permanece abierto. Valores válidos: de 15 a 300. Unidad: segundos.

  • downgradeBackend: opcional. El backend alternativo que se usa mientras el circuit breaker está abierto.

2.2 Configurar una directiva de degradación basada en el tiempo de respuesta del backend

Configure una directiva de degradación basada en el tiempo de respuesta del backend, medido desde que la puerta de enlace envía una solicitud hasta que recibe una respuesta.

errorThreshold: 10         # The threshold of the number of occurrences of long response at the backend.
windowInSeconds: 60          # The time window during which the number of occurrences of long response at the backend is checked by the circuit breaker to determine whether to trip.
openTimeoutSeconds: 120        # The period of time during which the circuit breaker stays open after it trips.
errorCondition: "$LatencyMilliSeconds > 500"     # The conditional expression that is used to determine whether the backend response is counted as a long response. In this example, if the backend response time exceeds 500 ms, the response is considered as a long response.
downgradeBackend:               # The backend to which API requests are directed when the circuit breaker is open.
  type: mock
  statusCode: 403

Campos:

  • errorThreshold: la cantidad de respuestas lentas que activa el circuit breaker.

  • windowInSeconds: la ventana de tiempo de evaluación. Valores válidos: de 10 a 90. Unidad: segundos.

  • openTimeoutSeconds: la duración durante la cual el circuit breaker permanece abierto. Valores válidos: de 15 a 300. Unidad: segundos.

  • errorCondition: la expresión que define una respuesta lenta. Variables disponibles: $LatencyMilliSeconds (milisegundos) y $LatencySeconds (segundos).

  • downgradeBackend: opcional. El backend alternativo que se usa mientras el circuit breaker está abierto.

2.3 Configurar una directiva de degradación basada en errores del backend

Configure una directiva de degradación basada en los códigos de error del backend.

errorCondition: "$StatusCode == 503"  # The conditional expression that specifies the error whose number of occurrences is checked by the circuit breaker to determine whether to trip.
errorThreshold: 1000                  # The threshold of the number of occurrences of the specified error.
windowInSeconds: 30                   # The time window during which the number of occurrences of the specified error at the backend is checked by the circuit breaker to determine whether to trip.
openTimeoutSeconds: 15                # The period of time during which the circuit breaker stays open after it trips.
downgradeBackend:                     # The backend to which API requests are directed when the circuit breaker is open.
  type: "HTTP"
  address: "http://api.foo.com"
  path: "/system-busy.json"
  method: GET
  • errorCondition: la expresión de error. Variables disponibles: $StatusCode (código de respuesta) y $LatencySeconds (latencia en segundos).

    • Por ejemplo, la expresión $StatusCode = 503 or $StatusCode = 504 se evalúa como verdadera si el código de estado de la respuesta del backend es 503 o 504.

    • Por ejemplo, $LatencySeconds > 30 indica que el tiempo de espera supera los 30 segundos.

  • errorThreshold: la cantidad de errores coincidentes que activa el circuit breaker.

  • windowsInSeconds: la ventana de tiempo de evaluación. Valores válidos: de 10 a 90. Unidad: segundos.

  • openTimeoutSeconds: la duración durante la cual el circuit breaker permanece abierto. Valores válidos: de 15 a 300. Unidad: segundos.

  • downgradeBackend: opcional. El backend alternativo que se usa mientras el circuit breaker está abierto.

2.4 Control preciso del estado

API Gateway se ejecuta en varios nodos de clúster, y cada uno mantiene su propio estado del circuit breaker. Esto puede causar imprecisiones de estado entre nodos. Para habilitar un estado del circuit breaker globalmente consistente, agregue el campo useGlobalState a la configuración de su plugin:

---
timeoutThreshold: 15 # The threshold of the number of occurrences of timeout at the backend.
windowInSeconds: 30 # The time window during which the number of occurrences of timeout at the backend is checked by the circuit breaker to determine whether to trip.
openTimeoutSeconds: 15 # The period of time during which the circuit breaker stays open after it trips.
useGlobalState: true # Accurate status control is enabled.
downgradeBackend: # The backend to which API requests are directed when the circuit breaker is open.
 type: mock
 statusCode: 302
 body: |
 <result>
 <errorCode>I's a teapot</errorCode>
 </result>

El valor predeterminado de useGlobalState es false. Establecerlo en true habilita un estado preciso a costa de una ligera sobrecarga de rendimiento, lo cual no afecta el QPS garantizado ni el SLA de su instancia.

2.5 Configurar una directiva de degradación por porcentaje

El circuit breaker se activa cuando se cumple cualquiera de las cuatro condiciones siguientes. Todas las condiciones tienen la misma prioridad.

  • errorThreshold: la cantidad de errores del backend (que coinciden con errorCondition) que activa el circuit breaker.

  • timeoutThreshold: la cantidad de tiempos de espera del backend que activa el circuit breaker.

  • errorThresholdByPercent: el umbral de tasa de errores, evaluado con respecto a la tasa de errores de la ventana de tiempo anterior.

  • timeoutThresholdByPercent: el umbral de tasa de tiempos de espera como porcentaje del total de solicitudes en una ventana de tiempo.

Ejemplo:

---
windowInSeconds: 3  # The time window during which the circuit breaker determines whether to trip. Valid values: 10 to 90. Unit: seconds.
openTimeoutSeconds: 3
errorThreshold: 90  # The threshold of the number of occurrences of the specified error.
timeoutThreshold: 90   # The threshold of the number of occurrences of timeout.
errorThresholdByPercent: 20    # The threshold of the percentage of requests in which the specified error occurs to the total number of requests.
timeoutThresholdByPercent: 20   # The threshold of the percentage of requests in which timeout occurs to the total number of requests.
errorCondition: "$StatusCode = 500"   # The error condition.
downgradeBackend:
  type: mock
  statusCode: 418
  body: |
    <result>
      <errorCode>I's a teapot</errorCode>
    </result>
Importante
  • Los umbrales porcentuales requieren como mínimo 100 solicitudes en una ventana de tiempo para surtir efecto.

  • En este ejemplo, errorThreshold: 90 y timeoutThreshold: 90 provocan que el circuit breaker se active si los errores o tiempos de espera superan 90 en una ventana de tiempo.

  • errorThresholdByPercent: 20 y timeoutThresholdByPercent: 20 activan el circuit breaker si la ventana de tiempo anterior tuvo al menos 100 solicitudes y la tasa de errores o tiempos de espera superó el 20%.

  • Las directivas de tiempo de espera basadas en porcentaje son compatibles a partir de la versión de junio de 2023.

2.6 Limitar solicitudes cuando se activa el circuit breaker

Cuando el circuit breaker se activa, se aplica una configuración temporal de limitación a todo el tráfico mientras el circuit breaker está abierto o semiabierto:

---
windowInSeconds: 1             # The time window in which the circuit breaker checks the number of occurrences of timeout at the backend.
openTimeoutSeconds: 15          # The period of time during which the circuit breaker stays open after it trips.
errorThreshold: 3
errorCondition: "$LatencyMilliSeconds > 1"
downgradeTrafficLimit:               # The backend to which API requests are directed when the circuit breaker is open.
  limit: 2
  period: MINUTE

3. Configuración del backend alternativo

Use downgradeBackend para especificar un backend alternativo cuando el circuit breaker está abierto. La configuración del backend debe coincidir con el formato de especificación de API utilizado en API Gateway (Import Swagger files to create APIs with API Gateway extensions). Se admiten los siguientes tipos de backend:

  • Backend HTTP

---
backend:
  type: HTTP
  address: "http://10.10.100.2:8000"
  path: "/users/{userId}"
  method: GET
  timeout: 7000        
  • Backend HTTP (VPC)

---
backend:
  type: HTTP-VPC
  vpcAccessName: vpcAccess1
  path: "/users/{userId}"
  method: GET
  timeout: 10000        
  • Function Compute

---
backend:
  type: FC
  fcRegion: cn-shanghai
  serviceName: fcService
  functionName: fcFunction
  arn: "acs:ram::111111111:role/aliyunapigatewayaccessingfcrole"        
  • MOCK

---
backend:
  type: MOCK
  mockResult: "mock result sample"
  mockStatusCode: 200
  mockHeaders:
    - name: Content-Type
      value: text-plain
    - name: Content-Language
      value: zhCN

4. Códigos de error

Código de error

Código de estado HTTP

Mensaje

Descripción

D503BB

503

Backend circuit breaker busy

La API está protegida por su circuit breaker.

D503CB

503

Backend circuit breaker open, ${Reason}

El circuit breaker está abierto. Compruebe el rendimiento del backend antes de volver a probar las llamadas a la API.