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
Voxel Transformer for 3D object detection

Voxel Transformer This is a reproduced repo of Voxel Transformer for 3D object detection. The code is mainly based on OpenPCDet. Introduction We provi

173 Dec 25, 2022
Pytorch implementation of paper "Efficient Nearest Neighbor Language Models" (EMNLP 2021)

Pytorch implementation of paper "Efficient Nearest Neighbor Language Models" (EMNLP 2021)

Junxian He 57 Jan 01, 2023
[Machine Learning Engineer Basic Guide] 부스트캠프 AI Tech - Product Serving 자료

Boostcamp-AI-Tech-Product-Serving 부스트캠프 AI Tech - Product Serving 자료 Repository 구조 part1(MLOps 개론, Model Serving, 머신러닝 프로젝트 라이프 사이클은 별도의 코드가 없으며, part

Sung Yun Byeon 269 Dec 21, 2022
A Python package for causal inference using Synthetic Controls

Synthetic Control Methods A Python package for causal inference using synthetic controls This Python package implements a class of approaches to estim

Oscar Engelbrektson 107 Dec 28, 2022
PyTorch implementation of Spiking Neural Networks trained on surrogate gradient & BPTT using snntorch.

snn-localization repo PyTorch implementation of Spiking Neural Networks trained on surrogate gradient & BPTT using snntorch. Install Dependencies Orig

Sami BARCHID 1 Jan 06, 2022
Improving Transferability of Representations via Augmentation-Aware Self-Supervision

Improving Transferability of Representations via Augmentation-Aware Self-Supervision Accepted to NeurIPS 2021 TL;DR: Learning augmentation-aware infor

hankook 38 Sep 16, 2022
The official implementation of Autoregressive Image Generation using Residual Quantization (CVPR '22)

Autoregressive Image Generation using Residual Quantization (CVPR 2022) The official implementation of "Autoregressive Image Generation using Residual

Kakao Brain 529 Dec 30, 2022
Code for the paper "Benchmarking and Analyzing Point Cloud Classification under Corruptions"

ModelNet-C Code for the paper "Benchmarking and Analyzing Point Cloud Classification under Corruptions". For the latest updates, see: sites.google.com

Jiawei Ren 45 Dec 28, 2022
This is the code for our KILT leaderboard submission to the T-REx and zsRE tasks. It includes code for training a DPR model then continuing training with RAG.

KGI (Knowledge Graph Induction) for slot filling This is the code for our KILT leaderboard submission to the T-REx and zsRE tasks. It includes code fo

International Business Machines 72 Jan 06, 2023
DeepOBS: A Deep Learning Optimizer Benchmark Suite

DeepOBS - A Deep Learning Optimizer Benchmark Suite DeepOBS is a benchmarking suite that drastically simplifies, automates and improves the evaluation

Aaron Bahde 7 May 12, 2020
CVPR 2022 "Online Convolutional Re-parameterization"

OREPA: Online Convolutional Re-parameterization This repo is the PyTorch implementation of our paper to appear in CVPR2022 on "Online Convolutional Re

Mu Hu 121 Dec 21, 2022
Double pendulum simulator using a symplectic Euler's method and Hamiltonian mechanics

Symplectic Double Pendulum Simulator Double pendulum simulator using a symplectic Euler's method. The program calculates the momentum and position of

Scott Marino 1 Jan 12, 2022
Code for paper "Learning to Reweight Examples for Robust Deep Learning"

learning-to-reweight-examples Code for paper Learning to Reweight Examples for Robust Deep Learning. [arxiv] Environment We tested the code on tensorf

Uber Research 261 Jan 01, 2023
Continual Learning of Long Topic Sequences in Neural Information Retrieval

ContinualPassageRanking Repository for the paper "Continual Learning of Long Topic Sequences in Neural Information Retrieval". In this repository you

0 Apr 12, 2022
Gym Threat Defense

Gym Threat Defense The Threat Defense environment is an OpenAI Gym implementation of the environment defined as the toy example in Optimal Defense Pol

Hampus Ramström 5 Dec 08, 2022
Bayesian Neural Networks in PyTorch

We present the new scheme to compute Monte Carlo estimator in Bayesian VI settings with almost no memory cost in GPU, regardles of the number of sampl

Jurijs Nazarovs 7 May 03, 2022
Exploration of some patients clinical variables.

Answer_ALS_clinical_data Exploration of some patients clinical variables. All the clinical / metadata data is available here: https://data.answerals.o

1 Jan 20, 2022
Repo for my Tensorflow/Keras CV experiments. Mostly revolving around the Danbooru20xx dataset

SW-CV-ModelZoo Repo for my Tensorflow/Keras CV experiments. Mostly revolving around the Danbooru20xx dataset Framework: TF/Keras 2.7 Training SQLite D

20 Dec 27, 2022
Creating predictive checklists from data using integer programming.

Learning Optimal Predictive Checklists A Python package to learn simple predictive checklists from data subject to customizable constraints. For more

Healthy ML 5 Apr 19, 2022
KDD CUP 2020 Automatic Graph Representation Learning: 1st Place Solution

KDD CUP 2020: AutoGraph Team: aister Members: Jianqiang Huang, Xingyuan Tang, Mingjian Chen, Jin Xu, Bohang Zheng, Yi Qi, Ke Hu, Jun Lei Team Introduc

96 May 30, 2022