https://github.com/yammer/circuitbox

Skip to content Toggle navigation
 
Sign up

  * Product
      +  
        Actions
        Automate any workflow
      +  
        Packages
        Host and manage packages
      +  
        Security
        Find and fix vulnerabilities
      +  
        Codespaces
        Instant dev environments
      +  
        Copilot
        Write better code with AI
      +  
        Code review
        Manage code changes
      +  
        Issues
        Plan and track work
      +  
        Discussions
        Collaborate outside of code
    Explore
      + All features
      + Documentation
      + GitHub Skills
      + Blog
  * Solutions
    For
      + Enterprise
      + Teams
      + Startups
      + Education
    By Solution
      + CI/CD & Automation
      + DevOps
      + DevSecOps
    Case Studies
      + Customer Stories
      + Resources
  * Open Source
      +  
        GitHub Sponsors
        Fund open source developers
      +  
        The ReadME Project
        GitHub community articles
    Repositories
      + Topics
      + Trending
      + Collections
  * Pricing

Search or jump to...

Search code, repositories, users, issues, pull requests...

Search
[                    ]
Clear

Search syntax tips

Provide feedback

We read every piece of feedback, and take your input very seriously.

[                    ] [ ] Include my email address so I can be
contacted
Cancel Submit feedback

Saved searches

Use saved searches to filter your results more quickly

Name [                    ] 
Query [                    ]

To see all available qualifiers, see our documentation.

Cancel Create saved search
Sign in
Sign up
You signed in with another tab or window. Reload to refresh your
session. You signed out in another tab or window. Reload to refresh
your session. You switched accounts on another tab or window. Reload
to refresh your session.
{{ message }}
yammer / circuitbox Public

  * Notifications
  * Fork 58
  * Star 512

Circuit breaker built with large Ruby apps in mind.

License

View license
512 stars 58 forks
Star
Notifications

  * Code
  * Issues 2
  * Pull requests 0
  * Actions
  * Projects 0
  * Security
  * Insights

More

  * Code
  * Issues
  * Pull requests
  * Actions
  * Projects
  * Security
  * Insights

yammer/circuitbox

This commit does not belong to any branch on this repository, and may
belong to a fork outside of the repository.
main
Switch branches/tags
[                    ]
Branches Tags
Could not load branches
Nothing to show
{{ refName }} default View all branches
Could not load tags
Nothing to show
{{ refName }} default
View all tags

Name already in use

A tag already exists with the provided branch name. Many Git commands
accept both tag and branch names, so creating this branch may cause
unexpected behavior. Are you sure you want to create this branch?
Cancel Create
1 branch 24 tags
Code

  * Local
  * Codespaces

  *  
    Clone
    HTTPS GitHub CLI
    [https://github.com/y]

    Use Git or checkout with SVN using the web URL.

    [gh repo clone yammer]

    Work fast with our official CLI. Learn more about the CLI.

  * Open with GitHub Desktop
  * Download ZIP

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

@matthewshafer
matthewshafer Merge pull request #197 from matthewshafer/
release-2-0-0
...
a85df31 May 4, 2023
Merge pull request #197 from matthewshafer/release-2-0-0

Release 2.0.0

a85df31

Git stats

  * 343 commits

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
.github/workflows
 
 
benchmark
 
 
ci
 
 
docs
 
 
lib
 
 
test
 
 
.gitignore
 
 
.rubocop.yml
 
 
.ruby-version
 
 
CHANGELOG.md
 
 
Gemfile
 
 
LICENSE
 
 
README.md
 
 
Rakefile
 
 
circuitbox.gemspec
 
 
test.sh
 
 
View code
[                    ]
Circuitbox Usage Global Configuration Per-Circuit Configuration
Circuit Store Notifications Faraday Installation Contributing

README.md

 Circuitbox

Tests Gem Version

Circuitbox is a Ruby circuit breaker gem. It protects your
application from failures of its service dependencies. It wraps calls
to external services and monitors for failures in one minute
intervals. Using a circuit's defaults once more than 5 requests have
been made with a 50% failure rate, Circuitbox stops sending requests
to that failing service for 90 seconds. This helps your application
gracefully degrade.

Resources about the circuit breaker pattern:

  * http://martinfowler.com/bliki/CircuitBreaker.html

Upgrading to 2.x? See 2.0 upgrade

 Usage

Circuitbox.circuit(:your_service, exceptions: [Net::ReadTimeout]) do
  Net::HTTP.get URI('http://example.com/api/messages')
end

Circuitbox will return nil for failed requests and open circuits. If
your HTTP client has its own conditions for failure, you can pass an
exceptions option.

class ExampleServiceClient
  def circuit
    Circuitbox.circuit(:yammer, exceptions: [Zephyr::FailedRequest])
  end

  def http_get
    circuit.run(exception: false) do
      Zephyr.new("http://example.com").get(200, 1000, "/api/messages")
    end
  end
end

Using the run method will throw an exception when the circuit is open
or the underlying service fails.

  def http_get
    circuit.run do
      Zephyr.new("http://example.com").get(200, 1000, "/api/messages")
    end
  end

 Global Configuration

Circuitbox defaults can be configured through Circuitbox.configure.
There are two defaults that can be configured:

  * default_circuit_store - Defaults to a Circuitbox::MemoryStore.
    This can be changed to a compatible Moneta store.
  * default_notifier - Defaults to
    Circuitbox::Notifier::ActiveSupport if
    ActiveSupport::Notifications is defined, otherwise defaults to
    Circuitbox::Notifier::Null

After configuring circuitbox through Circuitbox.configure, the
internal circuit cache of Circuitbox.circuit is cleared.

Any circuit created manually through Circuitbox::CircuitBreaker
before updating the configuration will need to be recreated to pick
up the new defaults.

The following is an example Circuitbox configuration:

  Circuitbox.configure do |config|
    config.default_circuit_store = Circuitbox::MemoryStore.new
    config.default_notifier = Circuitbox::Notifier::Null.new
  end

 Per-Circuit Configuration

class ExampleServiceClient
  def circuit
    Circuitbox.circuit(:your_service, {
      # exceptions circuitbox tracks for counting failures (required)
      exceptions:       [YourCustomException],

      # seconds the circuit stays open once it has passed the error threshold
      sleep_window:     300,

      # length of interval (in seconds) over which it calculates the error rate
      time_window:      60,

      # number of requests within `time_window` seconds before it calculates error rates (checked on failures)
      volume_threshold: 10,

      # the store you want to use to save the circuit state so it can be
      # tracked, this needs to be Moneta compatible, and support increment
      # this overrides what is set in the global configuration
      circuit_store: Circuitbox::MemoryStore.new,

      # exceeding this rate will open the circuit (checked on failures)
      error_threshold:  50,

      # Customized notifier
      # this overrides what is set in the global configuration
      notifier: Notifier.new
    })
  end
end

You can also pass a Proc as an option value which will evaluate each
time the circuit breaker is used. This lets you configure the circuit
breaker without having to restart the processes.

Circuitbox.circuit(:yammer, {
  sleep_window: Proc.new { Configuration.get(:sleep_window) },
  exceptions: [Net::ReadTimeout]
})

 Circuit Store

Holds all the relevant data to trip the circuit if a given number of
requests fail in a specified period of time. Circuitbox also supports
Moneta. As moneta is not a dependency of circuitbox it needs to be
loaded prior to use. There are a lot of moneta stores to choose from
but some pre-requisits need to be satisfied first:

  * Needs to support increment, this is true for most but not all
    available stores.
  * Needs to support expiry.
  * Needs to support bulk read.
  * Needs to support concurrent access if you share them. For example
    sharing a KyotoCabinet store across process fails because the
    store is single writer multiple readers, and all circuits sharing
    the store need to be able to write.

 Notifications

See Circuit Notifications

 Faraday

Circuitbox ships with a Faraday HTTP client middleware. The versions
of faraday the middleware has been tested against is >= 0.17 through
~> 2.0. The middleware does not support parallel requests through a
connections in_parallel method.

require 'faraday'
require 'circuitbox/faraday_middleware'

conn = Faraday.new(:url => "http://example.com") do |c|
  c.use Circuitbox::FaradayMiddleware
end

response = conn.get("/api")
if response.success?
  # success
else
  # failure or open circuit
end

By default the Faraday middleware returns a 503 response when the
circuit is open, but this as many other things can be configured via
middleware options

  * default_value value to return for open circuits, defaults to 503
    response wrapping the original response given by the service and
    stored as original_response property of the returned 503, this
    can be overwritten with either
      + a static value
      + a lambda which is passed the original_response and
        original_error. original_response will be populated if
        Faraday returns an error response, original_error will be
        populated if an error was thrown before Faraday returned a
        response.

c.use Circuitbox::FaradayMiddleware, default_value: lambda { |response, error| ... }

  * identifier circuit id, defaults to request url

c.use Circuitbox::FaradayMiddleware, identifier: "service_name_circuit"

  * circuit_breaker_options options to initialize the circuit with
    defaults to { exceptions:
    Circuitbox::FaradayMiddleware::DEFAULT_EXCEPTIONS }. Accepts same
    options as Circuitbox:CircuitBreaker#new

c.use Circuitbox::FaradayMiddleware, circuit_breaker_options: {}

  * open_circuit lambda determining what response is considered a
    failure, counting towards the opening of the circuit

c.use Circuitbox::FaradayMiddleware, open_circuit: lambda { |response| response.status >= 500 }

 Installation

Add this line to your application's Gemfile:

gem 'circuitbox'

And then execute:

$ bundle

Or install it yourself as:

$ gem install circuitbox

 Contributing

 1. Fork it
 2. Create your feature branch (git checkout -b my-new-feature)
 3. Commit your changes (git commit -am 'Add some feature')
 4. Push to the branch (git push origin my-new-feature)
 5. Create new Pull Request

About

Circuit breaker built with large Ruby apps in mind.

Resources

Readme

License

View license

Stars

512 stars

Watchers

30 watching

Forks

58 forks
Report repository

Releases 3

 
Release v2.0.0 Latest
May 4, 2023
+ 2 releases

Packages 0

No packages published

Used by 57

 

  * @pjjw
  * @nialov
  * @CorbanR
  * @fitzgibbon
  * @ben-kuhn
  * @yvan-sraka
  * @spectral-team
  * @peti

+ 49

Contributors 22

  * 
  * 
  * 
  * 
  * 
  * 
  * 
  * 
  * 
  * 
  * 

+ 11 contributors

Languages

  * Ruby 99.2%
  * Shell 0.8%

Footer

 (c) 2023 GitHub, Inc.

Footer navigation

  * Terms
  * Privacy
  * Security
  * Status
  * Docs
  * Contact GitHub
  * Pricing
  * API
  * Training
  * Blog
  * About

You can't perform that action at this time.