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
1
380
Circuit Breakers em Ruby
Lucas Mazza
November 19, 2016
Tweet
Share
More Decks by Lucas Mazza
See All by Lucas Mazza
OpenAPI e Elixir (e qualquer outra linguagem)
lucas
0
67
Ecto sem SQL
lucas
0
360
Feature Toggles! - Elixir
lucas
3
500
Feature Toggles! - Ruby
lucas
2
340
Testes automatizados e a prática antes da teoria
lucas
0
400
The Zen and Art of Refactoring
lucas
4
800
Minitest: voltando ao básico sobre testes
lucas
1
380
10 coisas que eu gostaria de ter aprendido mais cedo
lucas
67
5.4k
gems, executáveis e configurações
lucas
5
380
Other Decks in Programming
See All in Programming
API Platform 4.2: Redefining API Development
soyuka
0
210
JSONataを使ってみよう Step Functionsが楽しくなる実践テクニック #devio2025
dafujii
1
640
意外と簡単!?フロントエンドでパスキー認証を実現する WebAuthn
teamlab
PRO
2
780
OSS開発者という働き方
andpad
5
1.7k
概念モデル→論理モデルで気をつけていること
sunnyone
3
300
デザイナーが Androidエンジニアに 挑戦してみた
874wokiite
0
550
CloudflareのChat Agent Starter Kitで簡単!AIチャットボット構築
syumai
2
510
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
420
How Android Uses Data Structures Behind The Scenes
l2hyunwoo
0
480
そのAPI、誰のため? Androidライブラリ設計における利用者目線の実践テクニック
mkeeda
2
2.8k
AIを活用し、今後に備えるための技術知識 / Basic Knowledge to Utilize AI
kishida
22
5.9k
@Environment(\.keyPath)那么好我不允许你们不知道! / atEnvironment keyPath is so good and you should know it!
lovee
0
130
Featured
See All Featured
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
188
55k
Code Review Best Practice
trishagee
71
19k
It's Worth the Effort
3n
187
28k
YesSQL, Process and Tooling at Scale
rocio
173
14k
Bash Introduction
62gerente
615
210k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Rebuilding a faster, lazier Slack
samanthasiow
83
9.2k
Imperfection Machines: The Place of Print at Facebook
scottboms
268
13k
Site-Speed That Sticks
csswizardry
10
820
A Modern Web Designer's Workflow
chriscoyier
696
190k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
8
530
Automating Front-end Workflow
addyosmani
1370
200k
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