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
400
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
420
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
Lessons from Spec-Driven Development
simas
PRO
0
150
「AIで開発し、AIを届ける」をEvalでつなぐ 〜AIネイティブに始めるプロダクト開発の実践〜 / Connecting "Develop with AI, deliver AI" with Eval
rkaga
4
4.7k
AI時代の仕事技芸論 — ソフトウェア開発で「遊ぶように働く」職人的熟達のすすめ
kuranuki
1
620
Make SRE Operations Easier with Azure SRE Agent
kkamegawa
0
4.5k
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
180
肥大化するレガシーコードに立ち向かうためのインターフェース分離と依存の逆転 / JJUG CCC 2026 Spring
hirokunimaeta
0
510
開発体験を左右するライブラリの API 設計 - GraphQL スキーマ構築ライブラリから考える #tskaigi
izumin5210
2
1.6k
Javaの型とAI時代に型が大事な理由 / java types and type in AI era
kishida
2
110
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
3.2k
決定論的オーケストレーションの設計と実装 / Design and Implementation of Deterministic Orchestration
nrslib
3
1.2k
JJUG CCC 2026 Spring: JSpecify で実現する Kotlin フレンドリーな Java API 設計
ternbusty
1
150
脅威をエンジニアリングの糧にして――現場編 / Turning Threats into Engineering Fuel — Field Edition
nrslib
0
260
Featured
See All Featured
What does AI have to do with Human Rights?
axbom
PRO
1
2.2k
Context Engineering - Making Every Token Count
addyosmani
9
950
Deep Space Network (abreviated)
tonyrice
0
170
A Modern Web Designer's Workflow
chriscoyier
698
190k
Docker and Python
trallard
47
3.9k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.4k
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
580
Reality Check: Gamification 10 Years Later
codingconduct
0
2.2k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.5k
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
330
Java REST API Framework Comparison - PWX 2021
mraible
34
9.3k
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