Os circuit breakers protegem seu sistema quando o desempenho do backend degrada. Configure as condições de disparo, as durações de abertura e os backends de fallback para instâncias dedicadas.
Limites
Disponível apenas para instâncias dedicadas.
Máximo de 512 caracteres por expressão.
Tamanho máximo da configuração do plug-in: 50 KB.
1. Visão geral
Por padrão, se ocorrerem 1.000 timeouts no backend de uma API em 30 segundos, o circuit breaker dispara e entra no estado aberto por 90 segundos. Durante esse período, todas as requisições retornam Status=503 com o código de erro X-Ca-Error-Code=D503CB. Após 90 segundos, o circuit breaker entra no estado semiaberto e permite a passagem de um pequeno número de requisições. Se o backend se recuperar, o circuit breaker fecha e as requisições retomam normalmente.
Em uma dedicated instance, o circuit breaker plugin permite personalizar as seguintes configurações de circuit breaker:
Condição de disparo: o circuit breaker abre quando os timeouts do backend ou erros especificados ultrapassam um limiar dentro de uma janela de tempo.
Janela de tempo para avaliação das condições de disparo.
Duração do estado aberto após o disparo do circuit breaker.
Backend de fallback para requisições enquanto o circuit breaker estiver aberto.
2. Configurações
As configurações do plug-in de circuit breaker aplicam-se apenas a APIs em instâncias dedicadas. Em instâncias serverless, o sistema usa a configuração padrão do circuit breaker mesmo que um plug-in esteja vinculado à API.
2,1 Configurando políticas de degradação baseadas em timeouts do backend
Configure uma política de degradação baseada em timeouts do backend. Uma requisição conta como timeout se o backend não responder dentro do período de timeout definido pela 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: quantidade de timeouts do backend que aciona o circuit breaker. Valor máximo: 5000. Um valor muito baixo causa disparos frequentes.windowInSeconds: janela de tempo de avaliação. Valores válidos: 10 a 90. Unidade: segundos.openTimeoutSeconds: duração em que o circuit breaker permanece aberto. Valores válidos: 15 a 300. Unidade: segundos.downgradeBackend: opcional. Backend de fallback usado enquanto o circuit breaker estiver aberto.
2,2 Configurando uma política de degradação baseada no tempo de resposta do backend
Defina uma política de degradação baseada no tempo de resposta do backend, medido desde o envio da requisição pelo gateway até o recebimento da resposta.
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: número de respostas lentas que aciona o circuit breaker.windowInSeconds: janela de tempo de avaliação. Valores válidos: 10 a 90. Unidade: segundos.openTimeoutSeconds: duração em que o circuit breaker permanece aberto. Valores válidos: 15 a 300. Unidade: segundos.errorCondition: expressão que define uma resposta lenta. Variáveis disponíveis:$LatencyMilliSeconds(milissegundos) e$LatencySeconds(segundos).downgradeBackend: opcional. Backend de fallback usado enquanto o circuit breaker estiver aberto.
2,3 Configure uma política de degradação baseada em erros do backend
Estabeleça uma política de degradação baseada nos códigos de erro do 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: expressão de erro. Variáveis disponíveis:$StatusCode(código de resposta) e$LatencySeconds(latência em segundos).Por exemplo, a expressão
$StatusCode = 503 or $StatusCode = 504retorna verdadeiro se o código de status da resposta do backend for 503 ou 504.Como outro exemplo,
$LatencySeconds > 30indica que o timeout excede 30 segundos.
errorThreshold: quantidade de erros correspondentes que aciona o circuit breaker.windowsInSeconds: janela de tempo de avaliação. Valores válidos: 10 a 90. Unidade: segundos.openTimeoutSeconds: duração em que o circuit breaker permanece aberto. Valores válidos: 15 a 300. Unidade: segundos.downgradeBackend: opcional. Backend de fallback usado enquanto o circuit breaker estiver aberto.
2,4 Controle preciso de status
O API Gateway executa em vários nós de cluster, e cada um mantém seu próprio estado de circuit breaker. Isso pode causar imprecisão de status entre os nós. Para ative um status de circuit breaker globalmente consistente, adicione o campo useGlobalState à configuração do seu plug-in:
---
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>
O valor padrão de useGlobalState é false. Definir esse valor como true ativa o status preciso ao custo de uma pequena sobrecarga de desempenho, sem afetar o QPS garantido nem o SLA da sua instância.
2,5 Configure uma política de degradação por porcentagem
O circuit breaker dispara quando qualquer uma das quatro condições a seguir for atendida. Todas as condições têm prioridade igual.
errorThreshold: número de erros do backend (correspondentes aerrorCondition) que aciona o circuit breaker.timeoutThreshold: quantidade de timeouts do backend que aciona o circuit breaker.errorThresholdByPercent: limiar da taxa de erro, avaliado em relação à taxa de erro da janela de tempo anterior.timeoutThresholdByPercent: limiar da taxa de timeout como porcentagem do total de requisições em uma janela de tempo.
Exemplo:
---
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>
Os limiares de porcentagem exigem pelo menos 100 requisições em uma janela de tempo para entrar em vigor.
Neste exemplo,
errorThreshold: 90etimeoutThreshold: 90fazem o circuit breaker disparar se os erros ou timeouts ultrapassarem 90 em uma janela de tempo.Já
errorThresholdByPercent: 20etimeoutThresholdByPercent: 20acionam o circuit breaker se a janela de tempo anterior tiver tido pelo menos 100 requisições e a taxa de erro ou timeout tiver excedido 20%.Políticas de timeout baseadas em porcentagem são suportadas a partir da versão de junho de 2023.
2,6 Limite requisições quando o circuit breaker disparar
Quando o circuit breaker dispara, uma configuração temporária de limitação aplica-se a todo o tráfego enquanto o circuit breaker estiver aberto ou semiaberto:
---
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. Configuração do backend de fallback
Use downgradeBackend para especifique um backend de fallback quando o circuit breaker estiver aberto. A configuração do backend deve corresponder ao formato de especificação de API usado no API Gateway (Importar arquivos Swagger para crie APIs com extensões do API Gateway). Os seguintes tipos de backend são suportados:
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 erro
|
Código de erro |
Código de status HTTP |
Mensagem |
Descrição |
|
D503BB |
503 |
Backend circuit breaker busy |
A API está protegida pelo seu circuit breaker. |
|
D503CB |
503 |
Backend circuit breaker open, ${Reason} |
O circuit breaker está aberto. Verifique o desempenho do backend antes de testar novamente as chamadas de API. |