惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
小众软件
小众软件
V
V2EX
博客园 - Franky
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
量子位
博客园 - 【当耐特】
雷峰网
雷峰网
WordPress大学
WordPress大学
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
N
Netflix TechBlog - Medium
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
Visual Studio Blog
Microsoft Security Blog
Microsoft Security Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Spring Boot 3 and JVM Resilience in API Development: Avoi...
Nitish · 2026-06-15 · via DEV Community

Nitish

Spring Boot 3 and JVM Resilience in API Development: Avoiding JavaScript’s 2014 Pitfalls

Without proper thread pooling and structured error handling, your production APIs might face cascading failures under load—like Node.js applications did during JavaScript’s scalability debates in 2014—while Spring Boot’s thread-per-request model remains unmonitored and unoptimized.

Prerequisites

  • Java 17 or later
  • Spring Boot 3.2.4
  • Spring Web and Spring Data JPA dependencies
  • Docker 24.0+ and PostgreSQL 15 image
  • Postman or curl for API testing

Configuring Spring Boot for Concurrent Request Handling

Spring Boot’s default Tomcat configuration handles 100 simultaneous requests, but tuning is critical for high-throughput APIs. Add these dependencies to optimize thread pools and metrics:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

server.tomcat.threads.max=200
server.tomcat.threads.min-spare=20
management.endpoints.web.exposure.include=health,metrics,threaddump

  • server.tomcat.threads.max: Maximum worker threads for concurrent requests
  • management.endpoints.web.exposure.include: Enables actuator metrics for monitoring thread usage

Implementing Resilient Order Processing with @RestController

This REST controller uses Spring’s thread-per-request model to avoid JavaScript-style event-loop blocking, with explicit error handling for database failures:

package com.example.orderservice;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.dao.DataAccessException;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public String createOrder(@RequestBody OrderRequest request) {
        try {
            // Simulate database operation
            processOrder(request);
            return "Order processed";
        } catch (DataAccessException e) {
            throw new ServiceUnavailableException("Database write failed");
        }
    }

    private void processOrder(OrderRequest request) {
        // Business logic here
    }
}

@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
class ServiceUnavailableException extends RuntimeException {
    ServiceUnavailableException(String message) {
        super(message);
    }
}

Test with curl -X POST http://localhost:8080/orders -H "Content-Type: application/json" -d '{"productId": 123}'. Verify thread usage via /actuator/metrics/tomcat.threads.busy.

Dockerizing PostgreSQL for Spring Data JPA

# docker-compose.yml
version: '3.8'
services:
  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: orders
      POSTGRES_USER: spring
      POSTGRES_PASSWORD: secure
    ports:
      - "5432:5432"

Run docker-compose up before starting the Spring Boot app to ensure database connectivity.

Common Mistakes

Mistake 1: Blocking the main thread with synchronous I/O

// Wrong: Synchronous HTTP call in controller
String result = restTemplate.getForObject("https://slow-api", String.class);

// Fix: Offload to @Async service
@Async
public CompletableFuture<String> fetchExternalData() {
    return CompletableFuture.completedFuture(restTemplate.getForObject(...));
}

Synchronous calls in controllers exhaust worker threads. Use @Async with a configured task executor.

Mistake 2: Missing retries for transient database errors

// Wrong: No retry for JPA operations
orderRepository.save(order);

// Fix: Spring Retry with exponential backoff
@Retryable(retryFor = DataAccessException.class, maxAttempts = 3)
public void saveOrder(Order order) {
    orderRepository.save(order);
}

Add @EnableRetry and spring-retry dependency to recover from transient database issues.

Mistake 3: Overlooking connection pool limits

# Wrong: Default Hikari pool size
spring.datasource.hikari.maximum-pool-size=10

# Fix: Match pool to thread capacity
spring.datasource.hikari.maximum-pool-size=200

Too few database connections cause thread starvation. Align Hikari pool size to Tomcat’s threads.max.

Summary

  • Configure server.tomcat.threads.max to match expected concurrent users and monitor via /actuator/metrics
  • Use @Async with a custom ThreadPoolTaskExecutor for I/O-bound operations to prevent thread blocking
  • Set spring.datasource.hikari.maximum-pool-size equal to Tomcat threads to avoid database connection starvation

The author publishes Spring Boot starter templates at https://gumroad.com