REST API Fallback mechanism!

Handling API calls when the client or server is down requires planning for resilience, retries, and fallback mechanisms. Here’s how to approach it:


βœ… 1. Clarify Who is Down


Scenario Strategy
πŸ”΄ Client is down Client retries later or uses message queue
πŸ”΄ Server is down Client implements retries, circuit breakers, fallback

Β 

Let’s focus on client making a call and the server is down.


πŸ› οΈ Strategies to Handle API Call When Server is Down

βœ… A. Retry with Exponential Backoff

  • Automatically retry the failed request after waiting.
  • Increase wait time between attempts (e.g., 1s, 2s, 4s).

Example with Spring RestTemplate + RetryTemplate

RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.execute(context -> restTemplate.getForObject(url, String.class));

You can configure attempts, delay, backoff policy.


βœ… B. Circuit Breaker Pattern

  • Prevent system overload by stopping calls after repeated failures.
  • Automatically retries when the service becomes healthy.

πŸ”§ Tools:

  • Resilience4j (Recommended for Spring Boot)
  • Hystrix (deprecated)

@CircuitBreaker(name = "userApi", fallbackMethod = "fallbackUser")
public User getUser() {
Β  Β  return restTemplate.getForObject("http://api/user", User.class);
}

public User fallbackUser(Exception e) {
Β  Β  return new User("default", "offline");
}


βœ… C. Queue the Request (Asynchronous Retry)

  • Send the request to a message queue (e.g., Kafka, RabbitMQ).
  • Retry processing when the server is back up.
  • Useful for non-blocking use cases like order processing, email sending, etc.


βœ… D. Log and Alert

  • Log failure with request details.
  • Optionally alert DevOps team via Slack, Email, etc.

βœ… E. Client Timeout and Graceful UI Response

  • Always set client-side timeouts.
  • Show proper fallback message to user: β€œService temporarily unavailable, please try again later.”

πŸ” Bonus: Detecting If Server is Down

  • Ping health check endpoint before making a heavy call.
  • Use Spring Boot Actuator on the server side: /actuator/health

πŸ”’ Best Practices Summary

Practice Benefit
Retry with backoff Avoid hammering the server
Circuit breaker Fail fast, self-heal system
Fallback response Provide continuity to users
Message queue Ensure no data loss
Health checks Prevent unnecessary calls
Back to blog

Leave a comment