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
420
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
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
120
Ecto sem SQL
lucas
0
410
Feature Toggles! - Elixir
lucas
3
610
Feature Toggles! - Ruby
lucas
2
380
Testes automatizados e a prática antes da teoria
lucas
0
430
The Zen and Art of Refactoring
lucas
4
1k
Minitest: voltando ao básico sobre testes
lucas
1
430
10 coisas que eu gostaria de ter aprendido mais cedo
lucas
67
5.4k
gems, executáveis e configurações
lucas
5
420
Other Decks in Programming
See All in Programming
これからAgentCoreを触る方へトレンドはGatewayです
har1101
5
430
Observability in Practice:Grafana 與 Edge Device SRE 的那些事
blueswen
0
180
[2026年度第1回ORセミナー] 計画最適化ベンチャーと競技プログラミング人材
terryu16
0
280
才能?センス?知らん、 続けたもん勝ちだ。-- 結婚・出産・癌を越えてなお、私がプロダクトを創り続ける理由
16bitidol
1
570
PHPで使える日時の表現と、その知り方 #frontend_phpcon_do
o0h
PRO
0
270
作って学ぶ、 JSX (TSX) ランタイムの基本
syumai
7
1.7k
例外の正しい扱い方 そのエラー try-catchして大丈夫?
jinwatanabe
0
290
Honoでのサプライチェーン侵害対策 〜 3つのライブラリに学ぶ
yusukebe
7
1.5k
TAKTでAI駆動開発の品質を設計する
j5ik2o
7
1.6k
AIキャラアプリkaiwaの低遅延音声通話基盤をどう作ったか - AWS Gravitonで支える低遅延・低コストAI Agent基盤
mogamit
0
120
気圧・高度・GPSを記録&可視化するアプリ「Koudo」を作った話
hjmkth
1
330
エージェンティックRAGにAWSで入門しよう!
har1101
9
1.8k
Featured
See All Featured
Music & Morning Musume
bryan
47
7.3k
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
260
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
570
The Curse of the Amulet
leimatthew05
2
13k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.9k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.5k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
620
The innovator’s Mindset - Leading Through an Era of Exponential Change - McGill University 2025
jdejongh
PRO
1
210
Tips & Tricks on How to Get Your First Job In Tech
honzajavorek
1
550
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
490
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
4k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.4k
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