Safe methods vs unsafe methods in Rest API - Performance Comparison
We want to understand how the time it takes to handle safe and unsafe REST API methods changes as the number of requests grows.
How does the server's work increase when processing these different methods?
Analyze the time complexity of the following code snippet.
// Example REST API handler
function handleRequest(request) {
if (request.method === 'GET' || request.method === 'HEAD') {
return readData(request);
} else {
return modifyData(request);
}
}
function readData(request) {
// Reads data from database
}
function modifyData(request) {
// Updates database and triggers side effects
}
This code handles safe methods (GET, HEAD) by reading data and unsafe methods by modifying data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading or modifying data per request.
- How many times: Once per request, but modifyData may trigger extra operations like database writes or side effects.
As the number of requests increases, the server does more work for each request.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads or writes |
| 100 | 100 reads or writes |
| 1000 | 1000 reads or writes |
Pattern observation: The work grows directly with the number of requests, whether safe or unsafe.
Time Complexity: O(n)
This means the time to handle requests grows linearly with how many requests come in.
[X] Wrong: "Safe methods like GET take no time or less time than unsafe methods."
[OK] Correct: Both safe and unsafe methods require processing; unsafe methods may do more work, but safe methods still take time to read and respond.
Understanding how different REST methods affect server work helps you explain API performance and design choices clearly in interviews.
"What if modifyData triggered multiple database writes per request? How would the time complexity change?"