Skip to content

Implement circuit breaker #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions circuitbreaker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Circuit Breaker Middleware for Echo

This package provides a custom Circuit Breaker middleware for the Echo framework in Golang. It helps protect your application from cascading failures by limiting requests to failing services and resetting based on configurable timeouts and success criteria.

## Features

- Configurable failure handling
- Timeout-based state reset
- Automatic transition between states: Closed, Open, and Half-Open
- Easy integration with Echo framework

## Usage

```go
package main

import (
"net/http"
"time"

"github.com/labstack/echo-contrib/circuitbreaker"

"github.com/labstack/echo/v4"
)

func main() {

e := echo.New()

cbConfig := circuitbreaker.Config{
FailureThreshold: 5, // Number of failures before opening circuit
Timeout: 10 * time.Second, // Time to stay open before transitioning to half-open
SuccessThreshold: 3, // Number of successes needed to move back to closed state
}

cbMiddleware := circuitbreaker.New(cbConfig)

e.GET("/example", func(c echo.Context) error {
return c.String(http.StatusOK, "Success")
}, circuitbreaker.Middleware(cbMiddleware))

// Start server
e.Logger.Fatal(e.Start(":8081"))
}
```

### Circuit Breaker States

1. **Closed**: Requests pass through normally. If failures exceed the threshold, it transitions to Open.
2. **Open**: Requests are blocked. After the timeout period, it moves to Half-Open.
3. **Half-Open**: Allows a limited number of test requests. If successful, it resets to Closed, otherwise, it goes back to Open.
Loading