Exemplo de implementação do padrão circuit breaker em python

Overview

fast-circuit-breaker

Circuit breakers existem para permitir que uma parte do seu sistema falhe sem destruir todo seu ecossistema de serviços. Michael Nygard

Nesse exemplo vamos executar o serviço de oferta (fria) que se comunica com o serviço de oferta do parceiro (quente). Depois vamos provocar uma indisponibilidade no serviço de oferta do parceiro, retornando uma oferta fria (fallback) do serviço de oferta.

Fluxo de oferta!

Veremos que em certo momento o serviço de oferta deixará de se comunicar com o serviço de oferta do parceiro, abrindo o circuito (open), após um determinado tempo o serviço de oferta continuará tentando restabelecer a comunicação com serviço de oferta do parceiro, circuito meio-aberto (half-open).

Quando a comunicação entre os serviços for restabelecida, o circuito será fechado (close).

Observe abaixo o fluxo de mudança de estado do padrão circuit breaker.

Estados do circuit breaker!

Instalação

Crie um ambiente virtual.

python3 -m venv venv

Ative o ambiente virtual.

source venv/bin/activate

Instale as dependências do projeto.

pip install -r requirements.txt

Uso

Execute o serviço de oferta do parceiro, responsável por retornar uma oferta quente (hot).

python partner_offer_service.py

Execute o serviço de oferta responsável por buscar oferta quente no serviço de oferta do parceiro.

HTTPX_LOG_LEVEL=debug python offer_service.py

Vamos testar a busca de oferta, através de uma chamada HTTP do qualquer cliente (browser, curl, httpie), o exemplo abaixo usa o httpie.

http ":8001/offer"

A resposta deve ser uma oferta quente do serviço de oferta do parceiro.

"Hot offer 24:48"

Veja nos logs do serviço de oferta, a resposta OK do serviço de oferta do parceiro.

DEBUG [2021-06-19 11:03:03] httpx._client - HTTP Request: GET http://127.0.0.1:8000/offer/hot "HTTP/1.1 200 OK"

Circuit breaker

Vamos alterar o arquivo partner_offer_service.py na linha 13 para retornar o código de erro 500 na resposta do recurso GET /offer/hot, conforme exemplo abaixo.

return Response(content=body, status_code=500)

Atenção: os serviços tem a configuração de recarregar (reload) a aplicação toda vez que um arquivo é alterado.

Vamos chamar o serviço de busca de oferta novamente.

http ":8001/offer"

A resposta agora deve ser uma oferta fria, retornada através de uma função (fallback) do serviço de oferta.

"Cold offer fallback 47:32"

Veja nos logs do serviço de oferta um erro na comunicação com o serviço de oferta do parceiro.

DEBUG [2021-06-19 20:44:27] httpx._client - HTTP Request: GET http://127.0.0.1:8000/offer/hot "HTTP/1.1 500 Internal Server Error"

Vamos verificar o estado do circuito do serviço de oferta.

http ":8001/offer/circuit"

A resposta mostra que o circuito está com o estado fechado (current_state) e 1 falha fail_counter.

{
  "current_state": "closed",
  "fail_counter": 1
}

Antes de prosseguirmos vamos analisar a configuração do circuito no arquivo circuit_breaker.py, para mais informações consulte a documentação da biblioteca pybreaker.

  1. fail_max: Quantidade máxima de falhas.
  2. reset_timeout: Limite de tempo (segundos) para redefinição do estado do circuito.
  3. state_storage: Onde o estado será armazenado (Memória, Redis, etc).
  4. listeners: Ouvintes que serão notificados em cada evento do circuito
circuit_breaker = CircuitBreaker(
    fail_max=3,
    reset_timeout=15,
    state_storage=state_storage,
    listeners=[LogListener()]
)

Vamos chamar o recurso de buscar oferta mais 3 vezes.

http ":8001/offer"

Após 3 falhas (fail_max) na comunicação com o serviço de oferta do parceiro, o circuito é aberto (open).

Vamos verificar o estado do circuito mais uma vez.

http ":8001/offer/circuit"

Na resposta o circuito está aberto (current_state) com 3 falhas fail_counter.

{
  "current_state": "open",
  "fail_counter": 3
}

Observe que no estado aberto, não há registro de log de comunicação, pois o circuito protege o serviço de oferta do parceiro de receber chamadas por um determinado período de tempo.

No estado aberto (open), há cada 15 segundos (reset_timeout) o circuito entrará no estado meio-aberto (half-open) para tentar restabelecer a comunicação com o serviço de oferta do parceiro.

Podemos acompanhar (terminal) os eventos do circuito através dos logs da classe LogListener registrada como ouvinte na instancia do circuito.

Antes do circuito invocar a função.
Quando uma invocação de função levanta uma exceção.
Quando o estado do circuito mudou (open).
Quando o estado do circuito mudou (half-open).
Quando o estado do circuito mudou (open).

Caso alteremos o código da resposta do serviço de oferta do parceiro para 200, então o circuito será fechado (close), ou caso a resposta continue com código de erro 500 o circuito continuará aberto.

Owner
James G Silva
Desenvolvedor de software, ajudo pessoas nos primeiros passos da programação.
James G Silva
OHLC Average Prediction of Apple Inc. Using LSTM Recurrent Neural Network

Stock Price Prediction of Apple Inc. Using Recurrent Neural Network OHLC Average Prediction of Apple Inc. Using LSTM Recurrent Neural Network Dataset:

Nouroz Rahman 410 Jan 05, 2023
[CVPRW 21] "BNN - BN = ? Training Binary Neural Networks without Batch Normalization", Tianlong Chen, Zhenyu Zhang, Xu Ouyang, Zechun Liu, Zhiqiang Shen, Zhangyang Wang

BNN - BN = ? Training Binary Neural Networks without Batch Normalization Codes for this paper BNN - BN = ? Training Binary Neural Networks without Bat

VITA 40 Dec 30, 2022
NEATEST: Evolving Neural Networks Through Augmenting Topologies with Evolution Strategy Training

NEATEST: Evolving Neural Networks Through Augmenting Topologies with Evolution Strategy Training

Göktuğ Karakaşlı 16 Dec 05, 2022
Codes for our IJCAI21 paper: Dialogue Discourse-Aware Graph Model and Data Augmentation for Meeting Summarization

DDAMS This is the pytorch code for our IJCAI 2021 paper Dialogue Discourse-Aware Graph Model and Data Augmentation for Meeting Summarization [Arxiv Pr

xcfeng 55 Dec 27, 2022
The implementation of the algorithm in the paper "Safe Deep Semi-Supervised Learning for Unseen-Class Unlabeled Data" published in ICML 2020.

DS3L This is the code for paper "Safe Deep Semi-Supervised Learning for Unseen-Class Unlabeled Data" published in ICML 2020. Setups The code is implem

Guolz 36 Oct 19, 2022
A highly efficient and modular implementation of Gaussian Processes in PyTorch

GPyTorch GPyTorch is a Gaussian process library implemented using PyTorch. GPyTorch is designed for creating scalable, flexible, and modular Gaussian

3k Jan 02, 2023
Hack Camera, Microphone, Location, Clipboard With Just a Link. Also, Get Many Details About Victim's Device. And So On...

An Automated Tool to Hack Victim's Camera, Microphone, Location, Clipboard. Has 2 Extra Features. Version 1.1 Update Fixed Some Major Bugs Data Saving

ToxicNoob 36 Jan 07, 2023
3DMV jointly combines RGB color and geometric information to perform 3D semantic segmentation of RGB-D scans.

3DMV 3DMV jointly combines RGB color and geometric information to perform 3D semantic segmentation of RGB-D scans. This work is based on our ECCV'18 p

Владислав Молодцов 0 Feb 06, 2022
2021 National Underwater Robotics Vision Optics

2021-National-Underwater-Robotics-Vision-Optics 2021年全国水下机器人算法大赛-光学赛道-B榜精度第18名 (Kilian_Di的团队:A榜[email pro

Di Chang 9 Nov 04, 2022
Learning Saliency Propagation for Semi-supervised Instance Segmentation

Learning Saliency Propagation for Semi-supervised Instance Segmentation PyTorch Implementation This repository contains: the PyTorch implementation of

Berkeley DeepDrive 68 Oct 18, 2022
[ICCV2021] 3DVG-Transformer: Relation Modeling for Visual Grounding on Point Clouds

3DVG-Transformer This repository is for the ICCV 2021 paper "3DVG-Transformer: Relation Modeling for Visual Grounding on Point Clouds" Our method "3DV

22 Dec 11, 2022
PyTorch implementation of PP-LCNet: A Lightweight CPU Convolutional Neural Network

PyTorch implementation of PP-LCNet Reproduction of PP-LCNet architecture as described in PP-LCNet: A Lightweight CPU Convolutional Neural Network by C

Quan Nguyen (Fly) 47 Nov 02, 2022
AttentionGAN for Unpaired Image-to-Image Translation & Multi-Domain Image-to-Image Translation

AttentionGAN-v2 for Unpaired Image-to-Image Translation AttentionGAN-v2 Framework The proposed generator learns both foreground and background attenti

Hao Tang 530 Dec 27, 2022
Pretrained models for Jax/Haiku; MobileNet, ResNet, VGG, Xception.

Pre-trained image classification models for Jax/Haiku Jax/Haiku Applications are deep learning models that are made available alongside pre-trained we

Alper Baris CELIK 14 Dec 20, 2022
Large-Scale Pre-training for Person Re-identification with Noisy Labels (LUPerson-NL)

LUPerson-NL Large-Scale Pre-training for Person Re-identification with Noisy Labels (LUPerson-NL) The repository is for our CVPR2022 paper Large-Scale

43 Dec 26, 2022
The dataset and source code for our paper: "Did You Ask a Good Question? A Cross-Domain Question IntentionClassification Benchmark for Text-to-SQL"

TriageSQL The dataset and source code for our paper: "Did You Ask a Good Question? A Cross-Domain Question Intention Classification Benchmark for Text

Yusen Zhang 22 Nov 09, 2022
This is an implementation of PIFuhd based on Pytorch

Open-PIFuhd This is a unofficial implementation of PIFuhd PIFuHD: Multi-Level Pixel-Aligned Implicit Function forHigh-Resolution 3D Human Digitization

Lingteng Qiu 235 Dec 19, 2022
Official Code for ICML 2021 paper "Revisiting Point Cloud Shape Classification with a Simple and Effective Baseline"

Revisiting Point Cloud Shape Classification with a Simple and Effective Baseline Ankit Goyal, Hei Law, Bowei Liu, Alejandro Newell, Jia Deng Internati

Princeton Vision & Learning Lab 115 Jan 04, 2023
Easily benchmark PyTorch model FLOPs, latency, throughput, max allocated memory and energy consumption

⏱ pytorch-benchmark Easily benchmark model inference FLOPs, latency, throughput, max allocated memory and energy consumption Install pip install pytor

Lukas Hedegaard 21 Dec 22, 2022
Open source implementation of AceNAS: Learning to Rank Ace Neural Architectures with Weak Supervision of Weight Sharing

AceNAS This repo is the experiment code of AceNAS, and is not considered as an official release. We are working on integrating AceNAS as a built-in st

Yuge Zhang 6 Sep 07, 2022