SlideShare a Scribd company logo
1 of 26
Download to read offline
Circuit Breakers with Swift ⚡
Swift Cloud Workshop 3
Manny Guerrero
(@SwiftyGuerrero)
Agenda
• History of Circuit Breakers 🧐
• How a Circuit Breaker Works 🔍

• Advantages/Disadvantages with Swift 😕

• Implementation in Swift 🛠

• Demo 🏎

• Q & A 🚀
History of Circuit Breakers
• Early beginnings in electrical engineering
• Was popularized in software by Michael T. Nygard
How a Circuit Breaker Works
Advantages/Disadvantages with Swift
Advantages:
• Reduces CPU resources
• Can protect parts of a system from failures in other
parts
• Easy monitoring of the state
Disadvantages:
• Managing the state can be difficult if OOP isn’t
being used.
• Need to use specific Timer APIs
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
return .closed
}
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
return .closed
}
var workToPerform: ((CircuitBreaker) -> Void)?
var tripped: ((CircuitBreaker, Error?) -> Void)?
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
return .closed
}
var workToPerform: ((CircuitBreaker) -> Void)?
var tripped: ((CircuitBreaker, Error?) -> Void)?
let maxFailures: Int
let timeout: TimeInterval
let retryDelay: TimeInterval
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
return .closed
}
var workToPerform: ((CircuitBreaker) -> Void)?
var tripped: ((CircuitBreaker, Error?) -> Void)?
let maxFailures: Int
let timeout: TimeInterval
let retryDelay: TimeInterval
private var lastFailureTime: TimeInterval?
private var lastError: Error?
private var scheduler: Scheduler?
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
if let lastFailureTime = self.lastFailureTime,
failureCount > maxFailures &&
(Date().timeIntervalSince1970 - lastFailureTime) > retryDelay {
return .halfOpened
}
if failureCount == maxFailures {
return .open
}
return .closed
}
var workToPerform: ((CircuitBreaker) -> Void)?
var tripped: ((CircuitBreaker, Error?) -> Void)?
let maxFailures: Int
let timeout: TimeInterval
let retryDelay: TimeInterval
private var lastFailureTime: TimeInterval?
private var lastError: Error?
private var scheduler: Scheduler?
}
Implementation in Swift
enum BreakerState {
case open
case halfOpened
case closed
}
class CircuitBreaker {
var state: BreakerState {
if let lastFailureTime = self.lastFailureTime,
failureCount > maxFailures &&
(Date().timeIntervalSince1970 - lastFailureTime) > retryDelay {
return .halfOpened
}
if failureCount == maxFailures {
return .open
}
return .closed
}
var workToPerform: ((CircuitBreaker) -> Void)?
var tripped: ((CircuitBreaker, Error?) -> Void)?
let maxFailures: Int
let timeout: TimeInterval
let retryDelay: TimeInterval
private var lastFailureTime: TimeInterval?
private var lastError: Error?
private var scheduler: Scheduler?
init(timeout: TimeInterval = 10, maxFailures: Int = 3, retryDelay: TimeInterval = 2) {
self.timeout = timeout
self.maxFailures = maxFailures
self.retryDelay = retryDelay
}
deinit {
scheduler?.suspend()
scheduler = nil
}
}
Implementation in Swift
extension CircuitBreaker {
func start() {
switch state {
case .open:
tripCircuit()
case .halfOpened, .closed:
beginWork()
}
}
}
Implementation in Swift
extension CircuitBreaker {
func start() {
switch state {
case .open:
tripCircuit()
case .halfOpened, .closed:
beginWork()
}
}
}
private extension CircuitBreaker {
func tripCircuit() {
tripped?(self, lastError)
reset()
}
func beginWork() {
scheduler?.suspend()
startTimeoutTimer()
workToPerform?(self)
}
}
Implementation in Swift
extension CircuitBreaker {
func start() {
switch state {
case .open:
tripCircuit()
case .halfOpened, .closed:
beginWork()
}
}
func reset() {
scheduler?.suspend()
failureCount = 0
lastFailureTime = nil
lastError = nil
}
}
private extension CircuitBreaker {
func tripCircuit() {
tripped?(self, lastError)
reset()
}
func beginWork() {
scheduler?.suspend()
startTimeoutTimer()
workToPerform?(self)
}
}
private extension CircuitBreaker {
func startTimeoutTimer() {
scheduler?.suspend()
scheduler = Scheduler(startTime: timeout)
scheduler?.task = { [weak self] in
self?.failure()
}
scheduler?.resume()
}
}
Implementation in Swift
extension CircuitBreaker {
func failure(error: Error? = nil) {
scheduler?.suspend()
lastError = error
failureCount += 1
lastFailureTime = Date().timeIntervalSince1970
switch state {
case .open:
tripCircuit()
break
case .halfOpened, .closed:
startRetryDelayTimer()
break
}
}
}
Implementation in Swift
private extension CircuitBreaker {
func startTimeoutTimer() {
scheduler?.suspend()
scheduler = Scheduler(startTime: timeout)
scheduler?.task = { [weak self] in
self?.failure()
}
scheduler?.resume()
}
func startRetryDelayTimer() {
scheduler?.suspend()
scheduler = Scheduler(startTime: retryDelay)
scheduler?.task = { [weak self] in
self?.beginWork()
}
scheduler?.resume()
}
}
Implementation in Swift
extension CircuitBreaker {
func success() {
reset()
}
func failure(error: Error? = nil) {
scheduler?.suspend()
lastError = error
failureCount += 1
lastFailureTime = Date().timeIntervalSince1970
switch state {
case .open:
tripCircuit()
break
case .halfOpened, .closed:
startRetryDelayTimer()
break
}
}
}
Implementation in Swift
final class Scheduler {
var task: (() -> Void)?
private enum TimerState {
case suspended
case resumed
}
private var timerState: TimerState = .suspended
private let startTime: TimeInterval
private lazy var timer: DispatchSourceTimer = {
let dispatchTimer = DispatchSource.makeTimerSource()
let time: DispatchTime = .now() + startTime
dispatchTimer.schedule(deadline: time)
dispatchTimer.setEventHandler { [weak self] in
self?.task?()
}
return dispatchTimer
}()
init(startTime: TimeInterval) {
self.startTime = startTime
}
deinit {
timer.setEventHandler {}
timer.cancel()
timer.resume()
task = nil
}
}
extension Scheduler {
func resume() {
if timerState == .resumed { return }
timerState = .resumed
timer.resume()
}
func suspend() {
if timerState == .suspended { return }
timerState = .suspended
timer.suspend()
}
}
Lets Demo Our Implementation 🏎
IBM-Swift’s Circuit Breaker
• Provides a heavy duty implementation
• Provides advanced configuration
• Provides a snapshot of the circuit
breaker state
• Can plug in with SwiftMetrics
Lets Demo IBM-Swift’s CircuitBreaker 🏎
Resources
• SGCircuitBreaker: https://github.com/eman6576/SGCircuitBreaker
• Demos: https://github.com/eman6576/CircuitBreakerTime
• IBM-Swift CircuitBreaker: https://github.com/IBM-Swift/CircuitBreaker
Q & A 🚀
Thanks 🎉

More Related Content

Similar to Circuit Breakers with Swift

Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easyUwe Friedrichsen
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingMichael Arenzon
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.ILEran Harel
 
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Yoshifumi Kawai
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDISven Ruppert
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
Meetup talk: Readying your Go Webservice
Meetup talk: Readying your Go WebserviceMeetup talk: Readying your Go Webservice
Meetup talk: Readying your Go WebserviceRalph Ligtenberg
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java ConcurrencyCarol McDonald
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 
Building resilient applications
Building resilient applicationsBuilding resilient applications
Building resilient applicationsNuno Caneco
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel DevelopmentRodrigo Almeida
 
Von neumann workers
Von neumann workersVon neumann workers
Von neumann workersriccardobecker
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Reliability and Reslience
Reliability and ReslienceReliability and Reslience
Reliability and ReslienceDonald Belcham
 

Similar to Circuit Breakers with Swift (20)

Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Curator intro
Curator introCurator intro
Curator intro
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Ob1k presentation at Java.IL
Ob1k presentation at Java.ILOb1k presentation at Java.IL
Ob1k presentation at Java.IL
 
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Meetup talk: Readying your Go Webservice
Meetup talk: Readying your Go WebserviceMeetup talk: Readying your Go Webservice
Meetup talk: Readying your Go Webservice
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Building resilient applications
Building resilient applicationsBuilding resilient applications
Building resilient applications
 
Microkernel Development
Microkernel DevelopmentMicrokernel Development
Microkernel Development
 
Von neumann workers
Von neumann workersVon neumann workers
Von neumann workers
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
Reliability and Reslience
Reliability and ReslienceReliability and Reslience
Reliability and Reslience
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
2.pdf Ejercicios de programaciĂłn competitiva
2.pdf Ejercicios de programaciĂłn competitiva2.pdf Ejercicios de programaciĂłn competitiva
2.pdf Ejercicios de programaciĂłn competitivaDiego IvĂĄn Oliveros Acosta
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
2.pdf Ejercicios de programaciĂłn competitiva
2.pdf Ejercicios de programaciĂłn competitiva2.pdf Ejercicios de programaciĂłn competitiva
2.pdf Ejercicios de programaciĂłn competitiva
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 

Circuit Breakers with Swift

  • 1. Circuit Breakers with Swift ⚡ Swift Cloud Workshop 3 Manny Guerrero (@SwiftyGuerrero)
  • 2. Agenda • History of Circuit Breakers 🧐 • How a Circuit Breaker Works 🔍 • Advantages/Disadvantages with Swift 😕 • Implementation in Swift 🛠 • Demo 🏎 • Q & A 🚀
  • 3. History of Circuit Breakers • Early beginnings in electrical engineering • Was popularized in software by Michael T. Nygard
  • 4. How a Circuit Breaker Works
  • 5. Advantages/Disadvantages with Swift Advantages: • Reduces CPU resources • Can protect parts of a system from failures in other parts • Easy monitoring of the state Disadvantages: • Managing the state can be dicult if OOP isn’t being used. • Need to use specic Timer APIs
  • 6. Implementation in Swift enum BreakerState { case open case halfOpened case closed }
  • 7. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { }
  • 8. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { return .closed } }
  • 9. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { return .closed } var workToPerform: ((CircuitBreaker) -> Void)? var tripped: ((CircuitBreaker, Error?) -> Void)? }
  • 10. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { return .closed } var workToPerform: ((CircuitBreaker) -> Void)? var tripped: ((CircuitBreaker, Error?) -> Void)? let maxFailures: Int let timeout: TimeInterval let retryDelay: TimeInterval }
  • 11. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { return .closed } var workToPerform: ((CircuitBreaker) -> Void)? var tripped: ((CircuitBreaker, Error?) -> Void)? let maxFailures: Int let timeout: TimeInterval let retryDelay: TimeInterval private var lastFailureTime: TimeInterval? private var lastError: Error? private var scheduler: Scheduler? }
  • 12. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { if let lastFailureTime = self.lastFailureTime, failureCount > maxFailures && (Date().timeIntervalSince1970 - lastFailureTime) > retryDelay { return .halfOpened } if failureCount == maxFailures { return .open } return .closed } var workToPerform: ((CircuitBreaker) -> Void)? var tripped: ((CircuitBreaker, Error?) -> Void)? let maxFailures: Int let timeout: TimeInterval let retryDelay: TimeInterval private var lastFailureTime: TimeInterval? private var lastError: Error? private var scheduler: Scheduler? }
  • 13. Implementation in Swift enum BreakerState { case open case halfOpened case closed } class CircuitBreaker { var state: BreakerState { if let lastFailureTime = self.lastFailureTime, failureCount > maxFailures && (Date().timeIntervalSince1970 - lastFailureTime) > retryDelay { return .halfOpened } if failureCount == maxFailures { return .open } return .closed } var workToPerform: ((CircuitBreaker) -> Void)? var tripped: ((CircuitBreaker, Error?) -> Void)? let maxFailures: Int let timeout: TimeInterval let retryDelay: TimeInterval private var lastFailureTime: TimeInterval? private var lastError: Error? private var scheduler: Scheduler? init(timeout: TimeInterval = 10, maxFailures: Int = 3, retryDelay: TimeInterval = 2) { self.timeout = timeout self.maxFailures = maxFailures self.retryDelay = retryDelay } deinit { scheduler?.suspend() scheduler = nil } }
  • 14. Implementation in Swift extension CircuitBreaker { func start() { switch state { case .open: tripCircuit() case .halfOpened, .closed: beginWork() } } }
  • 15. Implementation in Swift extension CircuitBreaker { func start() { switch state { case .open: tripCircuit() case .halfOpened, .closed: beginWork() } } } private extension CircuitBreaker { func tripCircuit() { tripped?(self, lastError) reset() } func beginWork() { scheduler?.suspend() startTimeoutTimer() workToPerform?(self) } }
  • 16. Implementation in Swift extension CircuitBreaker { func start() { switch state { case .open: tripCircuit() case .halfOpened, .closed: beginWork() } } func reset() { scheduler?.suspend() failureCount = 0 lastFailureTime = nil lastError = nil } } private extension CircuitBreaker { func tripCircuit() { tripped?(self, lastError) reset() } func beginWork() { scheduler?.suspend() startTimeoutTimer() workToPerform?(self) } } private extension CircuitBreaker { func startTimeoutTimer() { scheduler?.suspend() scheduler = Scheduler(startTime: timeout) scheduler?.task = { [weak self] in self?.failure() } scheduler?.resume() } }
  • 17. Implementation in Swift extension CircuitBreaker { func failure(error: Error? = nil) { scheduler?.suspend() lastError = error failureCount += 1 lastFailureTime = Date().timeIntervalSince1970 switch state { case .open: tripCircuit() break case .halfOpened, .closed: startRetryDelayTimer() break } } }
  • 18. Implementation in Swift private extension CircuitBreaker { func startTimeoutTimer() { scheduler?.suspend() scheduler = Scheduler(startTime: timeout) scheduler?.task = { [weak self] in self?.failure() } scheduler?.resume() } func startRetryDelayTimer() { scheduler?.suspend() scheduler = Scheduler(startTime: retryDelay) scheduler?.task = { [weak self] in self?.beginWork() } scheduler?.resume() } }
  • 19. Implementation in Swift extension CircuitBreaker { func success() { reset() } func failure(error: Error? = nil) { scheduler?.suspend() lastError = error failureCount += 1 lastFailureTime = Date().timeIntervalSince1970 switch state { case .open: tripCircuit() break case .halfOpened, .closed: startRetryDelayTimer() break } } }
  • 20. Implementation in Swift final class Scheduler { var task: (() -> Void)? private enum TimerState { case suspended case resumed } private var timerState: TimerState = .suspended private let startTime: TimeInterval private lazy var timer: DispatchSourceTimer = { let dispatchTimer = DispatchSource.makeTimerSource() let time: DispatchTime = .now() + startTime dispatchTimer.schedule(deadline: time) dispatchTimer.setEventHandler { [weak self] in self?.task?() } return dispatchTimer }() init(startTime: TimeInterval) { self.startTime = startTime } deinit { timer.setEventHandler {} timer.cancel() timer.resume() task = nil } } extension Scheduler { func resume() { if timerState == .resumed { return } timerState = .resumed timer.resume() } func suspend() { if timerState == .suspended { return } timerState = .suspended timer.suspend() } }
  • 21. Lets Demo Our Implementation 🏎
  • 22. IBM-Swift’s Circuit Breaker • Provides a heavy duty implementation • Provides advanced conguration • Provides a snapshot of the circuit breaker state • Can plug in with SwiftMetrics
  • 23. Lets Demo IBM-Swift’s CircuitBreaker 🏎
  • 24. Resources • SGCircuitBreaker: https://github.com/eman6576/SGCircuitBreaker • Demos: https://github.com/eman6576/CircuitBreakerTime • IBM-Swift CircuitBreaker: https://github.com/IBM-Swift/CircuitBreaker
  • 25. Q & A 🚀