failover

package
v0.1.15 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 17 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Failover

Transport-level endpoint failover for the IONOS Go SDKs.

failover.RoundTripper is an http.RoundTripper wrapper that retries a request against several configured server endpoints when the underlying transport returns a network-level error, or when the response carries a status code that was explicitly configured for failover. It sits below the product-level callAPI retry loop, so failover happens before the SDK ever sees a response.

Quick start

import (
    "net/http"
    "time"

    "github.com/ionos-cloud/sdk-go-bundle/shared/failover"
)

endpoints := []failover.Endpoint{
    {URL: "https://api.example.com"},
    {URL: "https://api-backup.example.com", SkipTLSVerify: true},
}

opts := failover.Options{
    Strategy:              failover.RoundRobin,
    MaxRetries:            3,
    RetryOnTimeout:        true,
    FailoverOnStatusCodes: []int{502, 503},
    ExponentialBackoff: &failover.ExponentialBackoffOptions{
        InitialInterval: 500 * time.Millisecond,
        MaxInterval:     5 * time.Second,
    },
}

client := &http.Client{
    Transport: failover.NewRoundTripper(endpoints, opts, http.DefaultTransport),
}

Via the config file (shared/fileconfiguration), the same options are read from a failover: block:

failover:
  strategy: roundRobin
  retryableMethods:
    - GET
    - PUT
  retryOnTimeout: true
  failoverOnStatusCodes:
    - 502
    - 503

Request flow

HTTPClient.Do
   └─ RoundTripper.RoundTrip
        ├─ strategy none / empty      → pass through to base transport
        ├─ strategy unknown           → error (configuration error)
        └─ strategy roundRobin        → orderedRoundTrip
                 ├─ method not retryable → pass through to base transport
                 └─ for attempt = 0 .. MaxRetries:
                        server = endpoints[attempt % len(endpoints)]
                        rewrite scheme/host, clone request (GetBody)
                        send via that endpoint's transport
                        ├─ retryable network error  → backoff, next server
                        ├─ status in FailoverOnStatusCodes → drain body, backoff, next server
                        └─ otherwise                → return response
                    all attempts exhausted → return last error (no response)

Total attempts are MaxRetries + 1 (MaxRetries means retries, not attempts). If MaxRetries is 0, shared.DefaultMaxRetries is used.

Only the scheme and host are swapped per endpoint; path and query are preserved. Requests with a body must have GetBody set — the SDK generates requests that way, and retry.CloneRequestForRetry relies on it.

Strategies

Strategy Value Behaviour
failover.None "none" or "" Failover disabled; RoundTrip passes straight through to the base transport with no retry overhead.
failover.RoundRobin "roundRobin" Attempt n targets endpoints[n % len(endpoints)], cycling through servers sequentially.

Comparison is case-insensitive and whitespace-trimmed (NormalizeStrategy). roundRobin with an empty endpoint list is an error; an unrecognised strategy string is surfaced immediately as a configuration error.

Adding a strategy means adding a case to the switch in RoundTrip that builds its own serverOrder function (func(attempt int) int) — or dispatches to an entirely different method.

What triggers a failover

Network errors — failover happens only for an allowlist of transport-level errors. The error must be (or wrap) a *net.OpError carrying one of these syscall errnos:

Errno Typical cause Failover
syscall.ECONNREFUSED Nothing listening on the target port — server down or not yet started. always
syscall.ECONNRESET Peer sent RST: server crashed, restarted, or a middlebox dropped the connection. always
syscall.ECONNABORTED Connection aborted locally, typically an overflowing accept queue on the server. always
syscall.EHOSTUNREACH No route to that host — host down or unreachable from this network. always
syscall.ENETUNREACH The whole target network is unreachable. always
opErr.Timeout() / syscall.ETIMEDOUT Connection or I/O timed out. only when RetryOnTimeout: true

These errors often mean that no reply was received from that endpoint, but they do not prove the server did not process the request (for example, a connection reset can happen after the request is applied). Retrying non-idempotent methods can therefore duplicate side effects; keep the default idempotent method allowlist unless the API is known to make retries safe.

Matching is done with errors.Is, so wrapped errors are detected — see isRetryableNetOpError. An errno that arrives not wrapped in a *net.OpError is not retried; the *net.OpError type check is the outer gate.

HTTP status codes — any code listed in FailoverOnStatusCodes. The response body is drained and closed, then the request goes to the next server. Response headers (e.g. Retry-After) are not inspected at this layer.

What never triggers a failover

Case Why
DNS errors (*net.DNSError) Indicate misconfiguration, not a server being down.
Context cancelled / deadline exceeded (ctx.Err() != nil) The caller aborted; retrying is pointless and hides the cancellation.
TLS / certificate failures Deterministic configuration or protocol problems: tls.CertificateVerificationError, x509.UnknownAuthorityError, x509.HostnameError, x509.CertificateInvalidError, x509.SystemRootsError, tls.RecordHeaderError, tls.AlertError. Failing over would just repeat the same handshake failure.
Redirect and other protocol errors Not in the allowlist; there is no url.Error catch-all.
Non-retryable HTTP methods Passed straight to the base transport.

Default retryable methods are the safe/idempotent ones: GET, HEAD, PUT, DELETE, OPTIONS. Setting RetryableMethods replaces that set entirely. Adding POST/PATCH — especially together with RetryOnTimeout — can produce duplicate side effects, since a timed-out request may already have been applied server-side.

Per-endpoint TLS

Each Endpoint may carry its own SkipTLSVerify / CertificateAuthData. When either is set, a dedicated http.Transport is built for that endpoint at construction time (shared.CreateTransport); otherwise the endpoint shares the base transport passed to NewRoundTripper. Endpoints, transports, and options are snapshotted in the constructor, so mutating the original slices or struct afterwards has no effect on a live instance.

Backoff

Backoff between attempts is exponential, via cenkalti/backoff/v5, and is skipped after the final attempt. ExponentialBackoffOptions overrides only the fields you set; the rest keep the library defaults:

Field Default
InitialInterval 500ms
MaxInterval 60s
Multiplier 1.5
RandomizationFactor 0.5

Setting Multiplier to 1.0 yields constant backoff; combined with RandomizationFactor: 0 you get exact fixed delays. Sleeping honours the request context, so cancellation interrupts a pending backoff.

Interaction with the application-level retry loop

retry.DoWithApplicationRetry (the shared equivalent of each product's callAPI) wraps client.Do, which in turn invokes RoundTrip. The two layers compose as follows:

  • Every application-level retry starts a fresh RoundTrip, which cycles through the servers from the beginning. Worst case total attempts: Configuration.MaxRetries × failover.Options.MaxRetries.
  • If all failover attempts fail, RoundTrip returns an error, not a response. The application-level loop therefore returns immediately and its own status-code retry logic never runs.
  • That matters for overlapping codes: putting 502/503/504 in FailoverOnStatusCodes moves their handling to the transport, bypassing the application-level fixed-backoff retry (and, for 429, the Retry-After handling). Codes not listed pass through as a normal response and are retried by the application layer as usual.

Options reference

Option Type Meaning
Strategy Strategy none (default) or roundRobin.
RetryableMethods []string Methods eligible for failover. Empty → GET, HEAD, PUT, DELETE, OPTIONS.
RetryOnTimeout bool Also fail over on transport timeouts. Never applies to context errors.
FailoverOnStatusCodes []int Status codes that trigger failover to the next server.
MaxRetries int Number of retries (total attempts = MaxRetries + 1). 0 → shared.DefaultMaxRetries.
ExponentialBackoff *ExponentialBackoffOptions Backoff tuning; nil → library defaults.

All fields carry json/yaml tags, so Options can be embedded in configuration files as-is.

Debugging

Every decision is logged through shared.LogDebug with a [Failover] prefix — attempt index, server index and URL, method, target URL, and whether an error or status code was treated as retryable. Enable SDK debug logging to trace a failover sequence.

Files

  • failover_roundtripper.go — RoundTripper, Options, strategies, error classification
  • failover_roundtripper_test.go — behavioural tests (uses typed errors such as *net.OpError and *net.DNSError, not string-matched errors)
  • helpers_test.go — test helpers

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRoundTripper

func NewRoundTripper(endpoints []Endpoint, fo Options, defaultBase http.RoundTripper) http.RoundTripper

NewRoundTripper creates a RoundTripper that cycles through endpoints according to fo when a request fails. Slices in fo are copied so callers can safely mutate the originals.

For each endpoint, a dedicated http.Transport is created when SkipTLSVerify or CertificateAuthData are set; otherwise defaultBase is used.

When the strategy is "none" or empty, RoundTrip passes through to defaultBase with no retry overhead.

Types

type Endpoint

type Endpoint struct {
	URL                 string
	SkipTLSVerify       bool
	CertificateAuthData string
}

Endpoint represents a server endpoint with optional per-endpoint TLS configuration. When SkipTLSVerify or CertificateAuthData are set, a dedicated http.Transport is created for that endpoint at construction time, otherwise the default base transport is shared.

type ExponentialBackoffOptions

type ExponentialBackoffOptions struct {
	// InitialInterval is the initial interval between retries. If zero, it defaults to 500ms.
	InitialInterval time.Duration `json:"initialInterval,omitempty" yaml:"initialInterval,omitempty"`

	// MaxInterval is the maximum interval between retries. If zero, it defaults to 60s.
	MaxInterval time.Duration `json:"maxInterval,omitempty" yaml:"maxInterval,omitempty"`

	// Multiplier is the factor by which the interval increases after each retry. If nil, it defaults to 1.5.
	Multiplier *float64 `json:"multiplier,omitempty" yaml:"multiplier,omitempty"`

	// RandomizationFactor is the factor used to randomize the backoff intervals. If nil, it defaults to 0.5.
	RandomizationFactor *float64 `json:"randomizationFactor,omitempty" yaml:"randomizationFactor,omitempty"`
}

ExponentialBackoffOptions controls the backoff parameters for exponential backoff. By configuring Multiplier and RandomizationFactor, it is possible to achieve a constant backoff or a linear backoff as well.

func (*ExponentialBackoffOptions) NewExponentialBackoff

func (b *ExponentialBackoffOptions) NewExponentialBackoff() boff.BackOff

NewExponentialBackoff creates a new exponential backoff instance configured with the options in b. If b is nil, defaults from cenkalti/backoff are used.

type Options

type Options struct {
	Strategy Strategy `json:"strategy,omitempty" yaml:"strategy,omitempty"`

	// RetryableMethods controls which HTTP methods are eligible for transport-level
	// failover retries. If empty/nil, the default is safe/idempotent methods.
	RetryableMethods []string `json:"retryableMethods,omitempty" yaml:"retryableMethods,omitempty"`

	// RetryOnTimeout controls whether failover retries should also happen when
	// the underlying transport experiences a timeout (for example, a network
	// timeout such as net.OpError.Timeout() / ETIMEDOUT). It does not apply to
	// context cancellation or deadline-exceeded errors (ctx.Err() != nil), which
	// always stop retries.
	RetryOnTimeout bool `json:"retryOnTimeout,omitempty" yaml:"retryOnTimeout,omitempty"`

	// FailoverOnStatusCodes controls whether the transport should fail over to the
	// next server when it receives one of these HTTP status codes.
	FailoverOnStatusCodes []int `json:"failoverOnStatusCodes,omitempty" yaml:"failoverOnStatusCodes,omitempty"`

	// MaxRetries controls how many times the transport will attempt a request using the set strategy before giving up
	// and returning the last error. If zero, it defaults to 3.
	MaxRetries int `json:"maxRetries,omitempty" yaml:"maxRetries,omitempty"`

	ExponentialBackoff *ExponentialBackoffOptions `json:"exponentialBackoff,omitempty" yaml:"exponentialBackoff,omitempty"`
}

Options controls transport-level endpoint failover behaviour. It is nested under Configuration so it can be grouped cleanly in JSON/YAML.

This layer only applies when a multiserver strategy is active (currently only RoundRobin). With None/empty or a single server, the transport passes through directly to the base http.RoundTripper.

Interaction with product-level callAPI retry loop

Product-level callAPI wraps HTTPClient.Do(), which invokes RoundTrip(). Each callAPI retry triggers a fresh RoundTrip() call that cycles through all servers from the beginning. Worst-case total attempts:

callAPI.MaxRetries × Options.MaxRetries

FailoverOnStatusCodes behaviour

Status codes listed in FailoverOnStatusCodes are handled at the transport level: the response body is drained, and the request is retried against the next server with exponential backoff. Response headers (e.g. Retry-After) are not inspected. If all servers return a listed code, RoundTrip returns an error (not an HTTP response), so callAPI receives err != nil and returns immediately — its own status-code retry logic is never reached.

Status codes NOT listed here pass through as a normal HTTP response to callAPI, which has its own retry logic for 502/503/504 (fixed backoff, no POST retry) and 429 (honors Retry-After).

func (*Options) Validate added in v0.1.13

func (o *Options) Validate() error

Validate checks the failover options. It returns nil when the receiver is nil or when every value is acceptable, otherwise an aggregated error describing each problem found.

type RoundTripper

type RoundTripper struct {
	// contains filtered or unexported fields
}

RoundTripper is an http.RoundTripper wrapper that retries the request against multiple configured servers when the underlying transport returns a network-level error or an HTTP status code listed in Options.FailoverOnStatusCodes.

Notes:

  • Network errors trigger retries with exponential backoff, cycling to the next server.
  • Status codes in FailoverOnStatusCodes also trigger retries: the response body is drained and the request is sent to the next server. Response headers (e.g. Retry-After) are not inspected at this layer.
  • If the request carries a body, the request must have GetBody set (the SDK generates requests in a way that supports this).
  • For non-idempotent requests (POST, PATCH, etc.), enabling failover on timeouts can produce duplicates when RetryOnTimeout is set. Context cancellation always stops retries immediately.

The request URL is rewritten by swapping scheme/host with each server URL, preserving path and query.

Endpoints, transports, and options are snapshotted at construction time; subsequent changes to the original slices or struct do not affect this instance.

func (*RoundTripper) RoundTrip

func (t *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper. It validates preconditions and dispatches to a strategy-specific method based on the configured Strategy:

  • RoundRobin: delegates to orderedRoundTrip, which cycles through servers sequentially.
  • None / empty: passes through to the base transport with no retry logic.
  • Unknown strategy: returns an error immediately (configuration error).

New strategies extend the switch in this method — each case builds its own server-selection function (or calls an entirely different method).

This method is called by HTTPClient.Do() inside product-level callAPI. Each callAPI retry triggers a fresh RoundTrip invocation that cycles through all servers from the beginning.

type Strategy

type Strategy string

Strategy selects the endpoint failover behaviour. It is a string type so it serializes nicely to JSON/YAML config files.

Supported values:

  • None ("none") or "": default behaviour (no endpoint failover)
  • RoundRobin ("roundRobin"): on network-level errors, retry the request against the next server in Servers

Note: comparisons should be case-insensitive.

const (
	None       Strategy = "none"
	RoundRobin Strategy = "roundRobin"
)

func NormalizeStrategy

func NormalizeStrategy(s Strategy) Strategy

NormalizeStrategy returns the strategy in lower-case with surrounding whitespace removed, so comparisons are case-insensitive.

Jump to

Keyboard shortcuts

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