Course contentsShow
← Java
Lesson 2822 of 2,87051. CompletableFutureFree lesson

Real-World Example: Database Query Followed by API Call

Implement a realistic scenario where a database lookup's result triggers an HTTP request using thenCompose.

Real-World Example: Database Query Followed by API Call

You'll learn how to chain a database lookup with an HTTP request using thenCompose to model a realistic asynchronous workflow.

The Scenario

Imagine you're building an e-commerce system. When a user places an order, you first query the database to fetch product details, then use that information to call a pricing API. Each operation is asynchronous and depends on the previous one's result—perfect for thenCompose.

Implementation Pattern

CompletableFuture<Product> fetchProductFromDb(String productId) {
    return CompletableFuture.supplyAsync(() -> {
        // Simulate database query
        System.out.println("Querying database for product: " + productId);
        return new Product(productId, "Laptop");
    });
}

CompletableFuture<Price> fetchPriceFromApi(Product product) {
    return CompletableFuture.supplyAsync(() -> {
        // Simulate HTTP API call
        System.out.println("Calling pricing API for: " + product.name);
        return new Price(product.id, 999.99);
    });
}

// Chain them with thenCompose
CompletableFuture<Price> workflow = 
    fetchProductFromDb("PROD-123")
        .thenCompose(product -> fetchPriceFromApi(product));

Price finalPrice = workflow.join(); // Block for final result

Why This Works

The first supplyAsync retrieves the Product from the database. Then thenCompose takes that Product and passes it to fetchPriceFromApi, which returns another CompletableFuture<Price>. Without thenCompose, you'd get CompletableFuture<CompletableFuture<Price>>—nested and unusable. thenCompose flattens it automatically.

Realistic Flow

Each stage runs asynchronously on thread pool threads. If the database query takes 2 seconds and the API call takes 1 second, the total time is approximately 3 seconds—but your main thread isn't blocked until you call join().

Key Takeaway: Use thenCompose to chain dependent async operations where the second task needs the first's result, creating clean, readable pipelines that model real-world scenarios like database-then-API workflows.