Graceful degradation in Rest API - Time & Space 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.
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.
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.
The function makes one request regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 request |
| 100 | 1 request |
| 1000 | 1 request |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the function does not grow with input size; it stays constant.
[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.
Understanding how graceful degradation affects time complexity helps you design APIs that stay efficient even when handling errors or fallback data.
"What if the function made multiple fallback requests in sequence? How would the time complexity change?"