Suppose our microservice needs to call an external API, like a payment gateway, but it suddenly starts to slow down or crashes altogether. How do you usually protect your application from such neighbors to prevent the entire service from failing?
sobes.tech AI
Answer from AI
To protect a microservice from dependencies that may slow down or fail (for example, an external payment system API), the following approaches are usually used:
-
Timeouts and retries — set reasonable timeouts for requests and a limited number of retry attempts.
-
Circuit Breaker — if an external service frequently fails or responds slowly, the circuit breaker temporarily blocks calls to it to avoid overloading the system and waiting too long.
-
Bulkhead — isolate resources by allocating separate thread pools or goroutines for calls to the external service, so that a failure does not spread.
-
Fallback — when the external service is unavailable, return pre-prepared data or placeholders.
-
Monitoring and alerts — track the call status and respond quickly.
In Go, libraries like github.com/sony/gobreaker or github.com/afex/hystrix-go are often used to implement circuit breakers and timeouts.
Example with timeout and circuit breaker:
import (
"context"
"net/http"
"time"
"github.com/sony/gobreaker"
)
var cb *gobreaker.CircuitBreaker
func init() {
cb = gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "PaymentAPI",
MaxRequests: 5,
Interval: 60 * time.Second,
Timeout: 30 * time.Second,
ReadyToTrip: func(counts gobreaker.Counts) bool {
return counts.ConsecutiveFailures > 3
},
})
}
func callPaymentAPI(ctx context.Context, url string) (*http.Response, error) {
result, err := cb.Execute(func() (interface{}, error) {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
client := &http.Client{
Timeout: 5 * time.Second, // request timeout
}
return client.Do(req)
})
if err != nil {
// fallback or error handling
return nil, err
}
return result.(*http.Response), nil
}
Thus, in case of external service issues, our microservice will not hang and can handle the situation correctly.