Sobes.tech
Junior

Tell about a universal adapter for external payment gateways: architecture, retry, fallback, circuit breaker, configurable mappings.

sobes.tech AI

Answer from AI

A universal adapter for external payment gateways is an abstraction layer that allows working with different payment providers through a single interface.

Architecture:

  • Incoming requests arrive at the adapter in a common format.
  • The adapter maps this request to the specific gateway format (configurable mappings).
  • Sends the request to the external gateway.
  • Processes the response, converting it back to the common format.

Retry:

  • In case of temporary errors (e.g., timeouts, 5xx errors), the adapter retries the request with exponential backoff.
  • The number of attempts and intervals are configurable.

Fallback:

  • If the primary gateway is unavailable or the retry limit is exceeded, switching to a backup gateway is possible.
  • This increases fault tolerance.

Circuit Breaker:

  • A mechanism that 'breaks the chain' and temporarily blocks requests to a problematic gateway after frequent errors.
  • Helps avoid overload and switch quickly to fallback.

Configurable mappings:

  • Allow defining data transformation rules (e.g., fields, date formats, currencies) for each gateway in configuration files.
  • Provide flexibility and simplify adding new providers without changing the code.

An example of a simplified retry scheme with circuit breaker in pseudocode:

func SendPayment(request PaymentRequest) (PaymentResponse, error) {
    if circuitBreaker.IsOpen() {
        return fallback.SendPayment(request)
    }
    for i := 0; i < maxRetries; i++ {
        resp, err := gateway.Send(request)
        if err == nil {
            circuitBreaker.Reset()
            return resp, nil
        }
        circuitBreaker.RecordFailure()
        time.Sleep(backoff(i))
    }
    circuitBreaker.Open()
    return fallback.SendPayment(request)
}