circuitbreaker

package
v0.63.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

README

Circuit breaker configuration

Circuit breaker предотвращает попытки приложения выполнить операцию, которая скорее всего завершится неудачно. Он имеет два состояния: закрытый (запросы будут выполняться) и открытый (отвергаем все запросы, пока circuit не закроется). Используется seq-proxy при работе с шардами, создавая на каждый шард отдельный экземпляр.

В основе используется алгоритм скользящего окна (rolling window) для временного ряда. Общий размер окна (rolling window size) - это время, в течение которого хранятся метрики для использования алгоритмами Closer\Opener. Это окно задается параметрами NumBuckets * BucketWidth.

Где BucketWidth - размер одной ячейки (bucket) в скользящем окне, а NumBuckets - количество ячеек.

Например, для конфига:

Config{
NumBuckets:               10,
BucketWidth:              time.Second,
RequestVolumeThreshold:   15,
ErrorThresholdPercentage: 50,
}

Будет создана структура следующего вида:

img.png

Представим, что к нам каждую секунду в течение 10 приходил запрос, 5 из которых не были завершены успешно:

img_1.png

Из скользящего окна мы можем взять общее число запросов, обозначим ее переменной totalRequests. Circuit breaker не будет открыт, т.к. значение RequestVolumeThreshold не было превышено:

RequestVolumeThreshold := 15 // from the config
totalRequests := 10
checkPercentage := totalRequests >= RequestVolumeThreshold // false
if !checkPercentage { return }

Таким образом, проверка процентного соотношения ошибок не произойдет, хотя количество ошибок 50%. Эта логика нужна для того, чтобы не открывать circuit breaker в случаях, когда у нас не было достаточного количества запросов за временное окно.

Для того же конфига, но следующего распределения:

img.png

RequestVolumeThreshold := 15 // from the config
totalRequests := 17
checkPercentage := totalRequests >= RequestVolumeThreshold // true
if !checkPercentage { return }

fails := 10
shouldOpen := fails / totalRequests * 100 > ErrorThresholdPercentage // true
if shouldOpen { open() }

Теперь circuit breaker откроется и перестанет выполнять запросы, сразу же возвращая ошибку. Так будет происходить до тех пор, пока во время SleepWindow не будет произведен один успешный запрос.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CircuitBreaker

type CircuitBreaker struct {
	*circuit.Circuit
}

func New

func New(name string, config Config) *CircuitBreaker

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, callback func(context.Context) error) error

type Config

type Config struct {
	// Timeout for the execution context.
	Timeout time.Duration
	// MaxConcurrent the maximum number of requests allowed to be executed at one time.
	MaxConcurrent int64

	// NumBuckets the number of buckets the rolling window is divided into.
	NumBuckets int

	// BucketWidth used to compute the duration of the statistical rolling window.
	BucketWidth time.Duration

	// RequestVolumeThreshold number of requests in the rolling window that will trigger
	// a check on the total number of requests as a percentage (ErrorThresholdPercentage).
	// For example, if the value is 20, then if only 19 requests are received in the rolling window
	// the circuit will not trigger percentage check to open the circuit.
	// Set 1 to disable and always trigger percentage check.
	RequestVolumeThreshold int64

	// TotalThresholdPercent ratio in the rolling window of the number of failed requests to the total number of requests.
	// For example, if the value is 10, if total requests in the rolling window is 100 when failed requests is 10,
	// then 10/100 >= 10% -> the circuit will be open.
	ErrorThresholdPercentage int64

	// SleepWindow how long to deny requests before allowing attempts
	// again to determine if the chain should be closed again.
	SleepWindow time.Duration
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL