Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 20

Orchestrating Concurrent Data for Complex UIs

Recommended resources

Welcome to our next lesson in the Networking & Data Fetching module. In our previous session, we established the Backend for Frontend (BFF) as a powerful pattern for creating a dedicated API layer for each client, simplifying the frontend by offloading data aggregation from complex microservice architectures. Now, we'll peel back that layer and design the engine inside the BFF: the request orchestrator.

This lesson tackles the heart of what makes a complex, data-rich application feel both fast and robust. We will design systems to manage concurrent and dependent data sources, and most critically, to handle the inevitable reality of partial failures. Your ability to architect a system that degrades gracefully—where the failure of a minor feature doesn't cascade into a full-blown outage—is a hallmark of a senior engineer.

1. Overview: From Data Chaos to Coordinated Flow

At scale, a single user interface is rarely powered by a single API call. A typical e-commerce product page, for instance, might need data from a ProductService, ReviewService, InventoryService, PricingService, and RecommendationService. Simply firing off requests from the client as components render creates a "chatty" interface and performance-killing "request waterfalls."

Request orchestration is the practice of intelligently coordinating these multiple data-fetching operations. A robust orchestrator, ideally living within your BFF, understands which requests can run in parallel, which must run in sequence, and what to do when any one of them fails. This is a core competency tested in L5+ interviews, where demonstrating end-to-end thinking—from backend microservice to client-side error boundary—is expected.


2. Core Concepts: Dependencies and Failures

Before diving into patterns, let's define our key challenges.

  • Concurrent (Parallel) Requests: These are independent data needs. On a product page, fetching the main product details and fetching user reviews are concurrent; neither depends on the other. Our goal is to maximize parallelism.
  • Dependent (Sequential) Requests: These create a chain. To fetch a user's shopping cart, you might first need to fetch the user's profile to get their cartId. This is a natural, but dangerous, source of latency if not managed carefully.
  • Partial Failure: One or more downstream services fail, but others succeed. If the RecommendationService is down, the user must still be able to see the product details and add it to their cart. The system must degrade gracefully, not fail catastrophically.

The diagram below shows an API Gateway handling requests. In a complex system, the gateway or a BFF is responsible for orchestrating calls to the various services.

This diagram shows an API Gateway mediating requests from various clients to backend microservices. The "Orchestration" block within the gateway is where the logic we're discussing today would live, handling parallel and sequential calls to services like User, Order, and Payment.

3. Deep Dives: Orchestration and Resilience Patterns

Deep Dive 1: Taming the Request Waterfall

The most common performance pitfall in data-heavy apps is the request waterfall. This occurs when you chain requests sequentially that could have been executed in parallel.

Data Fetching Patterns in Single-Page Applications

Martin Fowler's blog provides an excellent breakdown of common data-fetching patterns. We'll focus on the section that clearly illustrates the request waterfall problem.

Read the section about implementing a friends list. Pay close attention to Figure 6, "Request waterfall." The author explains how the Fetch-On-Render approach, where a child component starts fetching only after its parent has rendered, leads to this inefficient, sequential loading pattern.

To combat this, we use parallel fetching.

Pattern: Parallel Data Fetching with Promise.all

The most direct way to prevent a waterfall is to identify all independent requests and fire them off simultaneously. In JavaScript, Promise.all is the classic tool for this.

Let's revisit the user dashboard example from your NestJS experience. The client needs the user's profile, their last order, and their notification count. Instead of the client making three separate requests, it makes one call to the BFF. The BFF then becomes the orchestrator.

// Inside a NestJS BFF controller
@Get('/dashboard')
async getDashboardData(@Req() request) {
  const userId = request.user.id;

  try {
    const [user, lastOrder, notifications] = await Promise.all([
      this.userService.fetchUser(userId),
      this.orderService.fetchLastOrder(userId),
      this.notificationService.fetchUnreadCount(userId),
    ]);

    // Aggregate and return a single, clean payload
    return {
      greeting: `Welcome, ${user.name}`,
      lastOrderStatus: lastOrder.status,
      notificationCount: notifications.count,
    };
  } catch (error) {
    // Handle failure of the entire orchestration
    throw new InternalServerErrorException('Failed to load dashboard');
  }
}

This Fetch-Then-Render approach, where the data is fetched and aggregated before sending it to the client for rendering, is vastly more efficient.

Data Fetching Patterns in Single-Page Applications

Now, let's look at the solution to the waterfall problem discussed in the same article.

Read the section on parallel data fetching. The article demonstrates how to use Promise.all to fetch user and friends data concurrently, dramatically shortening the total wait time as shown in Figure 9. This is the core principle of efficient orchestration.

Handling Mixed Dependencies

What if some requests are dependent? Imagine our dashboard also needs a list of "suggested projects," which depends on the user's team ID (part of the user profile).

The orchestration logic becomes slightly more complex:

  1. Start the independent requests: userService.fetchUser(userId) and notificationService.fetchUnreadCount(userId).
  2. await the user promise.
  3. Once the user data is available, use user.teamId to kick off the projectService.fetchSuggestions(user.teamId) call.
  4. await all remaining promises.
  5. Aggregate and return.

By placing this logic in the BFF, the client remains simple and unaware of this complex dependency graph. It just makes one request and gets one response.

Deep Dive 2: Designing for Partial Failure

In a distributed system, failure is not an 'if,' but a 'when.' A senior engineer designs for it from day one. When your BFF calls five downstream services, you must assume any one of them could fail or become slow.

Pattern: Circuit Breaker

If a service is failing repeatedly, continuing to hammer it with requests is counterproductive. It adds load to a struggling service and makes your own application slow. The Circuit Breaker pattern solves this.

A circuit breaker acts as a state machine proxy for your requests:

  • Closed: The normal state. Requests pass through to the downstream service. If requests start failing, a failure counter increases.
  • Open: If the failure count exceeds a threshold, the circuit "opens." For a configured timeout period, all requests immediately fail without even being sent to the downstream service. The BFF returns a fallback response instantly.
  • Half-Open: After the timeout, the circuit becomes "half-open." It allows a single "probe" request to go through. If it succeeds, the circuit closes. If it fails, the circuit opens again.
This diagram shows the three states of the Circuit Breaker pattern. The system transitions from Closed to Open after multiple failures. After a timeout, it enters a Half-Open state to test the service, either returning to Closed on success or back to Open on failure.

The 3 a.m. Call That Changed The Way I Design APIs - The New Stack

This article is a fantastic "war story" about building resilient APIs. It provides a practical, business-driven perspective on why these patterns matter.

Read the section on partial failure. The author explains how implementing circuit breakers and fallbacks prevented cascading failures and led to a system that "degraded gracefully." The key takeaway is powerful: "A degraded response is almost always better than an error."

Pattern: Timeouts and Fallbacks

Every single outbound request from your orchestrator must have an aggressive timeout. A service that takes 30 seconds to respond is, for all practical purposes, a failed service.

When a request fails (either by timeout or because the circuit is open), you must have a fallback strategy:

  • Return Empty/Null Data: For the RecommendationService, the BFF can simply return an empty array []. The client sees the empty array and can choose to hide the recommendations carousel.
  • Return Stale Data: For a PricingService, the BFF could return a cached price from 5 minutes ago, perhaps with a flag indicating the data is stale. This is often better than showing no price at all.
  • Return a Default Value: For a FeatureFlagService, you could default to the "off" state for the flag.

Connecting to the Frontend: Suspense and Error Boundaries

How the BFF shapes its response directly impacts the client's ability to handle partial failure. Instead of the entire /dashboard request failing because one service is down, the BFF should succeed, returning a response where the data for the failed part is explicitly null or includes an error object.

// Successful response, even with partial failure
{
  "user": { "name": "Akhil" },
  "orders": [ /* ... */ ],
  "analytics": null, // or { "error": "Analytics service is currently unavailable" }
}

This allows the frontend to use patterns like React Suspense and Error Boundaries to handle the failure gracefully at the component level.

React Suspense: The Pattern That Instantly Fixes Data Fetching Hell 🔥

This video by tapaScript gives a masterclass on using Suspense and Error Boundaries to handle these exact scenarios on the client.

Watch how to wrap individual components in <Suspense> from this section. This allows parts of the UI to render with skeletons while other parts are still loading, preventing a single slow component from blocking everything. Next, observe how <ErrorBoundary> is combined with <Suspense> from this part. When a component's data fetch fails (the promise rejects), its specific error boundary catches it and displays a fallback UI, without crashing the rest of the dashboard. This is the client-side realization of the graceful degradation we designed in the BFF.


4. Trade-Off Analysis: Centralized vs. Decentralized Orchestration

Factor Centralized Orchestration (BFF) Decentralized Orchestration (Client)
Performance High. Reduces network round trips to a single call. Better for low-power clients and slow networks as aggregation logic is server-side. Low. Can create "chatty" clients with multiple round trips and request waterfalls, increasing perceived latency.
Complexity Shifts complexity to the BFF. The client becomes much simpler. Adds operational overhead (deploying/monitoring a new service). High client complexity. The client must manage multiple loading states, error states, dependency logic, and retries.
Resilience High. Enables advanced, centralized resilience patterns like circuit breakers, smart retries, and cached fallbacks. Moderate. Can use error boundaries for UI resilience, but lacks context for system-level patterns like circuit breaking.
Team Velocity High. The frontend team owns the BFF and can iterate on data requirements without waiting for multiple backend teams. Low. A single UI change might require coordinated changes across several backend teams, slowing down development.
When to Use Complex applications with multiple microservices, diverse clients (web, mobile), and stringent performance/resilience requirements. Simpler applications, monoliths, or when you have a single client and a well-structured API that already provides aggregated data.

5. Design Challenge

Prompt: Design the request orchestration for the main dashboard of a project management tool like Asana.

UI Components:

  • User Profile Header (avatar, name)
  • "My Tasks" list (tasks assigned to the user, sorted by due date)
  • "Activity Feed" (recent updates in projects the user follows)
  • "Projects" list (list of user's projects)

Data Sources (Microservices): UserService, TaskService, ActivityService, ProjectService.

Non-Functional Requirements:

  • The dashboard must have a low LCP. The header and "My Tasks" are critical for the initial view.
  • The Activity Feed is non-critical. If the ActivityService fails, the rest of the dashboard must render correctly.
  • Fetching "My Tasks" requires the userId. The Activity Feed depends on a list of projectIds fetched from the ProjectService.

Your Task:

  1. Draw a sequence diagram showing the orchestration flow within a BFF.
  2. Identify which requests can be made in parallel and which are sequential.
  3. Describe your strategy for handling a timeout failure from the ActivityService. What response does the BFF send, and how does the client render it?

6. Senior-Level Insight

A mid-level engineer will correctly identify the need for Promise.all and will likely place this logic on the client. They'll spot the sequential dependency for the Activity Feed. When a service fails, their solution might be a global error message that degrades the entire user experience.

A senior engineer immediately frames the solution around a BFF. Their orchestration logic will not only use Promise.all but will also be wrapped with aggressive timeouts for every downstream call. They will introduce the Circuit Breaker pattern as a non-negotiable for resilience. When discussing the ActivityService failure, they won't just say "it fails"; they'll specify that the BFF should catch the error, log it for observability, and purposefully return a successful 200 OK response to the client with activityFeed: null. This demonstrates a deep understanding of how to build a resilient system end-to-end, enabling the client to handle the failure gracefully with an Error Boundary at the component level rather than the page level.


7. Common Mistakes in Interviews

  • Forgetting Timeouts: Not explicitly mentioning that every downstream call must have a timeout is a red flag. A hanging request is a fatal flaw in an orchestrator.
  • Creating a Brittle System: Designing an "all-or-nothing" system where the failure of one non-critical microservice causes the entire BFF request to fail with a 500 error.
  • Client-side Orchestration by Default: Proposing to have the client make 5-10 requests for a complex page without first considering a BFF to abstract that complexity away.
  • Ignoring the "Why": Implementing Promise.all without explaining that it's to prevent a request waterfall and improve LCP.
  • Stopping at the BFF: Not connecting the BFF's error response shape to how the client-side framework (e.g., React with Suspense/Error Boundaries) would consume it to provide a seamless user experience.

8. Conclusion

You now have a powerful set of patterns for orchestrating complex data requirements. By moving this logic into a BFF, you can drastically improve performance, simplify your client code, and—most importantly—build resilient systems that withstand the inevitable failures of a distributed architecture. You've learned to not only fetch data in parallel but also to design for partial failure using circuit breakers, timeouts, and fallbacks.

Key Takeaways:

  • Orchestrate in the BFF: Use a Backend for Frontend to centralize data aggregation logic.
  • Maximize Parallelism: Use Promise.all to fight request waterfalls and reduce latency.
  • Embrace Partial Failure: A degraded experience is better than a 500 error. Design for graceful degradation from day one.
  • Use Circuit Breakers and Timeouts: Protect your system from slow or failing downstream services to prevent cascading failures.
  • Connect Backend and Frontend: The shape of your BFF's error response enables the client to use tools like Suspense and Error Boundaries for a granular, resilient UI.

In our next lesson, we'll stay within the Networking & Data Fetching module and complete our trifecta by designing the data-fetching architecture for an e-commerce product page, bringing together everything we've learned about BFFs, orchestration, and caching in a comprehensive, real-world scenario.