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 @RestControllerAdvice error responses, financial data types, and pagination.
  • Present a clean, refactored Spring Boot controller, service layer, and global exception handler.

Step-by-step walkthrough

  1. 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 with new inside 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 SimpleDateFormat instance field Thread safety Corrupted trade timestamps or runtime exceptions under concurrent load
    2 new PricingClient() inside placeOrder Resource waste Destroys connection pooling; leaks sockets/threads; untestable
    3 order never sets accountId Domain correctness Newly placed orders never appear in getHistory(accountId)
    4 catch (Exception e) returns 200 OK with [] Exception handling Database outage looks like an empty order history; zero logs or alerts
    5 Returns 500 on quantity <= 0 and 200 string on create HTTP semantics False server-error pages on bad client input; missing 201 + Location
    6 findAllByAccountId has no pagination Scalability Large accounts load tens of thousands of rows at once, risking OutOfMemoryError
    7 Pricing, mapping, and persistence inside controller Layer abstraction Tightly coupled web/business/data logic; hard to reuse or test
    8 Field @Autowired, raw List/ResponseEntity, JPA entity exposed API & maintainability Hidden non-final dependencies; loses type safety; couples JSON to DB schema
    9 Stock price stored as double; zone-less timestamp String Financial precision Binary floating-point rounding errors on money; ambiguous timezones
    10 Missing @Valid input checks and account ownership check Validation & security Null inputs throw 500; any user can read another user's accountId
  2. Thread safety and financial data types

    1. Shared SimpleDateFormat corrupts timestamps across threads. SimpleDateFormat stores intermediate digits inside a mutable internal Calendar field while formatting. When two worker threads call dateFormat.format(...) on the singleton controller at the same millisecond, they overwrite each other's Calendar:

    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: delete SimpleDateFormat, inject a java.time.Clock, and record execution time as java.time.Instant (an exact UTC point serialized as ISO-8601, such as "2025-05-01T14:15:03Z"). If formatted strings are ever needed, DateTimeFormatter is immutable and completely thread-safe.

    2. double silently loses cents on money. IEEE-754 binary floating-point (double) cannot represent most base-10 fractions such as 0.01 or 19.99 exactly. For example, buying 100 shares at $19.99 in double computes 19.99 * 100 == 1998.9999999999998; truncating to two decimal places yields $1,998.99—one cent short! Fix: represent all prices and monetary amounts with BigDecimal (backed by DECIMAL(19, 4) in SQL).

    3. Missing accountId orphans every placed order. placeOrder sets ticker, quantity, price, and timestamp, yet never sets accountId—even though getHistory queries findAllByAccountId(accountId). Every saved order has accountId = null and never shows up in history! Fix: scope the endpoint under /api/accounts/{accountId}/orders, verify the authenticated caller is authorized for accountId, and persist accountId on the Order.

  3. 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 adds 35 ms and 2 MB of buffers per call, then at 100 orders/sec the service burns 100 * 0.035 s = 3.5 thread-seconds every second and allocates 200 MB/sec of avoidable garbage. - Socket and thread leaks: Heavy clients often spawn background connection-eviction threads and hold OS file descriptors. Because pricingClient is never closed, sockets accumulate until the pod crashes with Too many open files or OutOfMemoryError. - Untestable code: Calling new PricingClient() directly inside the method makes it impossible to pass a mock client in unit tests.

    Fix: register PricingClient once 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 an OrderService, and wire all dependencies via constructor injection with private final fields. Also make sure the network call pricingClient.getQuote(...) runs outside any @Transactional database block so database pool connections are never held idle waiting on external network I/O.

  4. 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 <= 0 is invalid client input, so return 400 Bad Request, never 500 Internal Server Error. Returning 500 tells load balancers, clients, and monitoring dashboards that the server itself crashed, triggering false on-call pages and wasteful client retries. On successful creation, return 201 Created with a Location header (/api/accounts/{accountId}/orders/{orderId}) and the created OrderResponse JSON body rather than 200 OK with a plain string.
    • Use noun-based resource paths: Replace /api/orders/create (which puts an action verb in the path when POST already means create) with /api/accounts/{accountId}/orders (POST to place an order, GET to list history).
    • Validate declaratively with Bean Validation (@Valid): If a client sends {} (quantity == null, ticker == null), request.getQuantity() <= 0 in the original code throws a NullPointerException when unboxing a null Integer! Annotating a Java record DTO with @NotBlank and @NotNull @Positive plus @Valid rejects malformed payloads automatically with 400 Bad Request before controller logic even runs.
    • Eliminate raw types and direct JPA entity returns: Replace raw ResponseEntity and List with ResponseEntity<OrderResponse> and OrderPage. Returning JPA Order entities directly leaks internal database columns and risks LazyInitializationException during 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.
  5. Exception swallowing and unbounded history pagination

    Look at getHistory in the original code:

    try {
        return orderRepository.findAllByAccountId(accountId);
    } catch (Exception e) {
        return new ArrayList();
    }
    

    This block has two severe production hazards:

    1. Silent failure masquerading as empty data: When the database is unreachable or times out, catching Exception and returning [] sends 200 OK with an empty JSON array. Customers see $0 / zero orders in their history, monitoring reports 100% healthy 200 responses, and nothing is written to error logs! Instead, let infrastructure exceptions propagate to a central @RestControllerAdvice that logs the error once and returns 503 Service Unavailable with a structured error payload.
    2. Unbounded result set: findAllByAccountId loads every historical order for that account into memory at once. Consider a frequent trader or institutional account with 50,000 orders at ~500 bytes of JSON per order: a single GET serializes 25 MB of JSON (plus tens of megabytes of Hibernate entity state). Just 20 concurrent refreshes pull 1,000,000 rows and 500 MB+ onto the JVM heap, starving worker threads and triggering OutOfMemoryError. Fix: paginate using Spring Data's Pageable (with a sensible default like size = 50 and a strict max page size cap via spring.data.web.pageable.max-page-size=200) and return a Slice<Order> sorted newest-first (executedAt DESC). Returning Slice fetches size + 1 rows to compute hasNext without running an expensive extra SELECT COUNT(*) query across big tables.
  6. 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();
        }
    }
    
  7. Centralized error handling with @RestControllerAdvice

    Instead of scattering try/catch blocks across controllers, a single @RestControllerAdvice class extending ResponseEntityExceptionHandler translates exceptions across all endpoints into standard RFC 9457 ProblemDetail JSON 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-readable 400 Bad Request body instead of a misleading 500:

    {
      "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 SimpleDateFormat or per-request fields on a controller or service; represent timestamps as UTC Instant via an injected Clock (and use immutable DateTimeFormatter when custom formatting is needed).
  • Heavy network clients belong in singleton @Bean definitions: Injecting one configured PricingClient via 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 accountId on every order so history queries actually find it, use BigDecimal instead of binary double to 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: Use 400 Bad Request for invalid input, 201 Created + Location for new resources, and 503 Service Unavailable for downstream outages, formatted consistently as RFC 9457 ProblemDetail JSON in one global advice class.
  • Always bound collection queries: Paginate history endpoints with Pageable (with a strict max-page-size cap) and Slice<Order> (which checks hasNext by fetching size + 1 rows without an expensive COUNT(*) 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 SimpleDateFormat static thinking that fixes concurrency: A static field is still shared across all 200 Tomcat threads, so the exact same race condition remains; switch to java.time.Instant and DateTimeFormatter.
  • Catching broad Exception in @RestControllerAdvice and returning 500 for everything: That accidentally overrides Spring's built-in 400 (malformed JSON) and 415 (unsupported media type) responses; extend ResponseEntityExceptionHandler and handle specific exceptions instead.
  • Adding @Transactional around placeOrder including pricingClient.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 size cap: Allowing ?size=5000000 lets a single caller reintroduce the unbounded memory blowup; enforce spring.data.web.pageable.max-page-size (and use keyset cursor pagination WHERE executed_at < :cursor if 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 @RestControllerAdvice boundary where the HTTP error is produced.
  • Catching style nitpicks while missing the broken accountId link: In code review interviews, spotting functional data-loss bugs (order.setAccountId(...) missing, catch returning 200 [], double rounding) carries far more weight than syntax preferences alone.

Follow-up questions

  • How can you make placeOrder idempotent so client retries over a flaky network never execute duplicate trades? Require clients to send a unique Idempotency-Key header (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 an idempotency_records table with a UNIQUE constraint alongside a SHA-256 hash of the request payload, a status (IN_PROGRESS or COMPLETED), and the serialized response. When a request arrives, claim the row as IN_PROGRESS first: if the unique constraint already exists with COMPLETED and the same payload hash, replay the saved 201 Created response without placing a second trade; if the payload hash differs, return 422 Unprocessable Content; if it is still IN_PROGRESS (within a short lease such as 30 seconds), return 409 Conflict so the client retries shortly. Finally, persist the Order and update the idempotency row to COMPLETED inside 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 @WebMvcTest and MockMvc without 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 @Valid Bean Validation) in under a second without starting services, JPA repositories, or a DataSource. Inject MockMvc to send simulated HTTP requests in memory and replace OrderService with @MockitoBean (or @MockBean prior to Spring Boot 3.4): stub when(orderService.placeOrder(eq("ACC-101"), any())).thenReturn(savedDto) to assert status().isCreated(), the Location header, and JSON fields on valid JSON, and send {"ticker": "AAPL", "quantity": 0} to assert status().isBadRequest() plus verifyNoInteractions(orderService). When Spring Security is on the classpath, annotate tests with @WithMockUser (and .with(csrf()) if CSRF is enabled) and @Import your method-security helper bean to verify 403 Forbidden when a user requests someone else's accountId.
  • 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 at 50 req/s and a hung pricing socket blocks for 30 s, concurrency tries to reach 50 * 30 = 1,500, exhausting all 200 Tomcat threads in just 200 / 50 = 4 seconds and 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)) on WebClient) so a single attempt blocks at most 1.1 s (50 * 1.1 = 55 threads). Next, wrap getQuote with a Resilience4j circuit breaker—a state machine that watches recent call failures and slow calls (for example, opening for 10 s whenever >= 50% of the last 20 calls fail or exceed 800 ms) and immediately throws CallNotPermittedException in microseconds instead of waiting on the network. Map that exception in ApiExceptionHandler to 503 Service Unavailable rather 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-only getQuote), keep total worst-case retry latency well below the caller's HTTP timeout.

Follow-up questions

Similar questions

More Schwab interview questions

All 2 Schwab questions →