0
0
Rest APIprogramming~5 mins

Graceful degradation in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Graceful degradation
O(1)
Understanding Time Complexity

When building REST APIs, graceful degradation means the system still works even if some parts fail.

We want to see how the time cost changes when handling fallback or error cases.

Scenario Under Consideration

Analyze the time complexity of the following REST API handler with graceful degradation.

async function fetchUserData(userId) {
  try {
    const profile = await fetch(`/api/profile/${userId}`);
    if (!profile.ok) throw new Error('Profile error');
    const data = await profile.json();
    return data;
  } catch {
    return { name: 'Guest', status: 'Limited data' };
  }
}

This code tries to get user profile data. If it fails, it returns default limited data instead.

Identify Repeating Operations

Look for repeated or costly steps in the code.

  • Primary operation: One network request to fetch user profile.
  • How many times: Exactly once per function call, no loops or recursion.
How Execution Grows With Input

The function makes one request regardless of input size.

Input Size (n)Approx. Operations
101 request
1001 request
10001 request

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the function does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "The time grows with the size of the userId or data returned."

[OK] Correct: The function only makes one request and handles one response, so time depends on that single call, not input size.

Interview Connect

Understanding how graceful degradation affects time complexity helps you design APIs that stay efficient even when handling errors or fallback data.

Self-Check

"What if the function made multiple fallback requests in sequence? How would the time complexity change?"