Bird
Raised Fist0
Spring Bootframework~8 mins

Returning different status codes in Spring Boot - Performance & Optimization

Choose your learning style10 modes available
Performance: Returning different status codes
MEDIUM IMPACT
This affects the server response time and perceived page load speed by the client, impacting how quickly the browser can proceed after receiving the status code.
Returning HTTP status codes in a Spring Boot REST API
Spring Boot
public ResponseEntity<String> getData() {
    Optional<String> data = service.getDataOptional();
    return data.map(d -> ResponseEntity.ok(d))
               .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not Found"));
}
Returns precise status codes like 404 for missing data, reducing client retries and improving perceived load speed.
📈 Performance GainReduces unnecessary network calls and speeds up client rendering by clear status signaling.
Returning HTTP status codes in a Spring Boot REST API
Spring Boot
public ResponseEntity<String> getData() {
    try {
        String data = service.getData();
        return new ResponseEntity<>(data, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>("Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Using generic exception handling returns 500 status for all errors, causing unnecessary retries or confusion on the client side.
📉 Performance CostBlocks client processing until server responds; may cause extra network round-trips if client retries.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Generic 500 on all errorsN/A (server-side)N/AN/A[X] Bad
Specific status codes (404, 200)N/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
The server sends an HTTP status code that informs the browser how to handle the response. Correct status codes help the browser decide whether to render content, show errors, or retry requests.
→Network Request
→Response Handling
→Rendering
⚠️ BottleneckNetwork Request and Response Handling
Core Web Vital Affected
LCP
This affects the server response time and perceived page load speed by the client, impacting how quickly the browser can proceed after receiving the status code.
Optimization Tips
1Always return the most accurate HTTP status code for the response.
2Avoid generic 500 errors for all failures; use 404, 400, or other codes as appropriate.
3Use status codes to help clients avoid unnecessary retries and speed up page load.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is returning specific HTTP status codes better for performance than always returning 500 on errors?
AIt makes the server response larger in size.
BIt increases server CPU usage.
CIt reduces unnecessary client retries and speeds up error handling.
DIt delays the initial connection to the server.
DevTools: Network
How to check: Open DevTools, go to the Network tab, reload the page or API call, and inspect the status code column for each request.
What to look for: Look for correct HTTP status codes (200, 404, 500) matching the expected server response to confirm efficient status handling.

Practice

(1/5)
1. In Spring Boot, which class is commonly used to return different HTTP status codes from a controller?
easy
A. ResponseEntity
B. HttpStatusCode
C. HttpResponse
D. StatusCode

Solution

  1. Step 1: Understand the purpose of ResponseEntity

    ResponseEntity is a Spring class that allows you to control the HTTP status code, headers, and body of the response.
  2. Step 2: Identify the correct class for status codes

    HttpStatusCode, HttpResponse, and StatusCode are not standard Spring Boot classes for returning responses with status codes.
  3. Final Answer:

    ResponseEntity -> Option A
  4. Quick Check:

    Use ResponseEntity to return status codes [OK]
Hint: Use ResponseEntity to set status codes easily [OK]
Common Mistakes:
  • Confusing ResponseEntity with HttpStatusCode
  • Trying to return status codes without ResponseEntity
  • Using non-existent classes like HttpResponse
2. Which of the following is the correct way to return a 404 Not Found status with a message in a Spring Boot controller?
easy
A. return new ResponseEntity("Not Found", 404);
B. return new ResponseEntity<>("Not Found", 404);
C. return ResponseEntity.status(404).body("Not Found");
D. return ResponseEntity(HttpStatus.NOT_FOUND, "Not Found");

Solution

  1. Step 1: Check the syntax for ResponseEntity with status and body

    The method ResponseEntity.status(404).body("Not Found") correctly sets the status and body.
  2. Step 2: Identify incorrect syntax options

    B uses a constructor with an int 404 instead of HttpStatus.NOT_FOUND. C uses an int instead of HttpStatus enum. D is not a valid constructor call.
  3. Final Answer:

    return ResponseEntity.status(404).body("Not Found"); -> Option C
  4. Quick Check:

    Use ResponseEntity.status().body() for custom status [OK]
Hint: Use ResponseEntity.status(code).body(message) [OK]
Common Mistakes:
  • Using int instead of HttpStatus enum
  • Incorrect constructor usage
  • Missing method chaining for status and body
3. What will be the HTTP status code returned by this Spring Boot controller method?
public ResponseEntity<String> getUser(boolean found) {
    if (found) {
        return ResponseEntity.ok("User found");
    } else {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
    }
}
medium
A. 404 if found is true, 200 if false
B. Always 404
C. Always 200
D. 200 if found is true, 404 if false

Solution

  1. Step 1: Analyze the if condition

    If found is true, the method returns ResponseEntity.ok("User found"), which means HTTP 200.
  2. Step 2: Analyze the else condition

    If found is false, it returns ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"), which means HTTP 404.
  3. Final Answer:

    200 if found is true, 404 if false -> Option D
  4. Quick Check:

    ResponseEntity.ok = 200, status(HttpStatus.NOT_FOUND) = 404 [OK]
Hint: ResponseEntity.ok = 200, status(HttpStatus.NOT_FOUND) = 404 [OK]
Common Mistakes:
  • Mixing up true/false branches
  • Assuming default status 200 always
  • Confusing status codes with messages
4. Identify the error in this Spring Boot controller method that tries to return a 201 Created status:
public ResponseEntity<String> createItem() {
    return new ResponseEntity<>("Item created", 201);
}
medium
A. Cannot return ResponseEntity with a String body
B. Using int 201 instead of HttpStatus enum
C. ResponseEntity constructor requires three arguments
D. Missing @ResponseBody annotation

Solution

  1. Step 1: Check ResponseEntity constructor parameters

    The constructor expects a body and an HttpStatus enum, not an int.
  2. Step 2: Identify the incorrect use of status code

    Passing 201 as int causes a compilation error; should use HttpStatus.CREATED instead.
  3. Final Answer:

    Using int 201 instead of HttpStatus enum -> Option B
  4. Quick Check:

    Use HttpStatus.CREATED, not int 201 [OK]
Hint: Use HttpStatus enum, not int, for status codes [OK]
Common Mistakes:
  • Passing int instead of HttpStatus enum
  • Forgetting to import HttpStatus
  • Assuming String body is invalid
5. You want to create a Spring Boot controller method that returns 201 Created when a new user is successfully added, 400 Bad Request if the input is invalid, and 401 Unauthorized if the user is not logged in. Which code snippet correctly implements this behavior?
hard
A. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) { if (!loggedIn) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized"); } if (!validInput) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input"); } return ResponseEntity.status(HttpStatus.CREATED).body("User created"); }
B. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) { if (!validInput) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized"); } if (!loggedIn) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input"); } return ResponseEntity.status(HttpStatus.CREATED).body("User created"); }
C. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) { if (!loggedIn) { return new ResponseEntity<>("Unauthorized", 401); } if (!validInput) { return new ResponseEntity<>("Invalid input", 400); } return new ResponseEntity<>("User created", 201); }
D. } ;)102 ,"detaerc resU"(>gnirtS

Solution

  1. Step 1: Verify correct use of HttpStatus enums

    public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) { if (!loggedIn) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized"); } if (!validInput) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input"); } return ResponseEntity.status(HttpStatus.CREATED).body("User created"); } uses HttpStatus.UNAUTHORIZED, HttpStatus.BAD_REQUEST, and HttpStatus.CREATED enums correctly.
  2. Step 2: Check logical order and syntax

    This code checks !loggedIn first, then !validInput, then returns 201. Options B, C, and D misuse status codes or pass ints to constructors instead of using HttpStatus enums.
  3. Final Answer:

    Uses HttpStatus enums with correct logic: !loggedIn (401), !validInput (400), then 201 -> Option A
  4. Quick Check:

    Use HttpStatus enums and correct logic order [OK]
Hint: Check login first, then input, use HttpStatus enums [OK]
Common Mistakes:
  • Passing int status codes instead of HttpStatus enums
  • Mixing up 400 and 401 status codes
  • Incorrect order of condition checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard