Statelessness requirement in Rest API - Time & Space Complexity
When building REST APIs, statelessness means each request is independent and carries all needed info.
We want to see how this affects the work the server does as requests come in.
Analyze the time complexity of the following REST API request handler.
GET /items?id=123
// Server receives request
// Parses query parameters
// Looks up item by id in database
// Returns item data as response
This code handles one request by fetching an item using its id from storage.
Each request triggers these steps:
- Primary operation: Database lookup by id
- How many times: Once per request
There are no loops or recursion inside a single request; work depends on the request size.
Each request is handled separately, so work grows linearly with number of requests.
| Number of Requests (n) | Approx. Operations |
|---|---|
| 10 | 10 database lookups |
| 100 | 100 database lookups |
| 1000 | 1000 database lookups |
Pattern observation: More requests mean proportionally more work, but each request cost stays the same.
Time Complexity: O(n)
This means the total work grows directly with the number of requests, since each is handled independently.
[X] Wrong: "The server remembers past requests, so handling new ones gets faster."
[OK] Correct: Statelessness means the server does not keep info between requests, so each request takes similar time.
Understanding statelessness helps you explain how APIs scale and why each request cost matters on its own.
"What if the server started caching results between requests? How would the time complexity change?"