Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Circuit Breakers em Ruby
Search
Lucas Mazza
November 19, 2016
Programming
410
1
Share
Circuit Breakers em Ruby
Lucas Mazza
November 19, 2016
More Decks by Lucas Mazza
See All by Lucas Mazza
OpenAPI e Elixir (e qualquer outra linguagem)
lucas
0
110
Ecto sem SQL
lucas
0
390
Feature Toggles! - Elixir
lucas
3
590
Feature Toggles! - Ruby
lucas
2
360
Testes automatizados e a prática antes da teoria
lucas
0
420
The Zen and Art of Refactoring
lucas
4
970
Minitest: voltando ao básico sobre testes
lucas
1
410
10 coisas que eu gostaria de ter aprendido mais cedo
lucas
67
5.4k
gems, executáveis e configurações
lucas
5
410
Other Decks in Programming
See All in Programming
生成 AI 時代のスナップショットテストってやつを見せてあげますよ(α版)
ojun9
0
340
「接続」—パフォーマンスチューニングの最後の一手 〜点と点を結ぶ、その一瞬のために〜
kentaroutakeda
5
2.5k
存在論的プログラミング: 時間と存在を記述する
koriym
5
780
テレメトリーシグナルが導くパフォーマンス最適化 / Performance Optimization Driven by Telemetry Signals
seike460
PRO
2
220
最初からAWS CDKで技術検証してもいいんじゃない?
akihisaikeda
4
180
PHPで TLSのプロトコルを実装してみる
higaki_program
0
740
Reactive ❤️ Loom: A Forbidden Love Story
franz1981
2
220
Mastering Event Sourcing: Your Parents Holidayed in Yugoslavia
super_marek
0
150
「速くなった気がする」をデータで疑う
senleaf24
0
150
仕様漏れ実装漏れをなくすトレーサビリティAI基盤のご紹介
orgachem
PRO
8
4.7k
Going Multiplatform with Your Android App (Android Makers 2026)
zsmb
1
330
KagglerがMixSeekを触ってみた
morim
0
370
Featured
See All Featured
YesSQL, Process and Tooling at Scale
rocio
174
15k
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
500
SEO for Brand Visibility & Recognition
aleyda
0
4.4k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
508
140k
How Software Deployment tools have changed in the past 20 years
geshan
0
33k
Color Theory Basics | Prateek | Gurzu
gurzu
0
280
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
470
AI Search: Where Are We & What Can We Do About It?
aleyda
0
7.3k
Raft: Consensus for Rubyists
vanstee
141
7.4k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
250
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
340
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
1
2.5k
Transcript
Circuit Breakers em Ruby
@lucasmazza http://afterhours.io/
None
None
https://sp.femug.com https://github.com/femug/femug
Circuit Breakers em Ruby
None
None
None
None
❓
None
None
rescue_from StandardError do render text: 'oops' end
rescue_from StandardError do render text: 'oops' end ❓❓❓❓❓❓❓❓❓ ❓❓❓❓❓❓❓❓❓
“You wrap a protected function call in a circuit breaker
object, which monitors for failures.” http://martinfowler.com/bliki/CircuitBreaker.html
https://pragprog.com/book/mnee/release-it
None
None
None
None
None
None
None
None
Estado + transições
✓ Timeouts
✓ Timeouts ✓ Downtimes
✓ Timeouts ✓ Downtimes ✓ Picos de erros
✓ Timeouts ✓ Downtimes ✓ Picos de erros ✓ Má
configuração
★ Limite de falhas
★ Limite de falhas ★ Tempo para reset
★ Limite de falhas ★ Tempo para reset ★ Erros
a ignorar
None
❓API pública ❓Gestão do estado ❓Concorrência
jnunemaker/resilient
require 'resilient/circuit_breaker' circuit_breaker = Resilient::CircuitBreaker.get('acme-co-api') if circuit_breaker.allow_request? begin # API
Call circuit_breaker.success rescue => boom circuit_breaker.failure # do fallback end else # do fallback end
circuit_breaker = Resilient::CircuitBreaker.get('example', { # at what percentage of errors
should we open the circuit error_threshold_percentage: 50, # do not try request again for 5 seconds sleep_window_seconds: 5, # do not open circuit until at least 5 requests have happened request_volume_threshold: 5, }) # etc etc etc
✅ Boa API pública ⚠ Não é distribuído ⚠ Não
é concorrente
✅ Instrumentação & Métricas
shopify/semian
gem 'semian', require: %w(semian semian/redis) def fetch_user User.find(session[:user_id]) rescue Redis::CannotConnectError
nil end
Semian.register(:mysql_shard0, timeout: 0.5, error_threshold: 3, error_timeout: 10) Semian[:mysql_shard0].acquire do #
Perform a MySQL query here end
“Semian is not a trivial library to understand, introduces complexity
and thus should be introduced with care.” https://github.com/shopify/semian#do-i-need-semian
“It is paramount that you understand Semian before including it
in production as you may otherwise be surprised by its behaviour.” https://github.com/shopify/semian#do-i-need-semian
⚠ Monkeypatch ⚠ estado por host ✅ Concorrente
✅ Suporte a instrumentação ✅ Battle tested
orgsync/stoplight
light = Stoplight('acme-co-api') { do_api_call } .with_fallback { do_fallback }
.with_threshold(3) # => Stoplight::Light light.color #=> 'green', 'yellow' ou 'red' light.run
require 'redis' redis = Redis.new data_store = Stoplight::DataStore::Redis.new(redis) Stoplight::Light.default_data_store =
data_store slack = Slack::Notifier.new('http://www.example.com/webhook-url') notifier = Stoplight::Notifier::Slack.new(slack) Stoplight::Light.default_notifiers += [notifier] notifier = Stoplight::Notifier::Logger.new(Rails.logger) Stoplight::Light.default_notifiers += [notifier]
⚠ API não idiomática ✅ Distribuído ✅ Concorrente
✅ Implementação bem legível
netflix/hystrix
None
orgsync/stoplight
class CircuitBreaker def initialize(client, name) @client = client @name =
name end def method_missing(method, *args, &block) Stoplight(@name) { @client.public_send(method, *args, &block) }.run end end
gh_client = GitHub::Client.new('acme-co-oauth2-token') client = CircuitBreaker.new(gh_client, 'client-acme-co') # Requests feito
dentro do Circuit Breaker client.repo('plataformatec/devise') client.repo('plataformatec/simple_form') client.repo('plataformatec/faraday-http-cache')
Pattern + Gem Você!
❓Monitoramento
Métricas
StatsD Librato NewRelic AppSignal …
Notificações
Notificações
Reset manual
❓Fallback vs raise
Escrita vs leitura sync vs async
Executar uma operação em background Retry + backoff
Ler dados de uma API Fallback e/ou cache
None
Obrigado! @lucasmazza