Docs Home
Start your 30 day free trial.
START FOR FREE

Reliability Intelligence: Implement fallbacks around unreachable dependencies

At its core, a dependency fallback is simply a “plan b” for when the dependency cannot be reached. Fallbacks can vary in complexity from static responses, previously received cached data, to a completely separate subroutine. Choosing to implement a fallback for a given dependency will depend on your application’s priorities. See Simple example with Failsafe for a full example (Java).

‍

When not to implement a fallback?

When a network dependency cannot be reached, choosing between returning a fallback response versus returning an error depends on how your application prioritizes consistency versus availability. For some applications, it’s much more important to return something (such as stale or cached data) over returning an error. However, in other cases it can be much more important to surface an error.

‍

Example: Availability over Consistency (fallback)

A social media feed may choose to show older posts when a dependency responsible for yielding new posts is temporarily unavailable.

‍

Example: Consistency over Availability (no fallback)

A financial institution may choose to fail transactions if it cannot successfully read or write correct balance information across parties involved.

‍

Simple example with Failsafe

The following example uses the Java library Failsafe which contains primitives like the Fallback interface for easy implementation and lots of flexibility. Similar libraries exist for other languages (Failsafe-go).

‍

Java

import dev.failsafe.Failsafe;
import dev.failsafe.Fallback;
import dev.failsafe.Timeout;

import java.time.Duration;

public class DependencyClient {
    /// Often, your dependency client can be configured with a timeout instead
    static final Timeout<String> TIMEOUT = Timeout.of(Duration.ofSeconds(1));

    /// Simulate a call to an external service
    public String fetchData() {
        throw new RuntimeException("Dependency failed");
    }

    public static void main(String[] args) {
        DependencyClient client = new DependencyClient();

        // Fallback when timeout or exception occurs
        Fallback<String> fallback = Fallback.of(() -> "default-value");

        // Wrap the call
        String result = Failsafe.with(fallback, TIMEOUT)
            .get(() -> client.fetchData());

        System.out.println(result); // prints "default-value"
    }
}
On this page
Back to top
RELATED PAGES