Client-server architecture in Rest API - Time & Space Complexity
When we use client-server architecture, the client sends requests and the server processes them. We want to understand how the time to handle these requests changes as more requests come in.
How does the server's work grow when many clients ask for data?
Analyze the time complexity of the following code snippet.
// Server receives a list of user IDs
function getUserData(userIds) {
let results = [];
for (let id of userIds) {
let data = database.queryUser(id); // fetch user data
results.push(data);
}
return results;
}
This code fetches user data for each ID sent by the client, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each user ID to query the database.
- How many times: Once for each user ID in the input list.
As the number of user IDs increases, the server does more database queries, one per ID.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 database queries |
| 100 | 100 database queries |
| 1000 | 1000 database queries |
Pattern observation: The work grows directly with the number of user IDs; doubling the input doubles the work.
Time Complexity: O(n)
This means the server's work grows in a straight line with the number of requests it handles.
[X] Wrong: "The server handles all requests instantly, so time doesn't grow with more users."
[OK] Correct: Each request needs its own processing time, so more requests mean more total work and longer total time.
Understanding how server work grows with requests helps you design better APIs and explain performance clearly in interviews. It shows you know how systems handle real-world loads.
"What if the server could fetch data for all user IDs in one database query? How would the time complexity change?"