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
Official code repository for Continual Learning In Environments With Polynomial Mixing Times

Official code for Continual Learning In Environments With Polynomial Mixing Times Continual Learning in Environments with Polynomial Mixing Times This

Sharath Raparthy 1 Dec 19, 2021
Winners of DrivenData's Overhead Geopose Challenge

Winners of DrivenData's Overhead Geopose Challenge

DrivenData 22 Aug 04, 2022
A real-time speech emotion recognition application using Scikit-learn and gradio

Speech-Emotion-Recognition-App A real-time speech emotion recognition application using Scikit-learn and gradio. Requirements librosa==0.6.3 numpy sou

Son Tran 6 Oct 04, 2022
Voxel-based Network for Shape Completion by Leveraging Edge Generation (ICCV 2021, oral)

Voxel-based Network for Shape Completion by Leveraging Edge Generation This is the PyTorch implementation for the paper "Voxel-based Network for Shape

10 Dec 04, 2022
Language-Agnostic Website Embedding and Classification

Homepage2Vec Language-Agnostic Website Embedding and Classification based on Curlie labels https://arxiv.org/pdf/2201.03677.pdf Homepage2Vec is a pre-

25 Dec 27, 2022
TensorFlow implementation of Elastic Weight Consolidation

Elastic weight consolidation Introduction A TensorFlow implementation of elastic weight consolidation as presented in Overcoming catastrophic forgetti

James Stokes 67 Oct 11, 2022
LBK 20 Dec 02, 2022
Repository of the paper Compressing Sensor Data for Remote Assistance of Autonomous Vehicles using Deep Generative Models at ML4AD @ NeurIPS 2021.

Compressing Sensor Data for Remote Assistance of Autonomous Vehicles using Deep Generative Models Code and supplementary materials Repository of the p

Daniel Bogdoll 4 Jul 13, 2022
Implement some metaheuristics and cost functions

Metaheuristics This repot implement some metaheuristics and cost functions. Metaheuristics JAYA Implement Jaya optimizer without constraints. Cost fun

Adri1G 1 Mar 23, 2022
Machine learning library for fast and efficient Gaussian mixture models

This repository contains code which implements the Stochastic Gaussian Mixture Model (S-GMM) for event-based datasets Dependencies CMake Premake4 Blaz

Omar Oubari 1 Dec 19, 2022
Background Matting: The World is Your Green Screen

Background Matting: The World is Your Green Screen By Soumyadip Sengupta, Vivek Jayaram, Brian Curless, Steve Seitz, and Ira Kemelmacher-Shlizerman Th

Soumyadip Sengupta 4.6k Jan 04, 2023
This code is part of the reproducibility package for the SANER 2022 paper "Generating Clarifying Questions for Query Refinement in Source Code Search".

Clarifying Questions for Query Refinement in Source Code Search This code is part of the reproducibility package for the SANER 2022 paper "Generating

Zachary Eberhart 0 Dec 04, 2021
FluidNet re-written with ATen tensor lib

fluidnet_cxx: Accelerating Fluid Simulation with Convolutional Neural Networks. A PyTorch/ATen Implementation. This repository is based on the paper,

JoliBrain 50 Jun 07, 2022
Agent-based model simulator for air quality and pandemic risk assessment in architectural spaces

Agent-based model simulation for air quality and pandemic risk assessment in architectural spaces. User Guide archABM is a fast and open source agent-

Vicomtech 10 Dec 05, 2022
PyTorch implementation of "Supervised Contrastive Learning" (and SimCLR incidentally)

PyTorch implementation of "Supervised Contrastive Learning" (and SimCLR incidentally)

Yonglong Tian 2.2k Jan 08, 2023
A framework for the elicitation, specification, formalization and understanding of requirements.

A framework for the elicitation, specification, formalization and understanding of requirements.

NASA - Software V&V 161 Jan 03, 2023
DGN pymarl - Implementation of DGN on Pymarl, which could be trained by VDN or QMIX

This is the implementation of DGN on Pymarl, which could be trained by VDN or QM

4 Nov 23, 2022
BanditPAM: Almost Linear-Time k-Medoids Clustering

BanditPAM: Almost Linear-Time k-Medoids Clustering This repo contains a high-performance implementation of BanditPAM from BanditPAM: Almost Linear-Tim

254 Dec 12, 2022
Jetson Nano-based smart camera system that measures crowd face mask usage in real-time.

MaskCam MaskCam is a prototype reference design for a Jetson Nano-based smart camera system that measures crowd face mask usage in real-time, with all

BDTI 212 Dec 29, 2022
Matlab Python Heuristic Battery Opt - SMOP conversion and manual conversion

SMOP is Small Matlab and Octave to Python compiler. SMOP translates matlab to py

Tom Xu 1 Jan 12, 2022