422 Unprocessable Entity in Rest API - Time & Space Complexity
When a server returns a 422 Unprocessable Entity, it means the request was understood but has invalid data. We want to understand how checking this data affects the time it takes to process the request.
How does the server's work grow as the input data size grows?
Analyze the time complexity of the following code snippet.
POST /api/users
{
"name": "Alice",
"email": "alice@example.com",
"age": 30
}
// Server validates each field before saving
function validateRequest(data) {
for (let key in data) {
validateField(key, data[key]);
}
}
This code checks each field in the request to decide if the data is valid or should return a 422 error.
- Primary operation: Validation checks on each field of the input data.
- How many times: Once per field; each check runs a fixed number of times regardless of input size.
Since the server loops over each field in the input to validate it, the work grows linearly with the number of fields.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 fields | 10 checks |
| 100 fields | 100 checks |
| 1000 fields | 1000 checks |
Pattern observation: The time grows directly with the number of fields to validate.
Time Complexity: O(n)
This means the time to check the data grows in a straight line as the number of fields increases.
[X] Wrong: "The server always takes the same time to respond with 422 no matter the input size."
[OK] Correct: The server must check each field, so more fields mean more checks and more time.
Understanding how validation scales helps you design APIs that handle data efficiently and respond quickly, a useful skill in real projects and interviews.
"What if the validation included nested objects or arrays? How would the time complexity change?"