Performance: Why JWT matters for APIs
This affects API response time and server load by how authentication tokens are verified and managed.
Jump into concepts and practice - no test required
Use JWT tokens that carry user info and are verified via signature without DB calls.Use server-side sessions stored in database for every API request authentication check.
| Pattern | DB Calls | CPU Usage | Response Latency | Verdict |
|---|---|---|---|---|
| Server-side sessions | 1 DB call per request | Higher due to DB I/O wait | Increased by 10-50ms | [X] Bad |
| JWT tokens | No DB calls per request | Lower CPU for signature check | Minimal added latency (~1-2ms) | [OK] Good |
@GetMapping("/profile")
public ResponseEntity<String> getProfile(@RequestHeader("Authorization") String authHeader) {
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
return ResponseEntity.status(401).body("Unauthorized");
}
String token = authHeader.substring(7);
// Assume validateToken returns false if token invalid
if (!jwtService.validateToken(token)) {
return ResponseEntity.status(401).body("Unauthorized");
}
return ResponseEntity.ok("User profile data");
}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String authHeader = req.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
if (jwtService.validateToken(token)) {
SecurityContextHolder.getContext().setAuthentication(null);
}
}
chain.doFilter(request, response);
}