├── .travis.yml ├── LICENSE ├── README.md ├── doc.go ├── simulations_test.go ├── smartcb.go └── smartcb_test.go /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | before_install: 3 | - go get github.com/mattn/goveralls 4 | script: 5 | - $GOPATH/bin/goveralls -service=travis-ci 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Tahir Hashmi 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Self-Configuring Smart Circuit Breaker 2 | 3 | [![GoDoc](https://godoc.org/github.com/codemartial/smartcb?status.svg)](https://godoc.org/github.com/codemartial/smartcb) 4 | [![Maintainability](https://api.codeclimate.com/v1/badges/b58cc651c02e93aba9f8/maintainability)](https://codeclimate.com/github/codemartial/smartcb/maintainability) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/codemartial/smartcb)](https://goreportcard.com/report/github.com/codemartial/smartcb) 6 | [![Build Status](https://travis-ci.org/codemartial/smartcb.svg?branch=master)](https://travis-ci.org/codemartial/smartcb) 7 | [![Coverage Status](https://coveralls.io/repos/github/codemartial/smartcb/badge.svg?branch=master)](https://coveralls.io/github/codemartial/smartcb?branch=master) 8 | 9 | A circuit breaker that continuously adjusts itself according to the error rate profile of the protected task and configures the right tripping threshold as needed. 10 | 11 | Package smartcb provides a circuit breaker based on https://github.com/rubyist/circuitbreaker that automatically adjusts the tripping error threshold based on abnormal increase in error rate. All you need to tell it is the nominal QPS ("queries per second") for your task and it automatically sets the best values for adjusting the circuit breaker's responsiveness. If you want, you can adjust the circuit breaker's sensitivity as per your situation. 12 | 13 | The circuit breaker starts off with a learning phase for understanding the error profile of the wrapped command and then adjusts its tripping threshold for error rate based on what it has learned. 14 | 15 | The error threshold is calculated as an exponential weighted moving average which smoothens out jitter and can detect rapid changes in error rate, allowing for the circuit to trip fast in case of a rapid degradation of the wrapped command. 16 | 17 | ## Installation 18 | ```sh 19 | go get github.com/codemartial/smartcb 20 | ``` 21 | 22 | ## Usage 23 | ```go 24 | package main 25 | 26 | import ( 27 | "log" 28 | "time" 29 | 30 | "github.com/codemartial/smartcb" 31 | ) 32 | 33 | func main() { 34 | taskQPS := 1000 35 | 36 | st := smartcb.NewSmartTripper(taskQPS, smartcb.NewPolicies()) 37 | scb := smartcb.NewSmartCircuitBreaker(st) 38 | 39 | if scb.Call(protectedTask, 0) != nil && scb.Tripped() { 40 | log.Println("Circuit Breaker tripped at error rate", scb.ErrorRate(), "Normal error rate was ", st.LearnedRate()) 41 | } 42 | } 43 | ``` 44 | 45 | ## Testing and Simulation 46 | Run `go test` as usual to execute the unit tests. The package also includes a couple of simulations for slowly increasing error rates and fluctuating error rates that compare the state of SmartCB against Rate based circuit breaker from github.com/rubyist/circuitbreaker. To run these simulations use the following command: 47 | ```sh 48 | go test -tags sims 49 | ``` -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package smartcb provides a circuit breaker based on https://github.com/rubyist/circuitbreaker 2 | // that automatically adjusts the tripping error threshold based on abnormal increase 3 | // in error rate. All you need to tell it is the nominal QPS ("queries per second") 4 | // for your task and it automatically sets the best values for adjusting the circuit 5 | // breaker's responsiveness. If you want, you can adjust the circuit breaker's sensitivity 6 | // as per your situation. 7 | // 8 | // The circuit breaker starts off with a learning phase for understanding the error 9 | // profile of the wrapped command and then adjusts its tripping threshold for error 10 | // rate based on what it has learned. 11 | // 12 | // The error threshold is calculated as an exponential weighted moving average which 13 | // smoothens out jitter and can detect rapid changes in error rate, allowing for the 14 | // circuit to trip fast in case of a rapid degradation of the wrapped command. 15 | package smartcb 16 | -------------------------------------------------------------------------------- /simulations_test.go: -------------------------------------------------------------------------------- 1 | // +build sims 2 | 3 | package smartcb_test 4 | 5 | import ( 6 | "fmt" 7 | "math/rand" 8 | "sync" 9 | "sync/atomic" 10 | "testing" 11 | "time" 12 | 13 | "github.com/codemartial/smartcb" 14 | "github.com/eapache/go-resiliency/breaker" 15 | "github.com/rubyist/circuitbreaker" 16 | ) 17 | 18 | func SlowRampGenerator(maxRate float64, iters int) func() (error, float64) { 19 | var i int 20 | var rate float64 21 | return func() (error, float64) { 22 | i, rate = i+1, rate+maxRate/float64(iters) 23 | if rand.Float64() < rate { 24 | return fmt.Errorf(""), rate 25 | } 26 | return nil, rate 27 | } 28 | } 29 | 30 | func status(tripped bool) string { 31 | if tripped { 32 | return "O" 33 | } 34 | return "C" 35 | } 36 | 37 | func TestSlowRamp(t *testing.T) { 38 | fmt.Println("Slow Ramp Comparison") 39 | ticker := time.Tick(time.Microsecond * 10) 40 | st := smartcb.NewSmartTripper(100000, smartcb.NewPolicies()) 41 | scb := smartcb.NewSmartCircuitBreaker(st) 42 | rcb := circuit.NewBreakerWithOptions(&circuit.Options{ 43 | ShouldTrip: circuit.RateTripFunc(smartcb.NewPolicies().MaxFail, 100), 44 | WindowTime: time.Millisecond * 10, 45 | }) 46 | errgen := SlowRampGenerator(smartcb.NewPolicies().MaxFail*1.2, 1000000) 47 | var se, re, flipped bool 48 | for i := 0; i < 1000000; i++ { 49 | <-ticker 50 | e, rate := errgen() 51 | scb.Call(func() error { return e }, 0) 52 | rcb.Call(func() error { return e }, 0) 53 | if scb.Tripped() != se { 54 | se = !se 55 | flipped = true 56 | } 57 | if rcb.Tripped() != re { 58 | re = !re 59 | flipped = true 60 | } 61 | if flipped || i+1 == 1000000 || i == 10000 { 62 | fmt.Printf("%6d, %5.2f%%, %5.2f%%, SCB:%s, RCB:%s\n", i, (rate)*100.0, st.LearnedRate()*100.0, status(se), status(re)) 63 | flipped = false 64 | } 65 | } 66 | } 67 | func TestAverageJitter(t *testing.T) { 68 | fmt.Println("Jitter Comparison") 69 | ticker := time.Tick(time.Microsecond * 10) 70 | st := smartcb.NewSmartTripper(100000, smartcb.NewPolicies()) 71 | scb := smartcb.NewSmartCircuitBreaker(st) 72 | rcb := circuit.NewBreakerWithOptions(&circuit.Options{ 73 | ShouldTrip: circuit.RateTripFunc(smartcb.NewPolicies().MaxFail*0.5, 100), 74 | WindowTime: time.Millisecond * 10, 75 | }) 76 | errgen := func(rate float64) error { 77 | if rand.Float64() < rate { 78 | return fmt.Errorf("") 79 | } 80 | return nil 81 | } 82 | jitter := 0.0 83 | rate := smartcb.NewPolicies().MaxFail / 10.0 84 | var se, re, flipped bool 85 | for i := 0; i < 1000000; i++ { 86 | <-ticker 87 | e := errgen(rate + jitter) 88 | scb.Call(func() error { return e }, 0) 89 | rcb.Call(func() error { return e }, 0) 90 | if scb.Tripped() != se { 91 | se = !se 92 | flipped = true 93 | } 94 | if rcb.Tripped() != re { 95 | re = !re 96 | flipped = true 97 | } 98 | if flipped || i+1 == 1000000 || i == 10000 { 99 | fmt.Printf("%6d, %5.2f%%, %5.2f%%, SCB:%s, RCB:%s\n", i, (rate+jitter)*100.0, st.LearnedRate()*100.0, status(se), status(re)) 100 | flipped = false 101 | } 102 | if i > 100000 && i%1000 == 0 { 103 | jitter = rand.Float64() * rate * 10.0 * float64(500001-i) / 400000.0 104 | if jitter < 0.0 { 105 | jitter = 0.0 106 | } 107 | } 108 | } 109 | } 110 | func TestThrottle(t *testing.T) { 111 | testRealWorld(t, false) 112 | } 113 | 114 | func TestTotalFailure(t *testing.T) { 115 | testRealWorld(t, true) 116 | } 117 | 118 | func flaky(iter int, ratelimiter chan struct{}) error { 119 | time.Sleep(time.Millisecond*100 + time.Millisecond*time.Duration(rand.Float64())*100) 120 | if iter < 50000 || iter > 70000 { 121 | return nil 122 | } 123 | select { 124 | case <-ratelimiter: 125 | return nil 126 | default: 127 | time.Sleep(time.Millisecond*1000 + time.Millisecond*time.Duration(rand.Float64())*1000) 128 | return fmt.Errorf("Rate Limit Exceeded") 129 | } 130 | } 131 | 132 | func testRealWorld(t *testing.T, total bool) { 133 | fmt.Println("Throttle Sim") 134 | ticker := time.Tick(time.Microsecond * 2500) 135 | st := smartcb.NewSmartTripper(100, smartcb.NewPolicies()) 136 | scb := smartcb.NewSmartCircuitBreaker(st) 137 | rcb := circuit.NewThresholdBreaker(20) 138 | gcb := breaker.New(10, 2, 2*time.Second) 139 | 140 | ratelimiter := make(chan struct{}, 3) 141 | errgen := func(i int) error { return flaky(i, ratelimiter) } 142 | 143 | go func() { 144 | if total { 145 | return 146 | } 147 | ticks := time.Tick(time.Microsecond * 6667) 148 | for range ticks { 149 | for i := 0; i < 3; i++ { 150 | select { 151 | case ratelimiter <- struct{}{}: 152 | default: 153 | } 154 | } 155 | } 156 | }() 157 | 158 | var wg sync.WaitGroup 159 | var attempts_scb, attempts_rcb, attempts_gcb int64 160 | for i := 0; i < 100000; i++ { 161 | <-ticker 162 | wg.Add(3) 163 | go func(i int) { 164 | defer wg.Done() 165 | if scb.Ready() { 166 | atomic.AddInt64(&attempts_scb, 1) 167 | if errgen(i) == nil { 168 | scb.Success() 169 | } else { 170 | scb.Fail() 171 | } 172 | } 173 | }(i) 174 | go func(i int) { 175 | defer wg.Done() 176 | if rcb.Ready() { 177 | atomic.AddInt64(&attempts_rcb, 1) 178 | if errgen(i) == nil { 179 | rcb.Success() 180 | } else { 181 | rcb.Fail() 182 | } 183 | } 184 | }(i) 185 | go func(i int) { 186 | defer wg.Done() 187 | 188 | if cberr := gcb.Run(func() error { return errgen(i) }); cberr != breaker.ErrBreakerOpen { 189 | atomic.AddInt64(&attempts_gcb, 1) 190 | } 191 | }(i) 192 | if i%5000 == 0 { 193 | fmt.Println(i, atomic.LoadInt64(&attempts_scb), atomic.LoadInt64(&attempts_rcb), atomic.LoadInt64(&attempts_gcb)) 194 | } 195 | } 196 | wg.Wait() 197 | fmt.Println(99999, atomic.LoadInt64(&attempts_scb), atomic.LoadInt64(&attempts_rcb), atomic.LoadInt64(&attempts_gcb)) 198 | fmt.Println("Done") 199 | } 200 | -------------------------------------------------------------------------------- /smartcb.go: -------------------------------------------------------------------------------- 1 | package smartcb 2 | 3 | import ( 4 | "math" 5 | "sync" 6 | "time" 7 | 8 | "github.com/cenk/backoff" 9 | "github.com/rubyist/circuitbreaker" 10 | ) 11 | 12 | // Policies for configuring the circuit breaker's decision making. 13 | // 14 | // MaxFail is the only parameter that might need adjustment. 15 | // Do not tweak the other parameters unless you are a statistician. 16 | // If you must, experiment with changing one parameter at a time. 17 | // All parameters are required to be > 0 18 | // 19 | type Policies struct { 20 | // Absolute highest failure rate above which the breaker must open 21 | // Default is 0.05 (5%). 22 | MaxFail float64 23 | 24 | // Number of "decision windows" used for learning 25 | LearningWindowX float64 26 | // Number of "decision windows" after which learning is restarted. 27 | // 28 | // This setting must be greater than LearningWindowX otherwise the breaker 29 | // would be in a perpetual learning state 30 | ReLearningWindowX float64 31 | // Smoothing factor for error rate learning. Higher numbers reduce jitter 32 | // but cause more lag 33 | EWMADecayFactor float64 34 | // Number of trials in a decision window. 35 | SamplesPerWindow int64 36 | } 37 | 38 | var defaults = Policies{ 39 | MaxFail: 0.05, 40 | LearningWindowX: 10.0, 41 | ReLearningWindowX: 100.0, 42 | EWMADecayFactor: 10.0, 43 | SamplesPerWindow: 1000, 44 | } 45 | 46 | // State of Circuit Breaker's Learning Module 47 | type State int 48 | 49 | const ( 50 | // Learned state indicates Circuit Breaker has learned 51 | Learned State = iota 52 | 53 | // Learning state indicates Circuit Breaker is learning 54 | Learning 55 | ) 56 | 57 | const minFail = 0.001 58 | 59 | func (s State) String() string { 60 | switch s { 61 | case Learning: 62 | return "Learning" 63 | case Learned: 64 | fallthrough 65 | default: 66 | return "Learned" 67 | } 68 | } 69 | 70 | // SmartTripper controls behaviour of the tripping function used 71 | // by the circuit breaker 72 | // 73 | // All circuit breakers obtained out of a SmartTripper instance 74 | // share their learning state, but the circuit breaker state 75 | // (error rates, event counts, etc.) is not shared 76 | // 77 | type SmartTripper struct { 78 | decisionWindow time.Duration 79 | policies Policies 80 | state State 81 | rate float64 82 | initTime time.Time 83 | mu sync.Mutex 84 | } 85 | 86 | // NewPolicies returns Policies initialised to default values 87 | // 88 | func NewPolicies() Policies { 89 | return defaults 90 | } 91 | 92 | // NewSmartTripper creates a SmartTripper based on the nominal QPS for your task 93 | // 94 | // "Nominal QPS" is the basis on which the SmartTripper configures its 95 | // responsiveness settings. A suitable value for this parameter would be 96 | // your median QPS. If your QPS varies a lot during operation, choosing this 97 | // value closer to max QPS will make the circuit breaker reluctant to trip 98 | // during low traffic periods and choosing a value closer to min QPS will make it 99 | // slow to respond during high traffic periods. 100 | // 101 | // NOTE: Provide QPS value applicable for one instance of the circuit breaker, 102 | // not the overall QPS across multiple instances. 103 | // 104 | func NewSmartTripper(QPS int, p Policies) *SmartTripper { 105 | if QPS <= 0 { 106 | panic("smartcb.NewSmartTripper: QPS should be >= 1") 107 | } 108 | decisionWindow := time.Millisecond * time.Duration(float64(p.SamplesPerWindow)*1000.0/float64(QPS)) 109 | 110 | return &SmartTripper{decisionWindow: decisionWindow, policies: p, rate: minFail} 111 | } 112 | 113 | // State returns the Learning/Learned status of the Smart Tripper 114 | // 115 | // State change only happens when an error is triggered 116 | // Therefore timing alone can not be relied upon to detect state changes 117 | func (t *SmartTripper) State() State { 118 | t.mu.Lock() 119 | defer t.mu.Unlock() 120 | 121 | return t.state 122 | } 123 | 124 | // LearnedRate returns the tripping error rate learned by the SmartTripper 125 | // 126 | func (t *SmartTripper) LearnedRate() float64 { 127 | t.mu.Lock() 128 | defer t.mu.Unlock() 129 | 130 | return t.rate 131 | } 132 | 133 | func (t *SmartTripper) initLearning(cb *circuit.Breaker) { 134 | t.initTime = time.Now() 135 | t.state = Learning 136 | } 137 | 138 | func (t *SmartTripper) decideLearning(cb *circuit.Breaker) { 139 | learningCycles := t.policies.LearningWindowX 140 | relearningCycles := t.policies.ReLearningWindowX 141 | tElapsed := time.Since(t.initTime) 142 | 143 | // Initiate Learning Phase 144 | if t.initTime == (time.Time{}) || tElapsed > t.decisionWindow*time.Duration(relearningCycles) { 145 | t.initLearning(cb) 146 | tElapsed = time.Since(t.initTime) 147 | } 148 | 149 | cycles := float64(tElapsed) / float64(t.decisionWindow) 150 | 151 | // Terminate Learning Phase 152 | if t.state == Learning && cycles > learningCycles { 153 | t.state = Learned 154 | } 155 | } 156 | 157 | func (t *SmartTripper) recordError(cbr, samples float64) bool { 158 | if t.state != Learning { 159 | return false 160 | } 161 | 162 | maxFail := t.policies.MaxFail 163 | weightage := samples / float64(t.policies.SamplesPerWindow) 164 | t.rate += (cbr - t.rate) * weightage / (t.policies.EWMADecayFactor + weightage) 165 | 166 | // Enforce learned error rate limits 167 | if t.rate < minFail { 168 | t.rate = minFail 169 | } 170 | if t.rate > maxFail { 171 | t.rate = maxFail 172 | } 173 | return false 174 | } 175 | 176 | // Use Adjusted Wald Method to estimate whether we are confident enough to trip based on the no. of samples 177 | func (t *SmartTripper) shouldPerhapsTrip(target, actual float64, sampleSize int64) bool { 178 | ss := float64(sampleSize) 179 | ssig := float64(t.policies.SamplesPerWindow) 180 | if ss > ssig { 181 | return actual > target 182 | } 183 | pf := (ssig - ss) / (ssig - 1) 184 | fearFactor := math.Sqrt(pf*actual*(1-actual)/ss) * 2.58 // 2.58 = z-Critical at 99% confidence 185 | 186 | return actual-fearFactor > target 187 | } 188 | 189 | func (t *SmartTripper) tripper(cb *circuit.Breaker) bool { 190 | maxFail := t.policies.MaxFail 191 | 192 | t.mu.Lock() 193 | defer t.mu.Unlock() 194 | 195 | t.decideLearning(cb) 196 | 197 | samples := cb.Failures() + cb.Successes() 198 | errorRate := cb.ErrorRate() 199 | if samples < t.policies.SamplesPerWindow/10 { // Not enough data to decide 200 | return false 201 | } 202 | 203 | tripRate := math.Sqrt(maxFail/t.rate) * t.rate 204 | // Either trip or learn the error rate 205 | return t.shouldPerhapsTrip(tripRate, errorRate, samples) || t.recordError(errorRate, float64(samples)) 206 | } 207 | 208 | // NewSmartCircuitBreaker creates a new circuit.Breaker based on the SmartTripper 209 | // 210 | // It returns a circuit.Breaker from github.com/rubyist/circuitbreaker 211 | // Please see its documentation to understand how to use the breaker 212 | func NewSmartCircuitBreaker(t *SmartTripper) *circuit.Breaker { 213 | bo := backoff.NewExponentialBackOff() 214 | bo.InitialInterval = t.decisionWindow / 10 215 | options := &circuit.Options{ 216 | WindowTime: t.decisionWindow, 217 | BackOff: bo, 218 | } 219 | options.ShouldTrip = t.tripper 220 | return circuit.NewBreakerWithOptions(options) 221 | } 222 | -------------------------------------------------------------------------------- /smartcb_test.go: -------------------------------------------------------------------------------- 1 | package smartcb_test 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "math/rand" 7 | "sync" 8 | "testing" 9 | "time" 10 | 11 | "github.com/codemartial/smartcb" 12 | "github.com/rubyist/circuitbreaker" 13 | ) 14 | 15 | const minFail = 0.001 // Must match smartcb.minFail (which is unexported) 16 | 17 | func Example() { 18 | // Initialise policies and set max. tolerable failure rate 19 | // to 15% (= 0.15) 20 | policies := smartcb.NewPolicies() 21 | policies.MaxFail = 0.15 22 | 23 | // Create a SmartTripper Generator for a 10k QPS task 24 | var st = smartcb.NewSmartTripper(100000, policies) 25 | // Create a Circuit Breaker from the SmartTripper Generator 26 | var scb = smartcb.NewSmartCircuitBreaker(st) 27 | 28 | // The task to be wrapped with the circuit breaker 29 | protectedTask := func(errRate float64) (err error) { 30 | if rand.Float64() < errRate { 31 | return errors.New("forced error") 32 | } 33 | return nil 34 | } 35 | 36 | breakerEvents := scb.Subscribe() 37 | 38 | // Let's run the example for 200 ms 39 | stop := time.After(time.Millisecond * 200) 40 | loop := true 41 | for loop { 42 | select { 43 | case <-stop: // Stop execution now 44 | loop = false 45 | case e := <-breakerEvents: // Something changed with the circuit breaker 46 | if e == circuit.BreakerTripped { 47 | log.Println("Circuit Breaker tripped.", scb.ErrorRate(), st.State(), st.LearnedRate()) 48 | return 49 | } 50 | default: // Execute the task using circuit.Breaker.Call() method 51 | _ = scb.Call(func() error { return protectedTask(0.02) }, time.Second) 52 | } 53 | } 54 | } 55 | 56 | func protectedTask(errRate float64) (err error) { 57 | if rand.Float64() < errRate { 58 | return errors.New("forced error") 59 | } 60 | return nil 61 | } 62 | 63 | func TestSmartCB(t *testing.T) { 64 | st := smartcb.NewSmartTripper(10000, smartcb.NewPolicies()) 65 | scb := smartcb.NewSmartCircuitBreaker(st) 66 | 67 | t.Run("Learning", func(t *testing.T) { 68 | scb.Reset() 69 | testStop := time.After(time.Millisecond * 1100) 70 | bEvents := scb.Subscribe() 71 | loop := true 72 | for loop { 73 | select { 74 | case <-testStop: 75 | loop = false 76 | case e := <-bEvents: 77 | if e == circuit.BreakerTripped { 78 | t.Error("Circuit Breaker tripped in Learning Phase.", scb.ErrorRate(), st.State(), st.LearnedRate()) 79 | return 80 | } 81 | default: 82 | _ = scb.Call(func() error { return protectedTask(0.02) }, time.Second) 83 | } 84 | } 85 | }) 86 | 87 | t.Run("OperationFail", func(t *testing.T) { 88 | scb.ResetCounters() 89 | if st.State() != smartcb.Learned { 90 | t.Error("Circuit Breaker is still learning") 91 | } 92 | for i := 0; i < 1000; i++ { 93 | err := scb.Call(func() error { return protectedTask(0.2) }, time.Second) 94 | if err != nil && scb.Tripped() { 95 | break 96 | } 97 | } 98 | if !scb.Tripped() { 99 | t.Error("Circuit Breaker did not trip beyond learned failure rate", scb.ErrorRate(), st.LearnedRate()) 100 | } 101 | }) 102 | 103 | t.Run("OperationSuccess", func(t *testing.T) { 104 | scb.Reset() 105 | for { 106 | _ = scb.Call(func() error { return protectedTask(0) }, time.Second) 107 | if scb.Ready() && scb.Successes() > 50 { 108 | break 109 | } 110 | } 111 | for j := 0; j < 100; j++ { 112 | err := scb.Call(func() error { return protectedTask(0.018) }, time.Second) 113 | if err != nil && scb.Tripped() { 114 | t.Error(j, "Circuit breaker tripped unexpectedly", scb.ErrorRate()) 115 | return 116 | } 117 | } 118 | }) 119 | 120 | t.Run("MaxFail", func(t *testing.T) { 121 | for i := 0; i < 1000; i++ { 122 | err := scb.Call(func() error { return protectedTask(smartcb.NewPolicies().MaxFail) }, time.Second) 123 | if err != nil && scb.Tripped() { 124 | break 125 | } 126 | } 127 | if !scb.Tripped() { 128 | t.Error("Circuit Breaker did not trip at max failure rate", scb.ErrorRate(), st.LearnedRate()) 129 | } 130 | }) 131 | } 132 | 133 | func TestInvalidDuration(t *testing.T) { 134 | defer func() { 135 | if recover() == nil { 136 | t.Error("No panic despite invalid response duration") 137 | } 138 | }() 139 | 140 | _ = smartcb.NewSmartTripper(0, smartcb.NewPolicies()) 141 | } 142 | 143 | // Test that the breaker doesn't learn a high failure rate 144 | func TestLearnGuard(t *testing.T) { 145 | st := smartcb.NewSmartTripper(100000, smartcb.NewPolicies()) 146 | scb := smartcb.NewSmartCircuitBreaker(st) 147 | loop := true 148 | testStop := time.After(time.Millisecond * 110) 149 | for loop { 150 | select { 151 | case <-testStop: 152 | loop = false 153 | default: 154 | scb.Call(func() error { return protectedTask(smartcb.NewPolicies().MaxFail * 1.1) }, 0) 155 | } 156 | } 157 | if st.LearnedRate() > smartcb.NewPolicies().MaxFail { 158 | t.Error("Circuit Breaker learned a dangerous failure rate ", st.LearnedRate()) 159 | } 160 | } 161 | 162 | func TestLowLiquidity(t *testing.T) { 163 | p := smartcb.NewPolicies() 164 | scb := smartcb.NewSmartCircuitBreaker(smartcb.NewSmartTripper(10000, p)) 165 | for i := 1; i < int(p.SamplesPerWindow/10); i++ { 166 | scb.Call(func() error { return protectedTask(1.0) }, time.Second) 167 | 168 | if scb.Tripped() { 169 | t.Error("Circuit Breaker tripped unreasonably ", scb.ErrorRate(), scb.Failures()+scb.Successes()) 170 | } 171 | } 172 | } 173 | 174 | func concurrentCaller(errRate float64, scb *circuit.Breaker) { 175 | var wg sync.WaitGroup 176 | wg.Add(32) //MAGIC 177 | for i := 0; i < 32; i++ { 178 | go func() { 179 | _ = scb.Call(func() error { return protectedTask(errRate) }, time.Second) 180 | wg.Done() 181 | }() 182 | } 183 | wg.Wait() 184 | } 185 | 186 | func TestConcurrency(t *testing.T) { 187 | st := smartcb.NewSmartTripper(10000, smartcb.NewPolicies()) 188 | scb := smartcb.NewSmartCircuitBreaker(st) 189 | testStop := time.After(time.Second * 2) 190 | loop := true 191 | bEvents := scb.Subscribe() 192 | 193 | concurrentCall := func(errRate float64) { concurrentCaller(errRate, scb) } 194 | for loop { 195 | select { 196 | case <-testStop: 197 | loop = false 198 | case e := <-bEvents: 199 | if e == circuit.BreakerTripped { 200 | loop = false 201 | t.Error("Circuit Breaker tripped in Learning Phase.", scb.ErrorRate(), st.State(), st.LearnedRate()) 202 | } 203 | default: 204 | concurrentCall(0.02) 205 | } 206 | } 207 | 208 | tripped := false 209 | testStop = time.After(time.Second * 1) 210 | loop = true 211 | for loop { 212 | select { 213 | case <-testStop: 214 | loop = false 215 | case e := <-bEvents: 216 | if e == circuit.BreakerTripped { 217 | tripped = true 218 | } 219 | default: 220 | concurrentCall(0.2) 221 | } 222 | } 223 | if !tripped { 224 | t.Error("Circuit Breaker didn't trip above learned rate", scb.ErrorRate(), st.LearnedRate()) 225 | } 226 | 227 | testStop = time.After(time.Second * 2) 228 | loop = true 229 | for loop { 230 | select { 231 | case <-testStop: 232 | loop = false 233 | default: 234 | concurrentCall(0.02) 235 | } 236 | } 237 | } 238 | 239 | func TestStateLabels(t *testing.T) { 240 | tests := map[smartcb.State]string{smartcb.Learning: "Learning", smartcb.Learned: "Learned"} 241 | for k, v := range tests { 242 | t.Run(v, func(t *testing.T) { 243 | if k.String() != v { 244 | t.Error("Invalid Label for Learning State. Expected ", v, ", got ", k.String()) 245 | } 246 | }) 247 | } 248 | } 249 | 250 | func TestZeroErrorLearning(t *testing.T) { 251 | policies := smartcb.NewPolicies() 252 | st := smartcb.NewSmartTripper(100000, policies) 253 | scb := smartcb.NewSmartCircuitBreaker(st) 254 | 255 | loop := true 256 | testStop := time.After(time.Millisecond * 200) 257 | for loop { 258 | var err error 259 | select { 260 | case <-testStop: 261 | err = scb.Call(func() error { return protectedTask(100) }, time.Second) 262 | loop = false 263 | default: 264 | if err = scb.Call(func() error { return protectedTask(minFail / 2.0) }, time.Second); err != nil && scb.Tripped() { 265 | t.Error("Circuit breaker tripped in Learning Phase.", scb.ErrorRate(), st.State(), st.LearnedRate()) 266 | return 267 | } 268 | } 269 | } 270 | 271 | if st.State() != smartcb.Learned { 272 | t.Error("Circuit breaker is still learning") 273 | } 274 | if st.LearnedRate() < minFail { 275 | t.Error("Circuit breaker learned abnormally low error rate", st.LearnedRate(), "Expected rate was >=", minFail) 276 | } 277 | } 278 | 279 | func TestInitState(t *testing.T) { 280 | st := smartcb.NewSmartTripper(1000, smartcb.NewPolicies()) 281 | if st.State() == smartcb.Learning { 282 | t.Error("Circuit breaker initialised in Learning state") 283 | } 284 | } 285 | 286 | func BenchmarkCB(b *testing.B) { 287 | st := smartcb.NewSmartTripper(100000, smartcb.NewPolicies()) 288 | scb := smartcb.NewSmartCircuitBreaker(st) 289 | bEvents := scb.Subscribe() 290 | b.RunParallel(func(pb *testing.PB) { 291 | for pb.Next() { 292 | scb.Call(func() error { return protectedTask(0.0) }, 0) 293 | select { 294 | case e := <-bEvents: 295 | if e == circuit.BreakerTripped || e == circuit.BreakerFail { 296 | b.Error("Circuit breaker failed") 297 | } 298 | default: 299 | } 300 | } 301 | }) 302 | } 303 | --------------------------------------------------------------------------------