Auditing and Refactoring a Flawed Spring Boot Order Controller
Easy · Software Engineering Fundamentals · Java Developer · Onsite
Prompt
During a pull-request review for a trading backend service, a teammate proposes the following Spring Boot REST controller for submitting equity orders and reading an account's order log:
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@PostMapping("/create")
public ResponseEntity placeOrder(@RequestBody OrderRequest request) {
PricingClient pricingClient = new PricingClient();
if (request.getQuantity() <= 0) {
return ResponseEntity.status(500).body("Invalid share count");
}
double currentPrice = pricingClient.getQuote(request.getTicker());
Order order = new Order();
order.setTicker(request.getTicker());
order.setQuantity(request.getQuantity());
order.setExecutedPrice(currentPrice);
order.setTimestamp(dateFormat.format(new Date()));
orderRepository.save(order);
return ResponseEntity.status(200).body("Order submitted");
}
@GetMapping("/history/{accountId}")
public List getHistory(@PathVariable String accountId) {
try {
return orderRepository.findAllByAccountId(accountId);
} catch (Exception e) {
return new ArrayList();
}
}
}
Conduct a thorough engineering review of this controller and rewrite it to production quality.
Scope & Expectations
- Pinpoint at least five concrete defects spanning concurrency safety on singleton beans, per-request client allocation, domain data correctness, HTTP status/resource conventions, error handling, and unbounded database reads.
- Explain the architectural remedy for each defect—covering constructor injection, shared client beans, DTO validation, centralized
@RestControllerAdviceerror responses, financial data types, and pagination. - Present a clean, refactored Spring Boot controller, service layer, and global exception handler.
Step-by-step walkthrough
Overview: auditing the controller as a shared singleton
Before checking individual lines, recall how Spring Boot runs a
@RestController: by default, the controller is a singleton—Spring creates one instance at startup and shares it across every incoming HTTP request (up to 200 concurrent Tomcat worker threads by default). That execution model exposes two opposite failure modes immediately: - Instance fields on the controller are shared by all concurrent threads at once, so any mutable field is a concurrency bug. - Objects created withnewinside a method are rebuilt from scratch on every single HTTP request, so heavy clients waste connections, CPU, and memory.Scanning the controller systematically across concurrency, resources, HTTP design, data integrity, and scalability reveals 10 distinct issues:
# Bug or Anti-Pattern Category Impact 1 Shared SimpleDateFormatinstance fieldThread safety Corrupted trade timestamps or runtime exceptions under concurrent load 2 new PricingClient()insideplaceOrderResource waste Destroys connection pooling; leaks sockets/threads; untestable 3 ordernever setsaccountIdDomain correctness Newly placed orders never appear in getHistory(accountId)4 catch (Exception e)returns200 OKwith[]Exception handling Database outage looks like an empty order history; zero logs or alerts 5 Returns 500onquantity <= 0and200string on createHTTP semantics False server-error pages on bad client input; missing 201+Location6 findAllByAccountIdhas no paginationScalability Large accounts load tens of thousands of rows at once, risking OutOfMemoryError7 Pricing, mapping, and persistence inside controller Layer abstraction Tightly coupled web/business/data logic; hard to reuse or test 8 Field @Autowired, rawList/ResponseEntity, JPA entity exposedAPI & maintainability Hidden non- finaldependencies; loses type safety; couples JSON to DB schema9 Stock price stored as double; zone-less timestampStringFinancial precision Binary floating-point rounding errors on money; ambiguous timezones 10 Missing @Validinput checks and account ownership checkValidation & security Null inputs throw 500; any user can read another user'saccountIdThread safety and financial data types
1. Shared
SimpleDateFormatcorrupts timestamps across threads.SimpleDateFormatstores intermediate digits inside a mutable internalCalendarfield while formatting. When two worker threads calldateFormat.format(...)on the singleton controller at the same millisecond, they overwrite each other'sCalendar:Thread A (Order 1 at 10:15:03) Thread B (Order 2 at 10:15:07) ------------------------------------------ ------------------------------------------ calendar.setTime(10:15:03) calendar.setTime(10:15:07) <-- overwrites A! reads calendar -> "2025-05-01 10:15:07" (Order 1 is recorded with Order 2's timestamp, or throws ArrayIndexOutOfBoundsException!)In addition,
"yyyy-MM-dd HH:mm:ss"omits the timezone offset, making timestamps ambiguous during Daylight Saving Time transitions. Fix: deleteSimpleDateFormat, inject ajava.time.Clock, and record execution time asjava.time.Instant(an exact UTC point serialized as ISO-8601, such as"2025-05-01T14:15:03Z"). If formatted strings are ever needed,DateTimeFormatteris immutable and completely thread-safe.2.
doublesilently loses cents on money. IEEE-754 binary floating-point (double) cannot represent most base-10 fractions such as0.01or19.99exactly. For example, buying100shares at$19.99indoublecomputes19.99 * 100 == 1998.9999999999998; truncating to two decimal places yields$1,998.99—one cent short! Fix: represent all prices and monetary amounts withBigDecimal(backed byDECIMAL(19, 4)in SQL).3. Missing
accountIdorphans every placed order.placeOrdersets ticker, quantity, price, and timestamp, yet never setsaccountId—even thoughgetHistoryqueriesfindAllByAccountId(accountId). Every saved order hasaccountId = nulland never shows up in history! Fix: scope the endpoint under/api/accounts/{accountId}/orders, verify the authenticated caller is authorized foraccountId, and persistaccountIdon theOrder.Per-request client waste and dependency injection
Inside
placeOrder,PricingClient pricingClient = new PricingClient();builds a brand-new network client on every single order: - Wasted latency and CPU: HTTP clients maintain keep-alive connection pools so requests reuse open TLS sockets. Constructing a fresh client per call forces a brand-new TCP + TLS handshake every time. For example, if building the client and completing a fresh TLS handshake adds35 msand2 MBof buffers per call, then at100 orders/secthe service burns100 * 0.035 s = 3.5 thread-secondsevery second and allocates200 MB/secof avoidable garbage. - Socket and thread leaks: Heavy clients often spawn background connection-eviction threads and hold OS file descriptors. BecausepricingClientis never closed, sockets accumulate until the pod crashes withToo many open filesorOutOfMemoryError. - Untestable code: Callingnew PricingClient()directly inside the method makes it impossible to pass a mock client in unit tests.Fix: register
PricingClientonce as a singleton@Bean(where connection pool sizes and socket timeouts are configured centrally and Spring closes the client cleanly on shutdown), move business orchestration into anOrderService, and wire all dependencies via constructor injection withprivate finalfields. Also make sure the network callpricingClient.getQuote(...)runs outside any@Transactionaldatabase block so database pool connections are never held idle waiting on external network I/O.HTTP status codes, RESTful URLs, and input validation
Clean REST APIs use HTTP status codes, resource nouns, and typed Data Transfer Objects (DTOs)—lightweight request/response classes that decouple the public JSON contract from internal database tables:
- Use accurate HTTP status codes:
quantity <= 0is invalid client input, so return400 Bad Request, never500 Internal Server Error. Returning500tells load balancers, clients, and monitoring dashboards that the server itself crashed, triggering false on-call pages and wasteful client retries. On successful creation, return201 Createdwith aLocationheader (/api/accounts/{accountId}/orders/{orderId}) and the createdOrderResponseJSON body rather than200 OKwith a plain string. - Use noun-based resource paths: Replace
/api/orders/create(which puts an action verb in the path whenPOSTalready means create) with/api/accounts/{accountId}/orders(POSTto place an order,GETto list history). - Validate declaratively with Bean Validation (
@Valid): If a client sends{}(quantity == null,ticker == null),request.getQuantity() <= 0in the original code throws aNullPointerExceptionwhen unboxing anullInteger! Annotating a JavarecordDTO with@NotBlankand@NotNull @Positiveplus@Validrejects malformed payloads automatically with400 Bad Requestbefore controller logic even runs. - Eliminate raw types and direct JPA entity returns: Replace raw
ResponseEntityandListwithResponseEntity<OrderResponse>andOrderPage. Returning JPAOrderentities directly leaks internal database columns and risksLazyInitializationExceptionduring JSON serialization. - Authorize account access: Without an ownership check on
{accountId}, any logged-in user can read or trade on another customer's account simply by guessing an ID in the URL (an Insecure Direct Object Reference, or IDOR). Guard both endpoints with Spring Security's@PreAuthorize.
- Use accurate HTTP status codes:
Exception swallowing and unbounded history pagination
Look at
getHistoryin the original code:try { return orderRepository.findAllByAccountId(accountId); } catch (Exception e) { return new ArrayList(); }This block has two severe production hazards:
- Silent failure masquerading as empty data: When the database is unreachable or times out, catching
Exceptionand returning[]sends200 OKwith an empty JSON array. Customers see$0/ zero orders in their history, monitoring reports100%healthy200responses, and nothing is written to error logs! Instead, let infrastructure exceptions propagate to a central@RestControllerAdvicethat logs the error once and returns503 Service Unavailablewith a structured error payload. - Unbounded result set:
findAllByAccountIdloads every historical order for that account into memory at once. Consider a frequent trader or institutional account with50,000orders at~500 bytesof JSON per order: a singleGETserializes25 MBof JSON (plus tens of megabytes of Hibernate entity state). Just20concurrent refreshes pull1,000,000rows and500 MB+onto the JVM heap, starving worker threads and triggeringOutOfMemoryError. Fix: paginate using Spring Data'sPageable(with a sensible default likesize = 50and a strict max page size cap viaspring.data.web.pageable.max-page-size=200) and return aSlice<Order>sorted newest-first (executedAt DESC). ReturningSlicefetchessize + 1rows to computehasNextwithout running an expensive extraSELECT COUNT(*)query across big tables.
- Silent failure masquerading as empty data: When the database is unreachable or times out, catching
Refactored DTOs, controller, and service layer
Putting the refactored architecture together separates HTTP transport, business logic, and persistence cleanly:
HTTP Client | POST / GET /api/accounts/{accountId}/orders v OrderController (@Valid DTO validation, @PreAuthorize check, 201 + Location) | +---> ApiExceptionHandler (@RestControllerAdvice -> 400 / 503 ProblemDetail JSON) v OrderService (stateless singleton; fetches quote BEFORE DB write) | +---> PricingClient (@Bean singleton with pooled keep-alive connections & timeouts) +---> OrderRepository (Spring Data JPA; paginated Slice<Order> query)// Immutable request & response DTOs (decoupled from JPA entity) public record PlaceOrderRequest( @NotBlank @Size(max = 10) String ticker, @NotNull @Positive Integer quantity) { } public record OrderResponse( Long id, String accountId, String ticker, int quantity, BigDecimal executedPrice, Instant executedAt) { public static OrderResponse from(Order order) { return new OrderResponse( order.getId(), order.getAccountId(), order.getTicker(), order.getQuantity(), order.getExecutedPrice(), order.getExecutedAt()); } } public record OrderPage(List<OrderResponse> items, int page, int size, boolean hasNext) { } public interface OrderRepository extends JpaRepository<Order, Long> { Slice<Order> findByAccountId(String accountId, Pageable pageable); }@RestController @RequestMapping("/api/accounts/{accountId}/orders") public class OrderController { private final OrderService orderService; // Single constructor: final dependency, trivial to unit-test without Spring public OrderController(OrderService orderService) { this.orderService = orderService; } @PostMapping @PreAuthorize("@accountAccess.canTrade(authentication, #accountId)") public ResponseEntity<OrderResponse> placeOrder( @PathVariable String accountId, @Valid @RequestBody PlaceOrderRequest request) { OrderResponse created = orderService.placeOrder(accountId, request); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{orderId}") .buildAndExpand(created.id()) .toUri(); return ResponseEntity.created(location).body(created); // 201 Created + Location } @GetMapping @PreAuthorize("@accountAccess.canView(authentication, #accountId)") public OrderPage getHistory( @PathVariable String accountId, @PageableDefault(size = 50, sort = "executedAt", direction = Sort.Direction.DESC) Pageable pageable) { return orderService.getHistory(accountId, pageable); } }@Service public class OrderService { private final OrderRepository orderRepository; private final PricingClient pricingClient; private final Clock clock; public OrderService(OrderRepository orderRepository, PricingClient pricingClient, Clock clock) { this.orderRepository = orderRepository; this.pricingClient = pricingClient; this.clock = clock; } public OrderResponse placeOrder(String accountId, PlaceOrderRequest request) { // Fetch external quote OUTSIDE any DB transaction so DB connections never block on HTTP BigDecimal currentPrice = pricingClient.getQuote(request.ticker()); Order order = new Order(); order.setAccountId(accountId); order.setTicker(request.ticker()); order.setQuantity(request.quantity()); order.setExecutedPrice(currentPrice); order.setExecutedAt(Instant.now(clock)); Order saved = orderRepository.save(order); return OrderResponse.from(saved); } @Transactional(readOnly = true) public OrderPage getHistory(String accountId, Pageable pageable) { Slice<Order> slice = orderRepository.findByAccountId(accountId, pageable); List<OrderResponse> items = slice.getContent().stream() .map(OrderResponse::from) .toList(); return new OrderPage(items, slice.getNumber(), slice.getSize(), slice.hasNext()); } } @Configuration public class InfrastructureConfig { @Bean public PricingClient pricingClient() { // Instantiated ONCE at startup; configure connection pool and socket timeouts here return new PricingClient(); } @Bean public Clock clock() { return Clock.systemUTC(); } }Centralized error handling with @RestControllerAdvice
Instead of scattering
try/catchblocks across controllers, a single@RestControllerAdviceclass extendingResponseEntityExceptionHandlertranslates exceptions across all endpoints into standard RFC 9457ProblemDetailJSON responses:@RestControllerAdvice public class ApiExceptionHandler extends ResponseEntityExceptionHandler { private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class); // Override base handler to attach per-field validation messages on 400 Bad Request @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Map<String, String> fieldErrors = new LinkedHashMap<>(); for (FieldError err : ex.getBindingResult().getFieldErrors()) { fieldErrors.put(err.getField(), err.getDefaultMessage()); } ProblemDetail problem = ex.getBody(); problem.setProperty("errors", fieldErrors); return handleExceptionInternal(ex, problem, headers, status, request); } @ExceptionHandler(PricingUnavailableException.class) public ProblemDetail handlePricingUnavailable(PricingUnavailableException ex) { log.warn("Pricing service unavailable while placing order", ex); return ProblemDetail.forStatusAndDetail( HttpStatus.SERVICE_UNAVAILABLE, "Live pricing is temporarily unavailable; order was not placed."); } @ExceptionHandler({DataAccessResourceFailureException.class, TransientDataAccessException.class}) public ProblemDetail handleDatabaseUnavailable(DataAccessException ex) { log.error("Database unavailable during order request", ex); return ProblemDetail.forStatusAndDetail( HttpStatus.SERVICE_UNAVAILABLE, "Order service is temporarily unavailable. Please retry shortly."); } }Now sending
{"ticker": "AAPL", "quantity": 0}produces a clean, machine-readable400 Bad Requestbody instead of a misleading500:{ "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "Invalid request content.", "instance": "/api/accounts/ACC-101/orders", "errors": { "quantity": "must be greater than 0" } }
Intuition & how it works
Picture a Spring Boot @RestController as a single shared reception counter staffed simultaneously by 200 bank clerks (the HTTP worker threads). Because the controller is a singleton (one shared object instance for the entire application), leaving a mutable scratchpad like SimpleDateFormat on the counter means two clerks writing timestamps at the same millisecond overwrite each other's dates. Conversely, calling new PricingClient() inside placeOrder is like forcing a clerk to wire a brand-new telephone line from scratch for every single stock quote and toss the phone in the trash afterward.
The submitted controller fails in production on five fronts at once: shared SimpleDateFormat state corrupts trade timestamps under concurrency, per-request new PricingClient() wastes TCP/TLS handshakes and leaks sockets, placeOrder forgets to save accountId (so orders vanish from history) and uses imprecise double math for money, quantity <= 0 returns 500 while database crashes return 200 OK with [], and findAllByAccountId pulls unbounded rows into memory. Refactoring separates HTTP translation, business rules, and shared infrastructure so each layer has one safe job.
Walk through 3 concrete requests hitting the refactored design for account ACC-101:
1. Invalid order ({"ticker": "AAPL", "quantity": 0}): Bean Validation (@Valid + @Positive) rejects the DTO (Data Transfer Object, a dedicated Java record carrying JSON fields) before OrderService ever runs, and ApiExceptionHandler returns 400 Bad Request with "quantity": "must be greater than 0".
2. Valid order ({"ticker": "AAPL", "quantity": 10}): OrderController verifies ACC-101 ownership, OrderService fetches $189.50 as an exact BigDecimal from the shared singleton PricingClient before touching the database, saves the Order with accountId = "ACC-101" and UTC Instant.now(clock), and returns 201 Created with Location: /api/accounts/ACC-101/orders/42.
3. Order history (GET /api/accounts/ACC-101/orders?page=0&size=50): OrderService queries a bounded 50-row pagination slice sorted newest-first; if the database is down, the exception propagates to ApiExceptionHandler, logs an error, and returns 503 Service Unavailable instead of faking an empty [].
Key points
- Singleton controllers require immutable or thread-safe state: Never keep
SimpleDateFormator per-request fields on a controller or service; represent timestamps as UTCInstantvia an injectedClock(and use immutableDateTimeFormatterwhen custom formatting is needed). - Heavy network clients belong in singleton
@Beandefinitions: Injecting one configuredPricingClientvia constructor injection preserves HTTP keep-alive connection pools, centralizes timeouts, prevents socket leaks, and lets unit tests pass mocks effortlessly. - Financial correctness and security come first: Store
accountIdon every order so history queries actually find it, useBigDecimalinstead of binarydoubleto prevent one-cent rounding bugs, and verify caller authorization (@PreAuthorize) to block IDOR (Insecure Direct Object Reference, where changing an ID in the URL accesses someone else's data). - Honest HTTP semantics and centralized
@RestControllerAdvice: Use400 Bad Requestfor invalid input,201 Created+Locationfor new resources, and503 Service Unavailablefor downstream outages, formatted consistently as RFC 9457ProblemDetailJSON in one global advice class. - Always bound collection queries: Paginate history endpoints with
Pageable(with a strictmax-page-sizecap) andSlice<Order>(which checkshasNextby fetchingsize + 1rows without an expensiveCOUNT(*)scan). - Keep network I/O outside
@Transactional: Fetch the external stock quote before opening a database transaction so slow pricing responses never starve your HikariCP database connection pool.
Common mistakes
- Making
SimpleDateFormatstaticthinking that fixes concurrency: Astaticfield is still shared across all 200 Tomcat threads, so the exact same race condition remains; switch tojava.time.InstantandDateTimeFormatter. - Catching broad
Exceptionin@RestControllerAdviceand returning500for everything: That accidentally overrides Spring's built-in400(malformed JSON) and415(unsupported media type) responses; extendResponseEntityExceptionHandlerand handle specific exceptions instead. - Adding
@TransactionalaroundplaceOrderincludingpricingClient.getQuote(...): If the pricing service stalls for 2 seconds while 10 orders arrive concurrently, all 10 connections in a default 10-connection HikariCP pool sit idle waiting on HTTP, freezing unrelated read endpoints too. - Paginating without a maximum
sizecap: Allowing?size=5000000lets a single caller reintroduce the unbounded memory blowup; enforcespring.data.web.pageable.max-page-size(and use keyset cursor paginationWHERE executed_at < :cursorif users page thousands of rows deep). - Logging and rethrowing at repository, service, and controller layers: Printing the same stack trace three times floods log aggregators; log once at the
@RestControllerAdviceboundary where the HTTP error is produced. - Catching style nitpicks while missing the broken
accountIdlink: In code review interviews, spotting functional data-loss bugs (order.setAccountId(...)missing,catchreturning200 [],doublerounding) carries far more weight than syntax preferences alone.
Follow-up questions
- How can you make
placeOrderidempotent so client retries over a flaky network never execute duplicate trades? Require clients to send a uniqueIdempotency-Keyheader (a UUID generated once per user click and reused across network retries)—an idempotency key ensures repeating the same request has the exact same effect as running it once. Store(account_id, idempotency_key)in anidempotency_recordstable with aUNIQUEconstraint alongside a SHA-256 hash of the request payload, astatus(IN_PROGRESSorCOMPLETED), and the serialized response. When a request arrives, claim the row asIN_PROGRESSfirst: if the unique constraint already exists withCOMPLETEDand the same payload hash, replay the saved201 Createdresponse without placing a second trade; if the payload hash differs, return422 Unprocessable Content; if it is stillIN_PROGRESS(within a short lease such as 30 seconds), return409 Conflictso the client retries shortly. Finally, persist theOrderand update the idempotency row toCOMPLETEDinside the same database transaction so a crash between the two can never double-buy shares. - How would you verify controller routing, validation, and status codes with
@WebMvcTestandMockMvcwithout booting JPA or the full Spring context? Annotating the test class with@WebMvcTest(OrderController.class)boots only Spring's web slice (controllers,@RestControllerAdvice, Jackson JSON mappers, and@ValidBean Validation) in under a second without starting services, JPA repositories, or aDataSource. InjectMockMvcto send simulated HTTP requests in memory and replaceOrderServicewith@MockitoBean(or@MockBeanprior to Spring Boot 3.4): stubwhen(orderService.placeOrder(eq("ACC-101"), any())).thenReturn(savedDto)to assertstatus().isCreated(), theLocationheader, and JSON fields on valid JSON, and send{"ticker": "AAPL", "quantity": 0}to assertstatus().isBadRequest()plusverifyNoInteractions(orderService). When Spring Security is on the classpath, annotate tests with@WithMockUser(and.with(csrf())if CSRF is enabled) and@Importyour method-security helper bean to verify403 Forbiddenwhen a user requests someone else'saccountId. - How should you protect the service with client timeouts and a Resilience4j circuit breaker when
pricingClient.getQuote(...)slows down or hangs? By Little's Law (average concurrent in-flight requests equal arrival rate multiplied by response time), if orders arrive at50 req/sand a hung pricing socket blocks for30 s, concurrency tries to reach50 * 30 = 1,500, exhausting all200Tomcat threads in just200 / 50 = 4 secondsand freezing the entire service. First, set strict connection (300 ms) and read (800 ms) timeouts on the underlying HTTP client (or.timeout(Duration.ofMillis(800))onWebClient) so a single attempt blocks at most1.1 s(50 * 1.1 = 55threads). Next, wrapgetQuotewith a Resilience4j circuit breaker—a state machine that watches recent call failures and slow calls (for example, opening for10 swhenever>= 50%of the last20calls fail or exceed800 ms) and immediately throwsCallNotPermittedExceptionin microseconds instead of waiting on the network. Map that exception inApiExceptionHandlerto503 Service Unavailablerather than falling back to a stale cached stock price, because executing a market order at an outdated price is dangerous; if adding@Retry(at most 1 fast retry with jitter on read-onlygetQuote), keep total worst-case retry latency well below the caller's HTTP timeout.
Follow-up questions
- How can you make `placeOrder` idempotent so client retries over a flaky network never execute duplicate trades?
- How would you verify controller routing, validation, and status codes with `@WebMvcTest` and `MockMvc` without booting JPA or the full Spring context?
- How should you protect the service with client timeouts and a Resilience4j circuit breaker when `pricingClient.getQuote(...)` slows down or hangs?
Similar questions
- Spring IoC Lifecycle, Injection Trade-Offs, and Bean Wiring
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager